diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md new file mode 100644 index 0000000..5a17f5a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -0,0 +1,30 @@ +--- +name: Report a bug +about: Issue tracker is used for reporting bugs +title: '' +labels: 'type:bug' +assignees: '' +--- + +#### Specifications + +Terp-Core version: `Terpd version` +OS & Version: Windows/Linux/OSX +Commit hash: + +#### Expected behavior + + +#### Actual behavior + + +#### Steps to reproduce the behavior + + +#### Backtrace + +```` +[backtrace] +```` + +When submitting logs: please submit them as text and not screenshots. diff --git a/.github/ISSUE_TEMPLATE/config.yaml b/.github/ISSUE_TEMPLATE/config.yaml new file mode 100644 index 0000000..a49eab2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yaml @@ -0,0 +1 @@ +blank_issues_enabled: true \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..b165f6a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,31 @@ + + +# Summary + + + +## Problem Definition + + + +## Proposal + + + +____ + +### For Admin Use + +- [ ] Not duplicate issue +- [ ] Appropriate labels applied +- [ ] Appropriate contributors tagged +- [ ] Contributor-assigned/self-assigned +- [ ] Is a spike necessary to map out how the issue should be approached? diff --git a/.github/ISSUE_TEMPLATE/issue.md b/.github/ISSUE_TEMPLATE/issue.md new file mode 100644 index 0000000..23175c9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/issue.md @@ -0,0 +1,27 @@ +--- +name: General issue +about: A template for general issues with acceptance criteria +title: '' +assignees: '' +--- + + +## Background + +> This is where you can provide code examples or context (e.g. past PR's) +> e.g. +> - The following PRs contributed to... + +## Suggested Design + +> Here, you can put concrete steps as to what to do next +> e.g. +> - create test file in... + +## Acceptance Criteria + +> Goals & criteria for success +> e.g. +> - all existing and new tests should pass diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cddd0d5..cbe476c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,6 +1,11 @@ --- -on: [push, pull_request] -name: Build +name: build + +on: + push: + paths: + - '**.go' + - 'go.sum' concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -15,8 +20,21 @@ jobs: - name: Setup go uses: actions/setup-go@v4 with: - go-version: "1.20" + go-version: 1.20.0 - run: go build ./... + + test: + runs-on: ubuntu-latest + name: test + steps: + - name: Install Go + uses: actions/setup-go@v3 + with: + go-version: 1.20.0 + - name: Checkout code + uses: actions/checkout@v3 + - name: Test + run: go test ./... tidy: runs-on: ubuntu-latest @@ -26,7 +44,7 @@ jobs: - name: Setup go uses: actions/setup-go@v4 with: - go-version: "1.20" + go-version: 1.20.0 - run: | go mod tidy CHANGES_IN_REPO=$(git status --porcelain) diff --git a/.github/workflows/docker.yml b/.github/workflows/build_docker.yml similarity index 80% rename from .github/workflows/docker.yml rename to .github/workflows/build_docker.yml index 527164a..d832b9b 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/build_docker.yml @@ -2,7 +2,14 @@ name: Build Docker Image on PR on: - pull_request: + push: + branches: + - master + - main + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} jobs: docker: diff --git a/.github/workflows/codacy.yml b/.github/workflows/codacy.yml deleted file mode 100644 index af5c62c..0000000 --- a/.github/workflows/codacy.yml +++ /dev/null @@ -1,61 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -# This workflow checks out code, performs a Codacy security scan -# and integrates the results with the -# GitHub Advanced Security code scanning feature. For more information on -# the Codacy security scan action usage and parameters, see -# https://github.com/codacy/codacy-analysis-cli-action. -# For more information on Codacy Analysis CLI in general, see -# https://github.com/codacy/codacy-analysis-cli. - -name: Codacy Security Scan - -on: - push: - branches: [ "main", "release/v*" ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ "main", "release/v*" ] - schedule: - - cron: '24 14 * * 5' - -permissions: - contents: read - -jobs: - codacy-security-scan: - permissions: - contents: read # for actions/checkout to fetch code - security-events: write # for github/codeql-action/upload-sarif to upload SARIF results - actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status - name: Codacy Security Scan - runs-on: ubuntu-latest - steps: - # Checkout the repository to the GitHub Actions runner - - name: Checkout code - uses: actions/checkout@v3 - - # Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis - - name: Run Codacy Analysis CLI - uses: codacy/codacy-analysis-cli-action@5cc54a75f9ad88159bb54046196d920e40e367a5 - with: - # Check https://github.com/codacy/codacy-analysis-cli#project-token to get your project token from your Codacy repository - # You can also omit the token and run the tools that support default configurations - project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} - verbose: true - output: results.sarif - format: sarif - # Adjust severity of non-security issues - gh-code-scanning-compat: true - # Force 0 exit code to allow SARIF file generation - # This will handover control about PR rejection to the GitHub side - max-allowed-issues: 2147483647 - - # Upload the SARIF file generated in the previous step - - name: Upload SARIF results file - uses: github/codeql-action/upload-sarif@v2 - with: - sarif_file: results.sarif \ No newline at end of file diff --git a/.github/workflows/codeql-analizer.yml b/.github/workflows/codeql-analyzer.yml similarity index 89% rename from .github/workflows/codeql-analizer.yml rename to .github/workflows/codeql-analyzer.yml index 05a9cac..77f3446 100644 --- a/.github/workflows/codeql-analizer.yml +++ b/.github/workflows/codeql-analyzer.yml @@ -1,35 +1,35 @@ -name: "Code Scanning - Action" - -on: - pull_request: - paths: - - "**.go" - push: - branches: [ main ] - paths: - - "**.go" - -jobs: - CodeQL-Build: - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - - steps: - - name: Checkout repository - uses: actions/checkout@v3.5.0 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v2 - with: - languages: 'go' - queries: crypto-com/cosmos-sdk-codeql@main,security-and-quality - - - name: Autobuild - uses: github/codeql-action/autobuild@v2 - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 +name: "Code Scanning - Action" + +on: + pull_request: + paths: + - "**.go" + push: + branches: [ main ] + paths: + - "**.go" + +jobs: + CodeQL-Build: + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + steps: + - name: Checkout repository + uses: actions/checkout@v3.5.0 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: 'go' + queries: crypto-com/cosmos-sdk-codeql@main,security-and-quality + + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 \ No newline at end of file diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index abfda20..40b385c 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,40 +1,58 @@ -name: "CodeQL" - -on: - pull_request: - paths: - - "**.go" - push: - branches: - - main - - release/v* - paths: - - "**.go" - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - - steps: - - name: Checkout repository - uses: actions/checkout@v3 - - uses: actions/setup-go@v4 - with: - go-version: "1.20" - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v2 - with: - languages: "go" - queries: crypto-com/cosmos-sdk-codeql@main,security-and-quality - - - name: Build - run: make build - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 \ No newline at end of file +name: "Code Scanning - Action" + +on: + pull_request: + paths: + - "**.go" + push: + branches: + - main + - release/** + paths: + - "**.go" + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + - uses: actions/setup-go@v4 + with: + go-version: 1.20.0 + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: "go" + queries: crypto-com/cosmos-sdk-codeql@main,security-and-quality + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + # - name: Autobuild + # uses: github/codeql-action/autobuild@v2 + # with: + # debug: true + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl + + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + - name: Build + run: make build + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml deleted file mode 100644 index f5c89e3..0000000 --- a/.github/workflows/dependency-review.yml +++ /dev/null @@ -1,20 +0,0 @@ -# Dependency Review Action -# -# This Action will scan dependency manifest files that change as part of a Pull Request, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging. -# -# Source repository: https://github.com/actions/dependency-review-action -# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement -name: 'Dependency Review' -on: [pull_request] - -permissions: - contents: read - -jobs: - dependency-review: - runs-on: ubuntu-latest - steps: - - name: 'Checkout Repository' - uses: actions/checkout@v3 - - name: 'Dependency Review' - uses: actions/dependency-review-action@v3 \ No newline at end of file diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 2a4c36b..2ae2c07 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -5,13 +5,13 @@ on: tags: - v* branches: - - release/v* + - master - main pull_request: + paths: + - '**.go' permissions: contents: read - # Optional: allow read access to pull request. Use with `only-new-issues` option. - # pull-requests: read concurrency: group: ${{ github.workflow }}-${{ github.ref }} @@ -24,7 +24,7 @@ jobs: steps: - uses: actions/setup-go@v4 with: - go-version: "1.20" + go-version: 1.20.0 - uses: actions/checkout@v3 - name: golangci-lint diff --git a/.github/workflows/interchaintest-E2E.yml b/.github/workflows/interchaintest-E2E.yml new file mode 100644 index 0000000..9a894e8 --- /dev/null +++ b/.github/workflows/interchaintest-E2E.yml @@ -0,0 +1,186 @@ +name: ictest E2E + +on: + push: + tags: + - '**' + branches: + - '**' + paths: + - '**.yml' + - '**.go' + - '**.mod' + - '**.sum' + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }}-e2e + GO_VERSION: 1.20.0 + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-and-push-image: + runs-on: ubuntu-latest + outputs: + branchTag: ${{ steps.meta.outputs.version }} + permissions: + contents: read + packages: write + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # We setup go & cache dependencies here. This way each child job + # does not have to reinstall all dependencies individually. + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - name: Download dependencies + run: | + go mod download + cd interchaintest && go mod download + + - name: Set up QEMU + uses: docker/setup-qemu-action@v2 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + + - name: Log in to the Container registry + uses: docker/login-action@v2 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@v4 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + + - name: Build and push Docker image + id: push + uses: docker/build-push-action@v4 + with: + context: . + platforms: linux/amd64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max + + # make terp-core:branchname here for all needs.build-and-push-image.outputs.branchTag + # then upload to github. Then download for each as a cache. This way its only built once + + # TODO: Add reusable job template here, just changing the `make` command for each + + test-terp-basic: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-basic + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-ibc: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - name: checkout chain + uses: actions/checkout@v2 + + - run: make ictest-ibc + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-upgrade: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-upgrade + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-ibchooks: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-ibchooks + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-pfm: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: checkout chain + uses: actions/checkout@v2 + + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - run: make ictest-pfm + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} + + test-terp-tokenfactory: + runs-on: ubuntu-latest + needs: build-and-push-image + steps: + - name: Setup Golang with cache + uses: magnetikonline/action-golang-cache@v4 + with: + go-version: ${{ env.GO_VERSION }} + id: go + + - name: checkout chain + uses: actions/checkout@v2 + + - run: make ictest-tokenfactory + env: + BRANCH_CI: ${{needs.build-and-push-image.outputs.branchTag}} \ No newline at end of file diff --git a/.github/workflows/proto-buf-publisher.yml b/.github/workflows/proto-buf-publisher.yml deleted file mode 100644 index b0684c9..0000000 --- a/.github/workflows/proto-buf-publisher.yml +++ /dev/null @@ -1,38 +0,0 @@ -name: Proto Buf Publishing - Action -# Protobuf runs buf (https://buf.build/) push updated proto files to https://buf.build/cosmwasm/wasmd -# This workflow is only run when a .proto file has been changed -on: - push: - branches: - - main - paths: - - 'proto/**' - - # Sequence of patterns matched against refs/tags - tags: - - "v[0-9]+.[0-9]+.[0-9]+.*" # Push events to matching v*, //i.e. v20.15.10, v0.27.0-rc1 - -jobs: - push: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3.5.0 - - uses: bufbuild/buf-setup-action@v1.17.0 - - # lint checks - - uses: bufbuild/buf-lint-action@v1 - with: - input: "proto" - - # TODO: Add this when project is more stable. - # backward compatibility breaking checks - #- uses: bufbuild/buf-breaking-action@v1 - # with: - # input: 'proto' - # against: 'https://github.com/terpnetwork/terp-core.git#branch=master' - - # publish proto files - - uses: bufbuild/buf-push-action@v1 - with: - input: 'proto' - buf_token: ${{ secrets.BUF_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/push-docker-image.yml b/.github/workflows/push-docker-image.yml new file mode 100644 index 0000000..6436aed --- /dev/null +++ b/.github/workflows/push-docker-image.yml @@ -0,0 +1,75 @@ +# This workflow pushes new terp docker images on every new tag. +# +# On every new `vX.Y.Z` tag the following images are pushed: +# +# terpnetwork/terp-core:vX.Y.Z # is pushed +# terpnetwork/terp-core:X.Y.Z # is pushed +# terpnetwork/terp-core:X.Y # is updated to X.Y.Z +# terpnetwork/terp-core:X # is updated to X.Y.Z +# terpnetwork/terp-core:latest # is updated to X.Y.Z +# +# terpnetwork/terp-core-e2e:vX.Y.Z # is pushed +# terpnetwork/terp-core-e2e:X.Y.Z # is pushed +# terpnetwork/terp-core-e2e:X.Y # is updated to X.Y.Z +# terpnetwork/terp-core-e2e:X # is updated to X.Y.Z +# terpnetwork/terp-core-e2e:latest # is updated to X.Y.Z +# +# All the images above have support for linux/amd64 and linux/arm64. +# +# Due to QEMU virtualization used to build multi-platform docker images +# this workflow might take a while to complete. + +name: Push Docker Images + +on: + release: + types: [published, created, edited] + push: + tags: + - 'v[0-9]+.[0-9]+.[0-9]+' # ignore rc + +jobs: + terp-images: + runs-on: ubuntu-latest + steps: + - + name: Check out the repo + uses: actions/checkout@v3 + - + name: Set up QEMU + uses: docker/setup-qemu-action@v2 + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to GitHub Container Registry + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + - + name: Parse tag + id: tag + run: | + VERSION=$(echo ${{ github.ref_name }} | sed "s/v//") + MAJOR_VERSION=$(echo $VERSION | cut -d '.' -f 1) + MINOR_VERSION=$(echo $VERSION | cut -d '.' -f 2) + PATCH_VERSION=$(echo $VERSION | cut -d '.' -f 3) + echo "VERSION=$VERSION" >> $GITHUB_ENV + echo "MAJOR_VERSION=$MAJOR_VERSION" >> $GITHUB_ENV + echo "MINOR_VERSION=$MINOR_VERSION" >> $GITHUB_ENV + echo "PATCH_VERSION=$PATCH_VERSION" >> $GITHUB_ENV + - + name: Build and push + id: build_push_image + uses: docker/build-push-action@v4 + with: + file: Dockerfile + context: . + push: true + platforms: linux/amd64,linux/arm64 + tags: | + ghcr.io/terpnetwork/terp-core:${{ env.MAJOR_VERSION }} + ghcr.io/terpnetwork/terp-core:${{ env.MAJOR_VERSION }}.${{ env.MINOR_VERSION }} + ghcr.io/terpnetwork/terp-core:${{ env.MAJOR_VERSION }}.${{ env.MINOR_VERSION }}.${{ env.PATCH_VERSION }} + ghcr.io/terpnetwork/terp-core:v${{ env.MAJOR_VERSION }}.${{ env.MINOR_VERSION }}.${{ env.PATCH_VERSION }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..8df5eb6 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,35 @@ +--- +name: release binary + +on: + release: + types: [created] + +jobs: + release-alpine-static: + permissions: write-all + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Docker compose + run: STAKE_TOKEN="uterp" TIMEOUT_COMMIT=500ms docker-compose up -d + + - name: Copy binary + run: docker cp terpd_node_1:/usr/bin/terpd ./terpd + + - name: Save sha256 sum + run: sha256sum ./terpd > ./terpd_sha256.txt + + - name: Release + uses: softprops/action-gh-release@v1 + with: + token: ${{ github.token }} + files: | + terpd + terpd_sha256.txt + + - name: Dump docker logs on failure + if: failure() + uses: jwalton/gh-docker-logs@v2 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml deleted file mode 100644 index 183d99e..0000000 --- a/.github/workflows/tests.yml +++ /dev/null @@ -1,21 +0,0 @@ ---- -on: [push, pull_request] -name: Test - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - test: - runs-on: ubuntu-latest - name: test - steps: - - name: Install Go - uses: actions/setup-go@v3 - with: - go-version: "1.20" - - name: Checkout code - uses: actions/checkout@v3 - - name: Test - run: go test ./... \ No newline at end of file diff --git a/.github/workflows/tests.yml.archive b/.github/workflows/tests.yml.archive new file mode 100644 index 0000000..1d9a136 --- /dev/null +++ b/.github/workflows/tests.yml.archive @@ -0,0 +1,21 @@ +# --- +# on: [push, pull_request] +# name: Test + +# concurrency: +# group: ${{ github.workflow }}-${{ github.ref }} +# cancel-in-progress: true + +# jobs: +# test: +# runs-on: ubuntu-latest +# name: test +# steps: +# - name: Install Go +# uses: actions/setup-go@v3 +# with: +# go-version: "1.20" +# - name: Checkout code +# uses: actions/checkout@v3 +# - name: Test +# run: go test ./... \ No newline at end of file diff --git a/.gitignore b/.gitignore index f5f5405..4038110 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ examples/build/* docs/_build docs/tutorial dist +heighliner* tools-stamp docs/node_modules diff --git a/.golangci.yml b/.golangci.yml index b880fa4..c06683f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -61,4 +61,19 @@ linters-settings: allow-unused: false allow-leading-space: true require-explanation: false - require-specific: false \ No newline at end of file + require-specific: false + gci: + custom-order: true + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - blank # blank imports + - dot # dot imports + - prefix(github.com/cometbft/cometbft) + - prefix(github.com/cosmos) + - prefix(cosmossdk.io) + - prefix(github.com/cosmos/cosmos-sdk) + - prefix(github.com/terpnetwork/terp-core) + gosec: + excludes: + - G404 \ No newline at end of file diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..b2ffb15 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,31 @@ +# Install: +# - pip install pre-commit && pre-commit install +# +# VSCode Extension: +# - ext install MarkLarah.pre-commit-vscode +# +# On new hooks added here: +# - pre-commit run --all-files + +repos: +- repo: local + hooks: + - id: go-mod-tidy + name: "go mod tidy" + files: go.* + entry: ./scripts/git/tidy.sh + language: "script" + + - id: golangci-lint + name: "lint" + files: .*go + entry: ./scripts/git/linter.sh + require_serial: true + language: "script" + + - id: markdown-lint + name: "markdown linter" + files: .*md + entry: ./scripts/git/markdown_lint.sh + require_serial: true + language: "script" diff --git a/.sonarcloud.properties b/.sonarcloud.properties deleted file mode 100644 index 39468de..0000000 --- a/.sonarcloud.properties +++ /dev/null @@ -1,5 +0,0 @@ -# see https://docs.sonarcloud.io/advanced-setup/automatic-analysis/ -sonar.sources=. -sonar.exclusions=**/tests/**,**/benchmarks/**,**/ibctesting/**,**/wasmtesting/**,**/simulation/**,**/testdata/**,**/*.pb.go,**/*.pb.gw.go,**/*.test.go,**/test_*.go,**/*_fixtures.go,**/mock_*.go,**/*_mock.go - -sonar.tests=. diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index ad4edda..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,482 +0,0 @@ -# Changelog - -## [Unreleased](https://github.com/CosmWasm/wasmd/tree/HEAD) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.30.0...HEAD) - -## [v0.30.0](https://github.com/CosmWasm/wasmd/tree/v0.30.0) (2022-12-02) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.29.2...v0.30.0) - -- Provide source, builder and codehash information in store code proposal message[\#1072](https://github.com/CosmWasm/wasmd/pull/1072) -- Add new CLI query/ endpoint to get contracts by creator address [\#998](https://github.com/CosmWasm/wasmd/pull/998) -- Upgrade to Go v1.19 [\#1044](https://github.com/CosmWasm/wasmd/pull/1044) -- Upgrade to Cosmos-sdk to v0.45.11 [/#1096](https://github.com/CosmWasm/wasmd/pull/1096/) -- Upgrade to IBC v4.2.0 with interchain-accounts v0.2.4 [\#1088](https://github.com/CosmWasm/wasmd/pull/1088) -- Preserve contract history/ created date on genesis import [\#878](https://github.com/CosmWasm/wasmd/issues/878) -- Authz module integration - more granularity for WasmExecuteMsg authorizations [\#803](https://github.com/CosmWasm/wasmd/issues/803) -- StoreAndInstantiate gov proposal [\#785](https://github.com/CosmWasm/wasmd/issues/785) -- Start developer guide for contributors [\#654](https://github.com/CosmWasm/wasmd/issues/654) - -### Notable changes - -- IBC fee middleware is setup in `app.go`. Please note that it can be enabled with new channels only. A nice read is this [article](https://medium.com/the-interchain-foundation/ibc-relaying-as-a-service-the-in-protocol-incentivization-story-2c008861a957). -- Authz for wasm contracts can be granted via `wasmd tx wasm grant` and executed via `wasmd tx authz exec` command -- Go v1.19 required to prevent a mixed chain setup with older versions. Just to be on the safe side. -- Store code proposal types have new metadata fields added that can help to build client side tooling to verify the wasm contract in the proposal - -### Migration notes - -- The wasmd module version was bumped and a [state migration](https://github.com/CosmWasm/wasmd/pull/1021/files#diff-4357c2137e24f583b8f852cc210320cb71af18e2fdfb8c21b55d8667cfe54690R20) registered. -- See ibc-go [migration notes](https://github.com/cosmos/ibc-go/blob/v4.2.0/docs/migrations) -- See interchain-accounts [`MsgRegisterAccount.Version` field](https://github.com/cosmos/interchain-accounts-demo/compare/v0.1.0...v0.2.4#diff-ac8bca25810de6d3eef95f74fc9acf2223f3687822e6227b584e0d3b40db6566). Full diff [v0.1.0 to v0.2.4](https://github.com/cosmos/interchain-accounts-demo/compare/v0.1.0...v0.2.4) - -## [v0.29.2](https://github.com/CosmWasm/wasmd/tree/v0.29.2) (2022-11-08) - -- Fixes missing instantiate-anyof-addresses flag declaration for gov [/#1084](https://github.com/CosmWasm/wasmd/issues/1084) - -## [v0.29.1](https://github.com/CosmWasm/wasmd/tree/v0.29.1) (2022-10-14) - -- Upgrade to Cosmos-sdk to v45.9 [/#1052](https://github.com/CosmWasm/wasmd/pull/1052/) - -## [v0.29.0](https://github.com/CosmWasm/wasmd/tree/v0.29.0) (2022-10-10) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.28.0...v0.29.0) - -- Add dependencies for protobuf and remove third_party forlder [/#1030](https://github.com/CosmWasm/wasmd/pull/1030) -- Check wasmvm version on startup [\#1029](https://github.com/CosmWasm/wasmd/pull/1029/) -- Allow AccessConfig to use a list of addresses instead of just a single address [\#945](https://github.com/CosmWasm/wasmd/issues/945) -- Make contract addresses predictable \("deterministic"\) [\#942](https://github.com/CosmWasm/wasmd/issues/942) -- Add query for the total supply of a coin [\#903](https://github.com/CosmWasm/wasmd/pull/903) ([larry0x](https://github.com/larry0x)) -- Upgrade go to v1.18 [\#866] ([faddat](https://github.com/faddat)) -- Upgrade to ibc-go v3.3.0 REQUIRES [MIGRATION](https://github.com/cosmos/ibc-go/blob/v3.2.3/docs/migrations/support-denoms-with-slashes.md) [\#1016](https://github.com/CosmWasm/wasmd/pull/1016) -- Upgrade to cosmos-sdk v0.45.8 [\#964](https://github.com/CosmWasm/wasmd/pull/964/) ([faddat](https://github.com/faddat)) -- Upgrade wasmvm to v1.1.1 [\#1012](https://github.com/CosmWasm/wasmd/pull/1012), see [wasmvm v1.1.1](https://github.com/CosmWasm/wasmvm/releases/tag/v1.1.1) -- Add documentation how to add x/wasm to a new Cosmos SDK chain [\#876](https://github.com/CosmWasm/wasmd/issues/876) -- Upgrade keyring / go-keychain dependencies (removes deprecate warning) [\#957](https://github.com/CosmWasm/wasmd/issues/957) -- Make contract pinning an optional field in StoreCode proposals [\#972](https://github.com/CosmWasm/wasmd/issues/972) -- Add gRPC query for WASM params [\#889](https://github.com/CosmWasm/wasmd/issues/889) -- Expose Keepers in app.go? [\#881](https://github.com/CosmWasm/wasmd/issues/881) -- Remove unused `flagProposalType` flag in gov proposals [\#849](https://github.com/CosmWasm/wasmd/issues/849) -- Restrict code access config modifications [\#901](https://github.com/CosmWasm/wasmd/pull/901) -- Prevent migration to a restricted code [\#900](https://github.com/CosmWasm/wasmd/pull/900) -- Charge gas to unzip wasm code [\#898](https://github.com/CosmWasm/wasmd/pull/898) - -### Notable changes - -- BaseAccount and pruned vesting account types can be re-used for contracts addresses -- A new [MsgInstantiateContract2](https://github.com/CosmWasm/wasmd/pull/1014/files#diff-bf58b9da4b674719f07dd5421c532c1ead13a15f8896b59c1f724215d2064b73R75) was introduced which is an additional value for `message` type events -- Store event contains a new attribute with the code checksum now -- New `wasmd tx wasm instantiate2` CLI command for predictable addresses on instantiation -- New `cosmwasm_1_1` CosmWasm capability (former "feature") was introduced in [cosmwasm/#1356](https://github.com/CosmWasm/cosmwasm/pull/1356) to support total supply queries -- Protobuf files are published to [buf.build](https://buf.build/cosmwasm/wasmd/docs/main:cosmwasm.wasm.v1) - -### Migration notes - -- See ibc-go [migration notes](https://github.com/cosmos/ibc-go/blob/v3.3.0/docs/migrations/support-denoms-with-slashes.md) - -## [v0.28.0](https://github.com/CosmWasm/wasmd/tree/v0.28.0) (2022-07-29) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.27.0...v0.28.0) - -**API Breaking** - -No - -**Fixed Bugs** - -- Fix: Make events in reply completely determinisitic by stripping out anything coming from Cosmos SDK (not CosmWasm codebase) [\#917](https://github.com/CosmWasm/wasmd/pull/917) ([assafmo](https://github.com/assafmo)) - -Migration notes: - -- Contracts can no longer parse events from any calls except if they call another contract (or instantiate it, migrate it, etc). -The main issue here is likely "Custom" queries from a blockchain, which want to send info (eg. how many tokens were swapped). -Since those custom bindings are maintained by the chain, they can use the data field to pass any deterministic information -back to the contract. We recommend using JSON encoding there with some documented format the contracts can parse out easily. -- For possible non-determinism issues, we also sort all attributes in events. Better safe than sorry. - -## [v0.27.0](https://github.com/CosmWasm/wasmd/tree/v0.27.0) (2022-05-19) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.26.0...v0.27.0) - -**API Breaking** -Yes - -**Fixed bugs:** - -- Fix: allow no admin in instantiation through proposal [\#828](https://github.com/CosmWasm/wasmd/pull/828) ([jhernandezb](https://github.com/jhernandezb)) -- Fix SudoContractProposal and ExecuteContractProposal [\#808](https://github.com/CosmWasm/wasmd/pull/808) ([the-frey](https://github.com/the-frey)) - -**Implemented Enhancements** - -- Add UpdateInstantiateConfig governance proposal [\#820](https://github.com/CosmWasm/wasmd/pull/796) ([jhernandezb](https://github.com/jhernandezb)) -- Upgrade wasmvm to v1.0.0 [\#844](https://github.com/CosmWasm/wasmd/pull/844) and [\#858](https://github.com/CosmWasm/wasmd/pull/858) -- Support state sync [\#478](https://github.com/CosmWasm/wasmd/issues/478) -- Upgrade to ibc-go v3 [\#806](https://github.com/CosmWasm/wasmd/issues/806) -- Initial ICA integration [\#837](https://github.com/CosmWasm/wasmd/pull/837) ([ethanfrey](https://github.com/ethanfrey)) -- Consolidate MaxWasmSize constraints into a single var [\#826](https://github.com/CosmWasm/wasmd/pull/826) -- Add AccessConfig to CodeInfo query response [\#829](https://github.com/CosmWasm/wasmd/issues/829) -- Bump sdk to v0.45.4 [\#818](https://github.com/CosmWasm/wasmd/pull/818) ([alpe](https://github.com/alpe)) -- Bump buf docker image to fix proto generation issues [\#820](https://github.com/CosmWasm/wasmd/pull/820) ([alpe](https://github.com/alpe)) -- Add MsgStoreCode and MsgInstantiateContract support to simulations [\#831](https://github.com/CosmWasm/wasmd/pull/831) ([pinosu](https://github.com/pinosu)) - -**Implemented Enhancements** - -- Make MaxLabelSize a var not const [\#822](https://github.com/CosmWasm/wasmd/pull/822) - -## [v0.26.0](https://github.com/CosmWasm/wasmd/tree/v0.26.0) (2022-04-21) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.25.0...v0.26.0) - -**Fixed bugs:** - -- Unpack contract details from genesis [\#802](https://github.com/CosmWasm/wasmd/pull/802) - -**Closed issues:** - -- Issue Updating uploadAccess Param [\#804](https://github.com/CosmWasm/wasmd/issues/804) -- Add tx query to wasmd QueryPlugins for smart contract [\#788](https://github.com/CosmWasm/wasmd/issues/788) - -**Merged pull requests:** - -- Disable stargate queries [\#812](https://github.com/CosmWasm/wasmd/pull/812) -- Gov param change examples [\#805](https://github.com/CosmWasm/wasmd/pull/805) -- Create link to SECURITY.md in other repo [\#801](https://github.com/CosmWasm/wasmd/pull/801) -- Tests some event edge cases [\#799](https://github.com/CosmWasm/wasmd/pull/799) - -## [v0.25.0](https://github.com/CosmWasm/wasmd/tree/v0.25.0) (2022-04-06) - -**API Breaking** - -- Upgrade wasmvm to v1.0.0-beta10 [\#790](https://github.com/CosmWasm/wasmd/pull/790), [\#800](https://github.com/CosmWasm/wasmd/pull/800) - -**Implemented Enhancements** - -- Fix: close iterators [\#792](https://github.com/CosmWasm/wasmd/pull/792) -- Use callback pattern for contract state iterator [\#794](https://github.com/CosmWasm/wasmd/pull/794) -- Bump github.com/stretchr/testify from 1.7.0 to 1.7.1 [\#787](https://github.com/CosmWasm/wasmd/pull/787) -- Bump github.com/cosmos/ibc-go/v2 from 2.0.3 to 2.2.0 [\#786](https://github.com/CosmWasm/wasmd/pull/786) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.24.0...v0.25.0) - -## [v0.24.0](https://github.com/CosmWasm/wasmd/tree/v0.24.0) (2022-03-09) - -**API Breaking** - -- Add cosmwasm project prefix to REST query paths [\#743](https://github.com/CosmWasm/wasmd/issues/743) -- Add support for old contract addresses of length 20 [\#758](https://github.com/CosmWasm/wasmd/issues/758) -- Update wasmvm to 1.0.0-beta7 (incl wasmer 2.2) [\#774](https://github.com/CosmWasm/wasmd/issues/774) - -**Fixed bugs** - -- Add missing colons in String of some proposals [\#752](https://github.com/CosmWasm/wasmd/pull/752) -- Replace custom codec with SDK codec (needed for rosetta) [\#760](https://github.com/CosmWasm/wasmd/pull/760) -- Support `--no-admin` flag on cli for gov instantiation [\#771](https://github.com/CosmWasm/wasmd/pull/771) - -**Implemented Enhancements** - -- Add support for Buf Build [\#753](https://github.com/CosmWasm/wasmd/pull/753), [\#755](https://github.com/CosmWasm/wasmd/pull/755), [\#756](https://github.com/CosmWasm/wasmd/pull/756) -- Redact most errors sent to contracts, for better determinism guarantees [\#765](https://github.com/CosmWasm/wasmd/pull/765), [\#775](https://github.com/CosmWasm/wasmd/pull/775) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.23.0...v0.24.0) - -## [v0.23.0](https://github.com/CosmWasm/wasmd/tree/v0.23.0) (2022-01-28) - -**Fixed bugs** - -- Set end block order [\#736](https://github.com/CosmWasm/wasmd/issues/736) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.22.0...v0.23.0) - -## [v0.22.0](https://github.com/CosmWasm/wasmd/tree/v0.22.0) (2022-01-20) - -**Api Breaking:** - -- Upgrade to cosmos-sdk v0.45.0 [\#717](https://github.com/CosmWasm/wasmd/pull/717) -- Upgrade wasmvm to v1.0.0-beta5 [\#714](https://github.com/CosmWasm/wasmd/pull/714) - -**Implemented Enhancements:** - -- Use proper SystemError::NoSuchContract on ContractInfo if missing [\#687](https://github.com/CosmWasm/wasmd/issues/687) -- Benchmark tests flickering: directory not empty [\#659](https://github.com/CosmWasm/wasmd/issues/659) -- Implement PinCode and UnpinCode proposal client handlers [\#707](https://github.com/CosmWasm/wasmd/pull/707) ([orkunkl](https://github.com/orkunkl)) -- Use replace statements to enforce consistent versioning. [\#692](https://github.com/CosmWasm/wasmd/pull/692) ([faddat](https://github.com/faddat)) -- Fixed circleci by removing the golang executor from a docker build -- Go 1.17 provides a much clearer go.mod file [\#679](https://github.com/CosmWasm/wasmd/pull/679) ([faddat](https://github.com/faddat)) -- Autopin wasm code uploaded by gov proposal [\#726](https://github.com/CosmWasm/wasmd/pull/726) ([ethanfrey](https://github.com/ethanfrey)) -- You must explicitly declare --no-admin on cli instantiate if that is what you want [\#727](https://github.com/CosmWasm/wasmd/pull/727) ([ethanfrey](https://github.com/ethanfrey)) -- Add governance proposals for Wasm Execute and Sudo [\#730](https://github.com/CosmWasm/wasmd/pull/730) ([ethanfrey](https://github.com/ethanfrey)) -- Remove unused run-as flag from Wasm Migrate proposals [\#730](https://github.com/CosmWasm/wasmd/pull/730) ([ethanfrey](https://github.com/ethanfrey)) -- Expose wasm/Keeper.SetParams [\#732](https://github.com/CosmWasm/wasmd/pull/732) ([ethanfrey](https://github.com/ethanfrey)) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.21.0...v0.22.0) - -## [v0.21.0](https://github.com/CosmWasm/wasmd/tree/v0.21.0) (2021-11-17) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.20.0...v0.21.0) - -**Fixed bugs + Api Breaking:** - -- Prevent infinite gas consumption in simulation queries [\#670](https://github.com/CosmWasm/wasmd/issues/670) -- Amino JSON representation of inner message in Msg{Instantiate,Migrate,Execute}Contract [\#642](https://github.com/CosmWasm/wasmd/issues/642) - -**Implemented Enhancements:** - -- Bump wasmvm to v1.0.0-beta2 [\#676](https://github.com/CosmWasm/wasmd/pull/676) -- Add Benchmarks to compare with native modules [\#635](https://github.com/CosmWasm/wasmd/issues/635) -- Document M1 is not supported [\#653](https://github.com/CosmWasm/wasmd/issues/653) -- Open read access to sequences [\#669](https://github.com/CosmWasm/wasmd/pull/669) -- Remove unused flags from command prompt for storing contract [\#647](https://github.com/CosmWasm/wasmd/issues/647) -- Ran `make format` [\#649](https://github.com/CosmWasm/wasmd/issues/649) -- Add golangci lint check to circleci jobs [\620](https://github.com/CosmWasm/wasmd/issues/620) -- Updated error log statements in initGenesis for easier debugging: [\#643](https://github.com/CosmWasm/wasmd/issues/643) -- Bump github.com/cosmos/iavl from 0.17.1 to 0.17.2 [\#673](https://github.com/CosmWasm/wasmd/pull/673) -- Bump github.com/rs/zerolog from 1.25.0 to 1.26.0 [\#666](https://github.com/CosmWasm/wasmd/pull/666) - -## [v0.20.0](https://github.com/CosmWasm/wasmd/tree/v0.20.0) (2021-10-08) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.19.0...v0.20.0) - -**Fixed bugs:** - -- Add capabilities to begin block [\#626](https://github.com/CosmWasm/wasmd/pull/626) - -**Api Breaking:** - -- Update to wasmvm 1.0.0-soon2 [\#624](https://github.com/CosmWasm/wasmd/issues/624) - -**Implemented Enhancements:** - -- Upgrade Cosmos-sdk v0.42.10 [\#627](https://github.com/CosmWasm/wasmd/pull/627) ([alpe](https://github.com/alpe)) -- Add transaction index implemented as counter [\#601](https://github.com/CosmWasm/wasmd/issues/601) -- Fix inconsistent return of `contractAddress` from `keeper/init()`? [\#616](https://github.com/CosmWasm/wasmd/issues/616) -- Query pinned wasm codes [\#596](https://github.com/CosmWasm/wasmd/issues/596) -- Doc IBC Events [\#593](https://github.com/CosmWasm/wasmd/issues/593) -- Allow contract Info query from the contract [\#584](https://github.com/CosmWasm/wasmd/issues/584) -- Revisit reply gas costs for submessages. [\#450](https://github.com/CosmWasm/wasmd/issues/450) -- Benchmarks for gas pricing [\#634](https://github.com/CosmWasm/wasmd/pull/634) -- Treat all contracts as pinned for gas costs in reply [\#630](https://github.com/CosmWasm/wasmd/pull/630) -- Bump github.com/spf13/viper from 1.8.1 to 1.9.0 [\#615](https://github.com/CosmWasm/wasmd/pull/615) - -## [v0.19.0](https://github.com/CosmWasm/wasmd/tree/v0.19.0) (2021-09-15) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.18.0...v0.19.0) - -**Fixed bugs:** - -- Ensure Queries are executed read only [\#610](https://github.com/CosmWasm/wasmd/issues/610) -- Fix bug in query handler initialization on reply [\#604](https://github.com/CosmWasm/wasmd/issues/604) - -**Api Breaking:** - -- Bump Go version to 1.16 [\#612](https://github.com/CosmWasm/wasmd/pull/612) - -**Implemented Enhancements:** - -- Ensure query isolation [\#611](https://github.com/CosmWasm/wasmd/pull/611) -- Optimize BalanceQuery [\#609](https://github.com/CosmWasm/wasmd/pull/609) -- Bump wasmvm to v0.16.1 [\#605](https://github.com/CosmWasm/wasmd/pull/605) -- Bump github.com/rs/zerolog from 1.23.0 to 1.25.0 [\#603](https://github.com/CosmWasm/wasmd/pull/603) -- Add decorator options [\#598](https://github.com/CosmWasm/wasmd/pull/598) -- Bump github.com/spf13/cast from 1.4.0 to 1.4.1 [\#592](https://github.com/CosmWasm/wasmd/pull/592) - -## [v0.18.0](https://github.com/CosmWasm/wasmd/tree/v0.18.0) (2021-08-16) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.17.0...v0.18.0) - -**Api Breaking:** - -- Events documented and refactored [\#448](https://github.com/CosmWasm/wasmd/issues/448), [\#589](https://github.com/CosmWasm/wasmd/pull/589), [\#587](https://github.com/CosmWasm/wasmd/issues/587) -- Add organisation to grpc gateway path [\#578](https://github.com/CosmWasm/wasmd/pull/578) -- Move Proto version from `v1beta1` to `v1` for all cosmwasm.wasm.* types - [\#563](https://github.com/CosmWasm/wasmd/pull/563) -- Renamed InitMsg and MigrateMsg fields to Msg. This applies to protobuf Msg - and Proposals, as well as REST and CLI [\#563](https://github.com/CosmWasm/wasmd/pull/563) -- Removed source and builder fields from StoreCode and CodeInfo. They were rarely used. - [\#564](https://github.com/CosmWasm/wasmd/pull/564) -- Changed contract address derivation function. If you hardcoded the first contract - addresses anywhere (in scripts?), please update them. - [\#565](https://github.com/CosmWasm/wasmd/pull/565) - -**Implemented Enhancements:** - -- Cosmos SDK 0.42.9, wasmvm 0.16.0 [\#582](https://github.com/CosmWasm/wasmd/pull/582) -- Better ibc contract interface [\#570](https://github.com/CosmWasm/wasmd/pull/570) ([ethanfrey](https://github.com/ethanfrey)) -- Reject invalid events/attributes returned from contracts [\#560](https://github.com/CosmWasm/wasmd/pull/560) -- IBC Query methods from Wasm contracts only return OPEN channels [\#568](https://github.com/CosmWasm/wasmd/pull/568) -- Extendable gas costs [\#525](https://github.com/CosmWasm/wasmd/issues/525) -- Limit init/migrate/execute payload message size [\#203](https://github.com/CosmWasm/wasmd/issues/203) -- Add cli alias [\#496](https://github.com/CosmWasm/wasmd/issues/496) -- Remove max gas limit [\#529](https://github.com/CosmWasm/wasmd/pull/529) ([alpe](https://github.com/alpe)) -- Add SECURITY.md [\#303](https://github.com/CosmWasm/wasmd/issues/303) - -## [v0.17.0](https://github.com/CosmWasm/wasmd/tree/v0.17.0) (2021-05-26) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.16.0...v0.17.0) - -**Features:** - -- Remove json type cast for contract msgs [\#520](https://github.com/CosmWasm/wasmd/pull/520) ([alpe](https://github.com/alpe)) -- Bump github.com/cosmos/cosmos-sdk from 0.42.4 to 0.42.5 [\#519](https://github.com/CosmWasm/wasmd/pull/519) ([dependabot-preview[bot]](https://github.com/apps/dependabot-preview)) - -## [v0.16.0](https://github.com/CosmWasm/wasmd/tree/v0.16.0) (2021-04-30) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.15.1...v0.16.0) - -**Features:** - -- Upgrade to wasmvm v0.14.0-rc1 [\#508](https://github.com/CosmWasm/wasmd/pull/508) ([alpe](https://github.com/alpe)) -- Use the cache metrics from WasmVM [\#500](https://github.com/CosmWasm/wasmd/issues/500) -- Update IBC.md [\#494](https://github.com/CosmWasm/wasmd/pull/494) ([ethanfrey](https://github.com/ethanfrey)) -- Extend ContractInfo for custom data [\#492](https://github.com/CosmWasm/wasmd/pull/492) ([alpe](https://github.com/alpe)) -- Reply response on submessages can overwrite "caller" result [\#495](https://github.com/CosmWasm/wasmd/issues/495) -- Update to sdk 0.42.4 [\#485](https://github.com/CosmWasm/wasmd/issues/485) -- Add extension points to the CLI [\#477](https://github.com/CosmWasm/wasmd/pull/477) ([alpe](https://github.com/alpe)) -- Simplify staking reward query [\#399](https://github.com/CosmWasm/wasmd/issues/399) -- Update IBC.md [\#398](https://github.com/CosmWasm/wasmd/issues/398) -- Add IBCQuery support [\#434](https://github.com/CosmWasm/wasmd/issues/434) -- Follow proto dir best practice \(in cosmos eco\) [\#342](https://github.com/CosmWasm/wasmd/issues/342) -- Remove internal package [\#464](https://github.com/CosmWasm/wasmd/pull/464) ([alpe](https://github.com/alpe)) -- Introduce new interfaces for extendability [\#471](https://github.com/CosmWasm/wasmd/pull/471) ([alpe](https://github.com/alpe)) -- Handle non default IBC transfer port in message encoder [\#396](https://github.com/CosmWasm/wasmd/issues/396) -- Collect Contract Metrics [\#387](https://github.com/CosmWasm/wasmd/issues/387) -- Add Submessages for IBC callbacks [\#449](https://github.com/CosmWasm/wasmd/issues/449) -- Handle wasmvm Burn message [\#489](https://github.com/CosmWasm/wasmd/pull/489) ([alpe](https://github.com/alpe)) -- Add telemetry [\#463](https://github.com/CosmWasm/wasmd/pull/463) ([alpe](https://github.com/alpe)) -- Handle non default transfer port id [\#462](https://github.com/CosmWasm/wasmd/pull/462) ([alpe](https://github.com/alpe)) -- Allow subsecond block times [\#453](https://github.com/CosmWasm/wasmd/pull/453) ([ethanfrey](https://github.com/ethanfrey)) -- Submsg and replies [\#441](https://github.com/CosmWasm/wasmd/pull/441) ([ethanfrey](https://github.com/ethanfrey)) -- Ibc query support [\#439](https://github.com/CosmWasm/wasmd/pull/439) ([ethanfrey](https://github.com/ethanfrey)) -- Pin/Unpin contract in cache [\#436](https://github.com/CosmWasm/wasmd/pull/436) ([alpe](https://github.com/alpe)) -- Stargate msg and query [\#435](https://github.com/CosmWasm/wasmd/pull/435) ([ethanfrey](https://github.com/ethanfrey)) -- Sudo entry point [\#433](https://github.com/CosmWasm/wasmd/pull/433) ([ethanfrey](https://github.com/ethanfrey)) -- Add custom message handler option [\#402](https://github.com/CosmWasm/wasmd/pull/402) ([alpe](https://github.com/alpe)) -- Expose contract pinning [\#401](https://github.com/CosmWasm/wasmd/issues/401) -- Add support for Stargate CosmosMsg/QueryRequest [\#388](https://github.com/CosmWasm/wasmd/issues/388) -- Add MsgInstantiateContractResponse.data [\#385](https://github.com/CosmWasm/wasmd/issues/385) -- Added randomized simulation parameters generation [\#389](https://github.com/CosmWasm/wasmd/pull/389) ([bragaz](https://github.com/bragaz)) -- Implement IBC contract support [\#394](https://github.com/CosmWasm/wasmd/pull/394) ([alpe](https://github.com/alpe)) - -**Api breaking:** - -- Improve list contracts by code query [\#497](https://github.com/CosmWasm/wasmd/pull/497) ([alpe](https://github.com/alpe)) -- Rename to just `funds` [/#423](https://github.com/CosmWasm/wasmd/issues/423) - -**Fixed bugs:** - -- Correct order for migrated contracts [\#323](https://github.com/CosmWasm/wasmd/issues/323) -- Keeper Send Coins does not perform expected validation [\#414](https://github.com/CosmWasm/wasmd/issues/414) - -## [v0.15.1](https://github.com/CosmWasm/wasmd/tree/v0.15.1) (2021-02-18) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.15.0...v0.15.1) - -**Implemented enhancements:** - -- Support custom MessageHandler in wasm [\#327](https://github.com/CosmWasm/wasmd/issues/327) - -**Fixed bugs:** - -- Fix Parameter change via proposal [\#392](https://github.com/CosmWasm/wasmd/issues/392) - -## [v0.15.0](https://github.com/CosmWasm/wasmd/tree/v0.15.0) (2021-01-27) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.14.1...v0.15.0) - -**Features:** - -- Upgrade to cosmos-sdk v0.41.0 [\#390](https://github.com/CosmWasm/wasmd/pull/390) - -## [v0.14.1](https://github.com/CosmWasm/wasmd/tree/v0.14.1) (2021-01-20) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.14.0...v0.14.1) - -**Features:** - -- Upgrade to cosmos-sdk v0.40.1 final + Tendermint 0.34.3 [\#380](https://github.com/CosmWasm/wasmd/pull/380) - -## [v0.14.0](https://github.com/CosmWasm/wasmd/tree/v0.14.0) (2021-01-11) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.13.0...v0.14.0) - -**Features:** - -- Upgrade to cosmos-sdk v0.40.0 final [\#354](https://github.com/CosmWasm/wasmd/pull/369) -- Refactor to GRPC message server [\#366](https://github.com/CosmWasm/wasmd/pull/366) -- Make it easy to initialize contracts in genesis file with new CLI commands[\#326](https://github.com/CosmWasm/wasmd/issues/326) -- Upgrade to WasmVM v0.13.0 [\#358](https://github.com/CosmWasm/wasmd/pull/358) -- Upgrade to cosmos-sdk v0.40.0-rc6 [\#354](https://github.com/CosmWasm/wasmd/pull/354) -- Upgrade to cosmos-sdk v0.40.0-rc5 [\#344](https://github.com/CosmWasm/wasmd/issues/344) -- Add Dependabot to keep dependencies secure and up-to-date [\#336](https://github.com/CosmWasm/wasmd/issues/336) - -**Fixed bugs:** - -- Dependabot can't resolve your Go dependency files [\#339](https://github.com/CosmWasm/wasmd/issues/339) -- Errors in `InitGenesis` [\#335](https://github.com/CosmWasm/wasmd/issues/335) -- Invalid homeDir for export command [\#334](https://github.com/CosmWasm/wasmd/issues/334) - -## [v0.13.0](https://github.com/CosmWasm/wasmd/tree/v0.13.0) (2020-12-04) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.12.1...v0.13.0) - -**Fixed bugs:** - -- REST handler wrong `Sender` source [\#324](https://github.com/CosmWasm/wasmd/issues/324) - -**Closed issues:** - -- Change proto package to match \.\.\ [\#329](https://github.com/CosmWasm/wasmd/issues/329) -- Out of gas causes panic when external contract store query executed [\#321](https://github.com/CosmWasm/wasmd/issues/321) -- Check codecov report [\#298](https://github.com/CosmWasm/wasmd/issues/298) -- cosmwasm.GoAPI will not work on sdk.ValAddress [\#264](https://github.com/CosmWasm/wasmd/issues/264) -- Stargate: Add pagination support for queries [\#242](https://github.com/CosmWasm/wasmd/issues/242) - -**Merged pull requests:** - -- Rename protobuf package [\#330](https://github.com/CosmWasm/wasmd/pull/330) ([alpe](https://github.com/alpe)) -- Use base request data for sender [\#325](https://github.com/CosmWasm/wasmd/pull/325) ([alpe](https://github.com/alpe)) -- Handle panics in query contract smart [\#322](https://github.com/CosmWasm/wasmd/pull/322) ([alpe](https://github.com/alpe)) - -## [v0.12.1](https://github.com/CosmWasm/wasmd/tree/v0.12.1) (2020-11-23) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.12.0...v0.12.1) - -**Closed issues:** - -- Complete IBC Mock testing [\#255](https://github.com/CosmWasm/wasmd/issues/255) -- Idea: do multiple queries in one API call [\#72](https://github.com/CosmWasm/wasmd/issues/72) - -**Merged pull requests:** - -- Exclude generate proto code files in coverage [\#320](https://github.com/CosmWasm/wasmd/pull/320) ([alpe](https://github.com/alpe)) -- Upgrade wasmvm to 0.12.0 [\#319](https://github.com/CosmWasm/wasmd/pull/319) ([webmaster128](https://github.com/webmaster128)) -- Fix chain id setup in contrib/local/setup\_wasmd.sh [\#318](https://github.com/CosmWasm/wasmd/pull/318) ([orkunkl](https://github.com/orkunkl)) -- Add pagination to grpc queries [\#317](https://github.com/CosmWasm/wasmd/pull/317) ([alpe](https://github.com/alpe)) - -## [v0.12.0](https://github.com/CosmWasm/wasmd/tree/v0.12.0) (2020-11-17) - -[Full Changelog](https://github.com/CosmWasm/wasmd/compare/v0.12.0-alpha1...v0.12.0) - -**Closed issues:** - -- Merge wasmd and wasmcli into a single binary [\#308](https://github.com/CosmWasm/wasmd/issues/308) -- Change bech32 prefix for wasmd [\#313](https://github.com/CosmWasm/wasmd/issues/313) -- Upgrade go-cowasmwasm to wasmvm 0.12 [\#309](https://github.com/CosmWasm/wasmd/issues/309) -- Use string type for AccAddresses in proto [\#306](https://github.com/CosmWasm/wasmd/issues/306) -- Upgrade to cosmos/sdk v0.40.0-rc2 [\#296](https://github.com/CosmWasm/wasmd/issues/296) -- Generate protobuf outputs in a container [\#295](https://github.com/CosmWasm/wasmd/issues/295) -- Instantiate contract process ordering [\#292](https://github.com/CosmWasm/wasmd/issues/292) -- Make Wasm maxSize a configuration option [\#289](https://github.com/CosmWasm/wasmd/issues/289) -- Return error if wasm to big [\#287](https://github.com/CosmWasm/wasmd/issues/287) - -**Merged pull requests:** - -- Set bech32 prefix [\#316](https://github.com/CosmWasm/wasmd/pull/316) ([alpe](https://github.com/alpe)) -- Replace sdk.AccAddress with bech32 string [\#314](https://github.com/CosmWasm/wasmd/pull/314) ([alpe](https://github.com/alpe)) -- Integrate wasmcli into wasmd [\#312](https://github.com/CosmWasm/wasmd/pull/312) ([alpe](https://github.com/alpe)) -- Upgrade wasmvm aka go-cosmwasm [\#311](https://github.com/CosmWasm/wasmd/pull/311) ([alpe](https://github.com/alpe)) -- Upgrade to Stargate RC3 [\#305](https://github.com/CosmWasm/wasmd/pull/305) ([alpe](https://github.com/alpe)) -- Containerized Protobuf generation [\#304](https://github.com/CosmWasm/wasmd/pull/304) ([alpe](https://github.com/alpe)) -- Reject wasm code exceeding limit [\#302](https://github.com/CosmWasm/wasmd/pull/302) ([alpe](https://github.com/alpe)) -- Support self calling contract on instantiation [\#300](https://github.com/CosmWasm/wasmd/pull/300) ([alpe](https://github.com/alpe)) -- Upgrade to Stargate RC2 [\#299](https://github.com/CosmWasm/wasmd/pull/299) ([alpe](https://github.com/alpe)) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 05cb53b..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,110 +0,0 @@ -# Contributing - -Thank you for considering making contributions to Wasmd! - -Contributing to this repo can mean many things, such as participating in -discussion or proposing code changes. To ensure a smooth workflow for all -contributors, the general procedure for contributing has been established: - -1. Start by browsing [new issues](https://github.com/terpnetwork/terp-core/issues). - * Looking for a good place to start contributing? How about checking out some [good first issues](https://github.com/terpnetwork/terp-core/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) or [bugs](https://github.com/terpnetwork/terp-core/issues?q=is%3Aopen+is%3Aissue+label%3Abug)? -2. Determine whether a GitHub issue or discussion is more appropriate for your needs: - 1. If the issue you want addressed is a specific proposal or a bug, then open a [new issue](https://github.com/terpnetwork/terp-core/issues/new). - 2. Review existing [issues](https://github.com/terpnetwork/terp-core/issues) to find an issue you'd like to help with. -3. Participate in thoughtful discussion on that issue. -4. If you would like to contribute: - 1. Ensure that the proposal has been accepted. - 2. Ensure that nobody else has already begun working on this issue. If they have, - make sure to contact them to collaborate. - 3. If nobody has been assigned for the issue and you would like to work on it, - make a comment on the issue to inform the community of your intentions - to begin work. -5. To submit your work as a contribution to the repository follow standard GitHub best practices. See [pull request guideline](#pull-requests) below. - -**Note:** For very small or blatantly obvious problems such as typos, you are -not required to an open issue to submit a PR, but be aware that for more complex -problems/features, if a PR is opened before an adequate design discussion has -taken place in a GitHub issue, that PR runs a high likelihood of being rejected. - -## Development Procedure - -* The latest state of development is on `main`. -* `main` must never fail `make lint test test-race`. -* No `--force` onto `main` (except when reverting a broken commit, which should seldom happen). -* Create a branch to start work: - * Fork the repo (core developers must create a branch directly in the Wasmd repo), - branch from the HEAD of `main`, make some commits, and submit a PR to `main`. - * For core developers working within the `wasmd` repo, follow branch name conventions to ensure a clear - ownership of branches: `{issue#}-branch-name`. - * See [Branching Model](#branching-model-and-release) for more details. -* Be sure to run `make format` before every commit. The easiest way - to do this is have your editor run it for you upon saving a file (most of the editors - will do it anyway using a pre-configured setup of the programming language mode). -* Follow the [CODING GUIDELINES](CODING_GUIDELINES.md), which defines criteria for designing and coding a software. - -Code is merged into main through pull request procedure. - -### Testing - -Tests can be executed by running `make test` at the top level of the wasmd repository. - -### Pull Requests - -Before submitting a pull request: - -* merge the latest main `git merge origin/main`, -* run `make lint test` to ensure that all checks and tests pass. - -Then: - -1. If you have something to show, **start with a `Draft` PR**. It's good to have early validation of your work and we highly recommend this practice. A Draft PR also indicates to the community that the work is in progress. - Draft PRs also helps the core team provide early feedback and ensure the work is in the right direction. -2. When the code is complete, change your PR from `Draft` to `Ready for Review`. -3. Be sure to include a relevant changelog entry in the `Unreleased` section of `CHANGELOG.md` (see file for log format). The entry should be on top of all others changes in the section. - -PRs name should start upper case. -Additionally, each PR should only address a single issue. - -NOTE: when merging, GitHub will squash commits and rebase on top of the main. - -## Protobuf - -We use [Protocol Buffers](https://developers.google.com/protocol-buffers) along with [gogoproto](https://github.com/cosmos/gogoproto) to generate code for use in Wasmd. - -For deterministic behavior around Protobuf tooling, everything is containerized using Docker. Make sure to have Docker installed on your machine, or head to [Docker's website](https://docs.docker.com/get-docker/) to install it. - -For formatting code in `.proto` files, you can run `make proto-format` command. - -For linting we use [buf](https://buf.build/). You can use the commands `make proto-lint` to lint your proto files. - -To generate the protobuf stubs, you can run `make proto-gen`. - -We also added the `make proto-all` command to run all the above commands sequentially. - -In order for imports to properly compile in your IDE, you may need to manually set your protobuf path in your IDE's workspace settings/config. - -For example, in vscode your `.vscode/settings.json` should look like: - -```json -{ - "protoc": { - "options": [ - "--proto_path=${workspaceRoot}/proto", - ] - } -} -``` - -## Branching Model and Release - -User-facing repos should adhere to the trunk based development branching model: https://trunkbaseddevelopment.com. User branches should start with a user name, example: `{moniker}/{issue#}-branch-name`. - -Wasmd utilizes [semantic versioning](https://semver.org/). - -### PR Targeting - -Ensure that you base and target your PR on the `main` branch. - -All feature additions and all bug fixes must be targeted against `main`. Exception is for bug fixes which are only related to a released version. In that case, the related bug fix PRs must target against the release branch. - -If needed, we backport a commit from `main` to a release branch (excluding consensus breaking feature, API breaking and similar). \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 7e48739..4bd9e26 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,10 +15,10 @@ RUN apk add git WORKDIR /code COPY . /code/ # See https://github.com/CosmWasm/wasmvm/releases -ADD https://github.com/CosmWasm/wasmvm/releases/download/v1.2.1/libwasmvm_muslc.aarch64.a /lib/libwasmvm_muslc.aarch64.a -ADD https://github.com/CosmWasm/wasmvm/releases/download/v1.2.1/libwasmvm_muslc.x86_64.a /lib/libwasmvm_muslc.x86_64.a -RUN sha256sum /lib/libwasmvm_muslc.aarch64.a | grep 86bc5fdc0f01201481c36e17cd3dfed6e9650d22e1c5c8983a5b78c231789ee0 -RUN sha256sum /lib/libwasmvm_muslc.x86_64.a | grep a00700aa19f5bfe0f46290ddf69bf51eb03a6dfcd88b905e1081af2e42dbbafc +ADD https://github.com/CosmWasm/wasmvm/releases/download/v1.3.0/libwasmvm_muslc.aarch64.a /lib/libwasmvm_muslc.aarch64.a +ADD https://github.com/CosmWasm/wasmvm/releases/download/v1.3.0/libwasmvm_muslc.x86_64.a /lib/libwasmvm_muslc.x86_64.a +RUN sha256sum /lib/libwasmvm_muslc.aarch64.a | grep b1610f9c8ad8bdebf5b8f819f71d238466f83521c74a2deb799078932e862722 +RUN sha256sum /lib/libwasmvm_muslc.x86_64.a | grep b4aad4480f9b4c46635b4943beedbb72c929eab1d1b9467fe3b43e6dbf617e32 # Copy the library you want to the final location that will be found by the linker flag `-lwasmvm_muslc` RUN cp /lib/libwasmvm_muslc.${arch}.a /lib/libwasmvm_muslc.a @@ -45,4 +45,4 @@ EXPOSE 26656 # tendermint rpc EXPOSE 26657 -CMD ["/usr/bin/terpd", "version"] \ No newline at end of file +CMD ["/usr/bin/terpd", "version"] diff --git a/EVENTS.md b/EVENTS.md deleted file mode 100644 index 371e1c4..0000000 --- a/EVENTS.md +++ /dev/null @@ -1,420 +0,0 @@ -# Event System - -## Usage in the SDK - -Events are an essential part of the Cosmos SDK. They are similar to "logs" in Ethereum and allow a blockchain -app to attach key-value pairs to a transaction that can later be used to search for it or extract some information -in human readable form. Events are not written to the application state, nor do they form part of the AppHash, -but mainly intended for client use (and become an essential API for any reactive app or app that searches for txs). - -In contrast, transactions also have a binary "data" field that is part of the AppHash (provable with light client proofs, -part of consensus). This data is not searchable, but given a tx hash, you can be guaranteed what the data returned is. -This is often empty, but sometimes custom protobuf formats to return essential information from an execution. - -Every message in the SDK may add events to the EventManager and these are then added to the final ABCI result that is returned -to Tendermint. Events are exposed in 3 different ways over the Tendermint API (which is the only way a client can query). -First of all is the `events` field on the transaction result (when you query a transaction by hash, you can see all event emitted -by it). Secondly is the `log` field on the same transaction result. And third is the query interface to search or subscribe for -transactions. - -The `log` field actually has the best data. It contains an array of array of events. The first array is one entry per incoming message. -Transactions in the Cosmos SDK may consist of multiple messages that are executed atomically. Maybe we send tokens, then issue a swap -on a DEX. Each action would return it's own list of Events and in the logs, these are separated. For each message, it maintains a list -of Events, exactly in the order returned by the application. This is JSON encoded and can be parsed by a client. In fact this is -how [CosmJS](https://github.com/cosmos/cosmjs) gets the events it shows to the client. - -In Tendermint 0.35, the `events` field will be one flattened list of events over all messages. Just as if we concatenated all -the per-message arrays contained in the `log` field. This fix was made as -[part of an event system refactoring](https://github.com/tendermint/tendermint/pull/6634). This refactoring is also giving us -[pluggable event indexing engines](https://github.com/tendermint/tendermint/pull/6411), so we can use eg. PostgreSQL to -store and query the events with more powerful indexes. - -However, currently (until Tendermint 0.34 used in Cosmos SDK 0.40-0.43), all events of one transaction are "flat-mapped" on type. -Meaning all events with type `wasm` get merged into one. This makes the API not very useful to understanding more complex events -currently. There are also a number of limitations of the power of queries in the search interface. - -Given the state of affairs, and given that we seek to provide a stable API for contracts looking into the future, we consider the -`log` output and the Tendermint 0.35 event handling to be the standard that clients should adhere to. And we will expose a similar -API to the smart contracts internally (all events from the message appended, unmerged). -### Data Format - -The event has a string type, and a list of attributes. Each of them being a key value pair. All of these maintain a -consistent order (and avoid dictionaries/hashes). Here is a simple Event in JSON: - -```json -{ - "type": "wasm", - "attributes": [ - {"key": "_contract_address", "value": "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6"}, - {"key": "transfered", "value": "777000"} - ] -} -``` - -And here is a sample log output for a transaction with one message, which emitted 2 events: - -```json -[ - [ - { - "type": "message", - "attributes": [ - {"key": "module", "value": "bank"}, - {"key": "action", "value": "send"} - ] - }, - { - "type": "transfer", - "attributes": [ - {"key": "recipient", "value": "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6"}, - {"key": "amount", "value": "777000uatom"} - ] - } - ] -] -``` - -### Default Events in the SDK - -There are two places events that are emitted in every transaction regardless of the module which is executed. -[The first is `{"type": "message"}`](https://github.com/cosmos/cosmos-sdk/blob/6888de1d86026c25197c1227dae3d7da4d41a441/baseapp/baseapp.go#L746-L748) -defining an `action` attribute. This is emitted for each top-level (user-signed) message, but the action names have changed between -0.42 and 0.43. - -The other place is in the [signature verification AnteHandler](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/auth/ante/sigverify.go#L103-L120), where it emits information on the account sequences and signatures on the transaction. - -These are all handled in BaseApp and the middleware *before* any module is called and thus not exposed to CosmWasm contracts at all. - -### Standard Events in the SDK - -The events that will actually make it to the contracts are the events that are emitted by the other modules / keepers. Let's look -at some good examples of what they look like: - -The most basic one is `bank`, which emits two events on every send, a [custom "transfer" event](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/bank/keeper/send.go#L142-L147) as well as "sender" information under the [standard "message" type](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/bank/keeper/send.go#L148-L151). Replacing variables with string literals, they look like this: - -```go -sdk.NewEvent( - "transfer" - sdk.NewAttribute("recipient", toAddr.String()), - sdk.NewAttribute("sender", fromAddr.String()), - sdk.NewAttribute("amount", amt.String()), // eg 12456uatom -), -sdk.NewEvent( - "message", - sdk.NewAttribute("sender", fromAddr.String()), -), -``` - -The delegation module seems a bit more refined, emitting a generic "message" type event in [`msg_server.go`](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/distribution/keeper/msg_server.go#L42-L46) including the module name, **before** -emitting some custom event types closer to the actual code logic in -[`keeper.go`](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/distribution/keeper/keeper.go#L74-L77). - -This looks something like: - -```go -sdk.NewEvent( - "message", - sdk.NewAttribute("module", "distribution"), - sdk.NewAttribute("sender", msg.DelegatorAddress), -), -sdk.NewEvent( - "set_withdraw_address", - sdk.NewAttribute("withdraw_address", withdrawAddr.String()), -), -``` - -## Usage in wasmd - -In `x/wasm` we also use Events system. On one hand, the Go implementation of `x/wasm` emits standard events for each -message it processes, using the `distribution` module as an example. Furthermore, it allows contracts to -emit custom events based on their execution state, so they can for example say "dex swap, BTC-ATOM, in 0.23, out 512" -which require internal knowledge of the contract and is very useful for custom dApp UIs. - -`x/wasm` is also a consumer of events, since when a smart contract executes a SubMsg and processes the reply, it receives -not only the `data` response from the message execution, but also the list of events. This makes it even more important for -us to document a standard event processing format. - -### Standard Events in x/wasm - -Following the model of `distribution`, we will split the emitted events into two parts. All calls to the message server, will receive -the following event: - -```go -sdk.NewEvent( - "message", - sdk.NewAttribute("module", "wasm"), - // Note: this was "signer" before 0.18 - sdk.NewAttribute("sender", msg.Sender), -), -``` - -No further information will be added to the generic "message" type, but rather be contained in a more context-specific event type. -Here are some examples: - -```go -// Store Code -sdk.NewEvent( - "store_code", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", codeID)), - // features required by the contract (new in 0.18) - // see https://github.com/CosmWasm/wasmd/issues/574 - sdk.NewAttribute("feature", "stargate"), - sdk.NewAttribute("feature", "staking"), -) - -// Instantiate Contract -sdk.NewEvent( - "instantiate", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Execute Contract -sdk.NewEvent( - "execute", - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Migrate Contract -sdk.NewEvent( - "migrate", - // Note: this is the new code id that is being migrated to - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Set new admin -sdk.NewEvent( - "update_admin", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("admin", msg.NewAdmin), -) - -// Clear admin -sdk.NewEvent( - "clear_admin", - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Pin Code -sdk.NewEvent( - "pin_code", - sdk.NewAttribute("code_id", strconv.FormatUint(msg.CodeID, 10)), -) - -// Unpin Code -sdk.NewEvent( - "unpin_code", - sdk.NewAttribute("code_id", strconv.FormatUint(msg.CodeID, 10)), -) - -// Emitted when processing a submessage reply -sdk.NewEvent( - "reply", - sdk.NewAttribute("_contract_address", contractAddr.String()), - // If the submessage was successful, and reply is processing the success case - sdk.NewAttribute("mode", "handle_success"), - // If the submessage returned an error that was "caught" by the reply block - sdk.NewAttribute("mode", "handle_failure"), -) - -// Emitted when handling sudo -sdk.NewEvent( - "sudo", - sdk.NewAttribute("_contract_address", contractAddr.String()), -) -``` - -Note that every event that affects a contract (not store code, pin or unpin) will return the contract_address as -`_contract_address`. The events that are related to a particular wasm code (store code, instantiate, pin, unpin, and migrate) -will emit that as `code_id`. All attributes prefixed with `_` are reserved and may not be emitted by a smart contract, -so we use the underscore prefix consistently with attributes that may be injected into custom events. - -### Emitted Custom Events from a Contract - -When a CosmWasm contract returns a `Response` from one of the calls, it may return a list of attributes as well as a list -of events (in addition to data and a list of messages to dispatch). These are then processed in `x/wasm` to create events that -are emitted to the blockchain. - -If the response contains a non-empty list of `attributes`, `x/wasm` will emit a `wasm` type event. This event will -always be tagged with `_contract_address` by the Go module, so this is trust-worthy. The contract itself cannot overwrite -this field. Beyond this, the `attributes` returned by the contract, these are appended to the same event. - -A contact may also return custom `events`. These are multiple events, each with their own type as well as attributes. -When they are received, `x/wasm` prepends `wasm-` to the event type returned by the contact to avoid them trying to fake -an eg. `transfer` event from the bank module. The output here may look like: - -```go -sdk.NewEvent( - "wasm-promote" - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("batch_id", "6"), - sdk.NewAttribute("address", "cosmos1234567"), - sdk.NewAttribute("address", "cosmos1765432"), -), -sdk.NewEvent( - "wasm-promote" - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("batch_id", "7"), - sdk.NewAttribute("address", "cosmos19875632"), -) -``` - -Note that these custom events also have the `_contract_address` attribute automatically injected for easier attribution in the clients. -The multiple event API was designed to allow the contract to make logical groupings that are persisted in the event system, -more than flattening them all into one event like: - -```go -sdk.NewEvent( - "wasm" - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("action", "promote"), - sdk.NewAttribute("batch_id", "6"), - sdk.NewAttribute("address", "cosmos1234567"), - sdk.NewAttribute("address", "cosmos1765432"), - sdk.NewAttribute("batch_id", "7"), - sdk.NewAttribute("address", "cosmos19875632"), -) -``` - -If the Response contains neither `event` nor `attributes`, not `wasm*` events will be emitted, just the standard `message` -type as well as the action-dependent event (like `execute` or `migrate`). This is a significant change from pre-0.18 versions -where one could count on the `wasm` event to always be emitted. Now it is recommended to search for `execute._contract_address="foo"` -to find all transactions related to the contract. - -### Validation Rules - -While the `wasm` and `wasm-*` namespacing does sandbox the smart contract events and limits malicious activity they could -undertake, we also perform a number of further validation checks on the contracts: - -* No attribute key may start with `_`. This is currently used for `_contract_address` and is reserved for a - namespace for injecting more *trusted* attributes from the `x/wasm` module as opposed to the contract itself -* Event types are trimmed of whitespace, and must have at least two characters prior to prepending `wasm-`. If the contract returns - " hello\n", the event type will look like `wasm-hello`. If it emits " a ", this will be rejected with an error (aborting execution!) -* Attribute keys and values (both in `attributes` and under `events`) are trimmed of leading/trailing whitespace. If they are empty after - trimming, they are rejected as above (aborting the execution). Otherwise, they are passed verbatim. - -## Event Details for wasmd - -Beyond the basic Event system and emitted events, we must handle more advanced cases in `x/wasm` -and thus add some more logic to the event processing. Remember that CosmWasm contracts dispatch other -messages themselves, so far from the flattened event structure, or even a list of list (separated -by message index in the tx), we actually have a tree of messages, each with their own events. And we must -flatten that in a meaningful way to feed it into the event system. - -Furthermore, with the sub-message reply handlers, we end up with eg. "Contract A execute", "Contract B execute", -"Contract A reply". If we return all events by all of these, we may end up with many repeated event types and -a confusing results. However, we may use the standard "message" events to separate the sub-messages as it marks -where the next one starts. With careful analysis of the "sender" field on these "message" markers, we may be able -to reconstruct much of the tree execution path. We should ensure all this information is exposed in the most -consistent way possible. - -### Combining Events from Sub-Messages - -Each time a contract is executed, it not only returns the `message` event from its call, the `execute` event for the -contact and the `wasm` event with any custom fields from the contract itself. It will also return the same set of information -for all messages that it returned, which were later dispatched. The event system was really designed for one main -action emitting events, so we define a structure to flatten this event tree: - -* We only emit one event of type `message`. This is the top-level call, just like the standard Go modules. For all - dispatched submessages, we filter out this event type. -* All events are returned in execution order as [defined by CosmWasm docs](https://github.com/CosmWasm/cosmwasm/blob/main/SEMANTICS.md#dispatching-messages) -* `x/wasm` keeper emits a custom event for each call to a contract entry point. Not just `execute`, `instantiate`, - and `migrate`, but also `reply`, `sudo` and all ibc entry points. -* This means all `wasm*` events are preceeded by the cosmwasm entry point that returned them. - -To make this more clear, I will provide an example of executing a contract, which returns two messages, one to instantiate a new -contract and the other to set the withdrawl address, while also using `ReplyOnSuccess` for the instantiation (to get the -address). It will emit a series of events that looks something like this: - -```go -/// original execution (top-level message is the only one that gets the message tag) -sdk.NewEvent( - "message", - sdk.NewAttribute("module", "wasm"), - sdk.NewAttribute("sender", msg.Sender), -), - -// top-level exection call -sdk.NewEvent( - "execute", - sdk.NewAttribute("_contract_address", contractAddr.String()), -), -sdk.NewEvent( - "wasm", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("custom", "from contract"), -), - -// instantiating contract (first dipatched message) -sdk.NewEvent( - "instantiate", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", newContract.String()), -) -// didn't emit any attributes, but one event -sdk.NewEvent( - "wasm-custom", - sdk.NewAttribute("_contract_address", newContract.String()), - sdk.NewAttribute("foobar", "baz"), -), - -// handling the reply (this doesn't emit a message event as it never goes through the message server) -sdk.NewEvent( - "reply", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("mode", "handle_success"), -), -sdk.NewEvent( - "wasm", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("custom", "from contract"), -), - -// calling the distribution module (second dispatched message) -sdk.NewEvent( - "set_withdraw_address", - sdk.NewAttribute("withdraw_address", withdrawAddr.String()), -), -``` - -### Exposing Events to Reply - -When the `reply` clause in a contract is called, it will receive the data returned from the message it -applies to, as well as all events from that message. In the above case, when the `reply` function was called -on `contractAddr` in response to initializing a contact, it would get the binary-encoded `initData` in the `data` -field, and the following in the `events` field: - -```go -sdk.NewEvent( - "instantiate", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", newContract.String()), -) -sdk.NewEvent( - "wasm-custom", - sdk.NewAttribute("_contract_address", newContract.String()), - sdk.NewAttribute("foobar", "baz"), -), -``` - -If the original contract execution example above was actually the result of a message returned by an eg. factory contract, -and it registered a ReplyOn clause, the `reply` function on that contract would receive the entire 11 events in the example -above, and would need to use the `message` markers to locate the segment of interest. - -## Governance Events -The governance process is handled by the cosmos-sdk `gov` module. We do not emit any events of type "message" anymore in v0.18+. -Context-specific events are emitted as described above. `Execution` and `Migration` return some contract result though that are -emitted as: -```go -sdk.NewEvent( - "gov_contract_result", - sdk.NewAttribute("result", hex.EncodeToString(data)), -) -``` - -## IBC Events - -All IBC entry points are only called by external accounts and not from contracts. They need to contain proofs of state of other blockchains and cannot be called by other contracts on the same chain. Therefore, the event emitted are not essential for cross-contract calls, and `x/wasm` does not emit custom events for these actions. - -There are well-defined events emitted by the IBC base layer and are required for the relayer functionality. If you wish to subscribe to these, you can find them [defined in the `ibc-go` codebase](https://github.com/cosmos/ibc-go/blob/main/modules/core/04-channel/keeper/events.go). diff --git a/INTEGRATION.md b/INTEGRATION.md deleted file mode 100644 index 5907e20..0000000 --- a/INTEGRATION.md +++ /dev/null @@ -1,205 +0,0 @@ - - -# Integration - -If you want to use Wasm in your own app, here is how you can get this working -quickly and easily. -First start with This [article](https://medium.com/cosmwasm/cosmwasm-for-ctos-iv-native-integrations-713140bf75fc) -in the "CosmWasm for CTOs" series that gives you a high level view. -Then check to make sure you fit the pre-requisites, -then integrate the `x/wasm` module as described below, and finally, you -can add custom messages and queries to your custom Go/SDK modules, exposing -them to any chain-specific contract. - -## Prerequisites - -The pre-requisites of integrating `x/wasm` into your custom app is to be using -a compatible version of the Cosmos SDK, and to accept some limits to the -hardware it runs on. - -| wasmd | Cosmos SDK | -|:-----:|:----------:| -| v0.30 | v0.45.11 | -| v0.29 | v0.45.8 | -| v0.28 | v0.45.5 | -| v0.27 | v0.45.4 | -| v0.26 | v0.45.1 | -| v0.25 | v0.45.1 | -| v0.24 | v0.45.0 | -| v0.23 | v0.45.0 | -| v0.22 | v0.45.0 | -| v0.21 | v0.42.x | - - -We currently only support Intel/AMD64 CPUs and OSX or Linux. For Linux, the standard build -commands work for `glibc` systems (Ubuntu, Debian, CentOS, etc). If you wish to compile -for a `muslc` based system (like alpine), you need to compile a static library wasmvm locally -and compile go with the `muslc` build tag. Or just use the [Dockerfile](./Dockerfile), -which builds a static go binary in an alpine system. - -This limit comes from the Rust dll we use to run the wasm code, which comes -from [`wasmvm`](https://github.com/CosmWasm/wasmvm). There are open issues -for adding [ARM support](https://github.com/CosmWasm/wasmvm/issues/53), and -adding [Windows support](https://github.com/CosmWasm/wasmvm/issues/28). -However, these issues are not high on the roadmap and unless you are championing -them, please count on the current limits for the near future. - -## Quick Trial - -The simplest way to try out CosmWasm is simply to run `wasmd` out of the box, -and focus on writing, uploading, and using your custom contracts. There is -plenty that can be done there, and lots to learn. - -Once you are happy with it and want to use a custom Cosmos SDK app, -you may consider simply forking `wasmd`. *I highly advise against this*. -You should try one of the methods below. - -## Integrating wasmd - -### As external module - -The simplest way to use `wasmd` is just to import `x/wasm` and wire it up -in `app.go`. You now have access to the whole module and you custom modules -running side by side. (But the CosmWasm contracts will only have access -to `bank` and `staking`... more below on [customization](#Adding-Custom-Hooks)). - -The requirement here is that you have imported the standard sdk modules -from the Cosmos SDK, and enabled them in `app.go`. If so, you can just look -at [`wasmd/app/app.go`](https://github.com/terpnetwork/terp-core/blob/master/app/app.go#) -for how to do so (just search there for lines with `wasm`). - -`wasmd` also comes with 2 custom `ante handlers`: -* `CountTXDecorator` adds the TX position in the block into the context and passes it to the contracts -* `LimitSimulationGasDecorator` prevents an "infinite gas" query - -In order to support these features you would need to add our custom -ante handlers into the `ante handler chain` as in: [`app/ante.go`](https://github.com/terpnetwork/terp-core/blob/master/app/ante.go) - -### Copied into your app - -Sometimes, however, you will need to copy `x/wasm` into your app. This should -be in limited cases, and makes upgrading more difficult, so please take the -above path if possible. This is required if you have either disabled some key -SDK modules in your app (eg. using PoA not staking and need to disable those -callbacks and feature support), or if you have copied in the core `x/*` modules -from the Cosmos SDK into your application and customized them somehow. - -In either case, your best approach is to copy the `x/wasm` module from the -latest release into your application. Your goal is to make **minimal changes** -in this module, and rather add your customizations in a separate module. -This is due to the fact that you will have to copy and customize `x/wasm` -from upstream on all future `wasmd` releases, and this should be as simple -as possible. - -If, for example, you have forked the standard SDK libs, you just want to -change the imports (from eg. `github.com/cosmos/cosmos-sdk/x/bank` to -`github.com/YOUR/APP/x/bank`), and adjust any calls if there are compiler -errors due to differing APIs (maybe you use Decimals not Ints for currencies?). - -By the end of this, you should be able to run the standard CosmWasm contracts -in your application, alongside all your custom logic. - -## Adding custom hooks - -Once you have gotten this integration working and are happy with the -flexibility it offers you, you will probably start wishing for deeper -integration with your custom SDK modules. "It sure is nice to have custom -tokens with a bonding curve from my native token, but I would love -to trade them on the exchange I wrote as a Go module. Or maybe use them -to add options to the exchange." - -At this point, you need to dig down deeper and see how you can add this -power without forking either CosmWasm or `wasmd`. - -### Calling contracts from native code - -This is perhaps the easiest part. Let's say your native exchange module -wants to call into a token that lives as a CosmWasm module. You need to -pass the `wasm.Keeper` into your `exchange.Keeper`. If you know the format -for sending messages and querying the contract (exported as json schema -from each contract), and have a way of configuring addresses of supported -token contracts, your exchange code can simply call `wasm.Keeper.Execute` -with a properly formatted message to move funds, or `wasm.Keeper.SmartQuery` -to check balances. - -If you look at the unit tests in [`x/wasm/internal/keeper`](https://github.com/terpnetwork/terp-core/tree/master/x/wasm/internal/keeper), -it should be pretty straight forward. - -### Extending the Contract Interface - -If you want to let the contracts access your native modules, the first -step is to define a set of Messages and Queries that you want to expose, -and then add them as `CosmosMsg::Custom` and `QueryRequest::Custom` -variants. You can see an example of the [bindings for Terra](https://github.com/CosmWasm/terra-contracts/tree/master/packages/bindings). - -Once you have those bindings, use them to build a -[simple contact using much of the API](https://github.com/CosmWasm/terra-contracts/tree/master/contracts/maker). -Don't worry too much about the details, this should be usable, but mainly -you will want to upload it to your chain and use for integration tests -with your native Cosmos SDK modules. Once that is solid, then add more -and more complex contracts. - -You will then likely want to add a `mocks` package so you can provide -mocks for the functionality of your native modules when unit testing -the contracts (provide static data for exchange rates when your contracts -query it). You can see an example of [mocks for Terra contracts](https://github.com/CosmWasm/terra-contracts/tree/master/packages/mocks). - -What these three steps provide is basically a chain-specific extension to the CosmWasm contract SDK. -Any CosmWasm contract can import you library (bindings and mocks) and easily get started using -your custom, chain-specific extensions just as easily as using the standard CosmWasm interfaces. -What is left is actually wiring them up in your chain so they work as desired. - -Note, in order to ensure that no one tries to run the contracts on an unsupported chain, -you will want to include a `requires_XYZ` directive in your `bindings` library, this will -mean that only blockchain apps that explicitly declare their support for the `XYZ` extensions -(please rename XYZ to your project name) will allow the contract to be uploaded, and others -get error messages upon upload, not while running a critical feature later on. -You just need to add [a line like this](https://github.com/CosmWasm/terra-contracts/blob/master/packages/bindings/src/lib.rs#L13-L16) -to your binding library to add the requirement to any contract that imports your `bindings` lib. - -### Calling into the SDK - -Before I show how this works, I want to remind you, if you have copied `x/wasm`, -please **do not make these changes to `x/wasm`**. - -We will add a new module, eg. `x/contracts`, that will contain custom -bindings between CosmWasm contracts and your native modules. There are two entry points -for you to use. The first is -[`CustomQuerier`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/query_plugins.go#L35), -which allows you to handle your custom queries. The second is -[`CustomEncoder`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/handler_plugin.go#L30) -which allows you to convert the `CosmosMsg::Custom(YourMessage)` types to `[]sdk.Msg` to be dispatched. - -Writing stubs for these is rather simple. You can look at the `reflect_test.go` file to see this in action. -In particular, here [we define a `CustomQuerier`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/reflect_test.go#L355-L385), -and here [we define a `CustomHandler`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/reflect_test.go#L303-L353). -This code is responsible to take `json.RawMessage` from the raw bytes serialized from your custom types in rust and parse it into -Go structs. Then take these go structs and properly convert them for your custom SDK modules. - -You can look at the implementations for the `staking` module to see how to build these for non-trivial -cases, including passing in the `Keeper` via a closure. Here we -[encode staking messages](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/handler_plugin.go#L114-L192). -Note that withdraw returns 2 messages, which is an option you can use if needed to translate into native messages. -When we [handle staking queries](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/query_plugins.go#L109-L172) -we take in a `Keeper in the closure` and dispatch the custom `QueryRequest` from the contract to the native `Keeper` interface, -then encodes a response. When defining the return types, note that for proper parsing in the Rust contract, you -should properly name the JSON fields and use the `omitempty` keyword if Rust expects `Option`. You must also use -`omitempty` and pointers for all fields that correspond to a Rust `enum`, so exactly one field is serialized. - -### Wiring it all together - -Once you have writen and tested these custom callbacks for your module, you need to enable it in your application. -The first step is to write an integration test with a contract compiled with your custom SDK to ensure it works properly, -then you need to configure this in `app.go`. - -For the test cases, you must -[define the supported feature set](https://github.com/terpnetwork/terp-core/blob/ade03a1d39a9b8882e9a1ce80572d39d57bb9bc3/x/wasm/internal/keeper/reflect_test.go#L52) -to include your custom name (remember `requires_XYZ` above?). Then, when creating `TestInput`, -you can [pass in your custom encoder and querier](https://github.com/terpnetwork/terp-core/blob/ade03a1d39a9b8882e9a1ce80572d39d57bb9bc3/x/wasm/internal/keeper/reflect_test.go#L52). -Run a few tests with your compiled contract, ideally exercising the majority of the interfaces to ensure that all parsing between the contract and -the SDK is implemented properly. - -Once you have tested this and are happy with the results, you can wire it up in `app.go`. -Just edit [the default `NewKeeper` constructor](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/app/app.go#L257-L258) -to have the proper `availableCapabilities` and pass in the `CustomEncoder` and `CustomQuerier` as the last two arguments to `NewKeeper`. -Now you can compile your chain and upload your custom contracts on it. \ No newline at end of file diff --git a/Makefile b/Makefile index f6069ef..dc9eaa6 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,32 @@ #!/usr/bin/make -f -PACKAGES_SIMTEST=$(shell go list ./... | grep '/simulation') -VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//') +BRANCH := $(shell git rev-parse --abbrev-ref HEAD) COMMIT := $(shell git log -1 --format='%H') +VERSION := $(shell echo $(shell git describe --tags) | sed 's/^v//') +BINDIR ?= $(GOPATH)/bin +APP = ./app + +# don't override user values +ifeq (,$(VERSION)) + VERSION := $(shell git describe --tags) + # if VERSION is empty, then populate it with branch's name and raw commit hash + ifeq (,$(VERSION)) + VERSION := $(BRANCH)-$(COMMIT) + endif +endif + +PACKAGES_SIMTEST=$(shell go list ./... | grep '/simulation') LEDGER_ENABLED ?= true SDK_PACK := $(shell go list -m github.com/cosmos/cosmos-sdk | sed 's/ /\@/g') -BINDIR ?= $(GOPATH)/bin -SIMAPP = ./app + +# don't override user values +ifeq (,$(VERSION)) + VERSION := $(shell git describe --tags) + # if VERSION is empty, then populate it with branch's name and raw commit hash + ifeq (,$(VERSION)) + VERSION := $(BRANCH)-$(COMMIT) + endif +endif # for dockerized protobuf tools DOCKER := $(shell which docker) @@ -76,7 +96,14 @@ BUILD_FLAGS := -tags "$(build_tags_comma_sep)" -ldflags '$(ldflags)' -trimpath # The below include contains the tools and runsim targets. include contrib/devtools/Makefile -all: install lint test +all: install + @echo "--> project root: go mod tidy" + @go mod tidy + @echo "--> project root: linting --fix" + @GOGC=1 golangci-lint run --fix --timeout=8m + +install: go.sum + go install -mod=readonly $(BUILD_FLAGS) ./cmd/terpd build: go.sum ifeq ($(OS),Windows_NT) @@ -96,11 +123,33 @@ else go build -mod=readonly $(BUILD_FLAGS) -o build/contract_tests ./cmd/contract_tests endif -install: go.sum - go install -mod=readonly $(BUILD_FLAGS) ./cmd/terpd +test-node: + CHAIN_ID="local-1" HOME_DIR="~/.terp1" TIMEOUT_COMMIT="500ms" CLEAN=true sh scripts/test_node.sh + +############################################################################### +### Testing ### +############################################################################### -######################################## -### Tools & dependencies +test: test-unit +test-all: check test-race test-cover + +test-unit: + @VERSION=$(VERSION) go test -mod=readonly -tags='ledger test_ledger_mock' ./... + +benchmark: + @go test -mod=readonly -bench=. ./... + +test-sim-multi-seed-short: runsim + @echo "Running short multi-seed application simulation. This may take awhile!" + @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(APP) -ExitOnFail 50 5 TestFullAppSimulation + +test-sim-deterministic: runsim + @echo "Running short multi-seed application simulation. This may take awhile!" + @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(APP) -ExitOnFail 1 1 TestAppStateDeterminism + +############################################################################### +### Tools & dependencies ### +############################################################################### go-mod-cache: go.sum @echo "--> Download go modules to local cache" @@ -121,38 +170,6 @@ clean: distclean: clean rm -rf vendor/ -######################################## -### Testing - - -test: test-unit -test-all: check test-race test-cover - -test-unit: - @VERSION=$(VERSION) go test -mod=readonly -tags='ledger test_ledger_mock' ./... - -test-race: - @VERSION=$(VERSION) go test -mod=readonly -race -tags='ledger test_ledger_mock' ./... - -test-cover: - @go test -mod=readonly -timeout 30m -race -coverprofile=coverage.txt -covermode=atomic -tags='ledger test_ledger_mock' ./... - -benchmark: - @go test -mod=readonly -bench=. ./... - -test-sim-import-export: runsim - @echo "Running application import/export simulation. This may take several minutes..." - @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 50 5 TestAppImportExport - -test-sim-multi-seed-short: runsim - @echo "Running short multi-seed application simulation. This may take awhile!" - @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 50 5 TestFullAppSimulation - -test-sim-deterministic: runsim - @echo "Running short multi-seed application simulation. This may take awhile!" - @$(BINDIR)/runsim -Jobs=4 -SimAppPkg=$(SIMAPP) -ExitOnFail 1 1 TestAppStateDeterminism - - ############################################################################### ### Linting ### ############################################################################### @@ -170,11 +187,62 @@ format: format-tools find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs gofumpt -w find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs goimports -w -local github.com/terpnetwork/terp-core +############################################################################### +### e2e interchain test ### +############################################################################### + + # Executes basic chain tests via interchaintest +ictest-basic: rm-testcache + cd interchaintest && go test -race -v -run TestBasicTerpStart . + +ictest-ibchooks: rm-testcache + cd interchaintest && go test -race -v -run TestTerpIBCHooks . + +ictest-pfm: rm-testcache + cd interchaintest && go test -race -v -run TestPacketForwardMiddlewareRouter . + +ictest-tokenfactory: rm-testcache + cd interchaintest && go test -race -v -run TestTerpTokenFactory . + +ictest-feeshare: rm-testcache + cd interchaintest && go test -race -v -run TestTerpFeeShare . + +# Executes a basic chain upgrade test via interchaintest +ictest-upgrade: rm-testcache + cd interchaintest && go test -race -v -run TestBasicTerpUpgrade . + +# Executes a basic chain upgrade locally via interchaintest after compiling a local image as terpnetwork:local +ictest-upgrade-local: local-image ictest-upgrade + +# Executes IBC tests via interchaintest +ictest-ibc: rm-testcache + cd interchaintest && go test -race -v -run TestTerpGaiaIBCTransfer . + +rm-testcache: + go clean -testcache + +.PHONY: test-mutation ictest-basic ictest-upgrade ictest-ibc +############################################################################### +### heighliner ### +############################################################################### + +get-heighliner: + git clone https://github.com/strangelove-ventures/heighliner.git + cd heighliner && go install + +local-image: +ifeq (,$(shell which heighliner)) + echo 'heighliner' binary not found. Consider running `make get-heighliner` +else + heighliner build -c terpnetwork --local -f ./chains.yaml +endif + +.PHONY: get-heighliner local-image ############################################################################### ### Protobuf ### ############################################################################### -protoVer=0.11.6 +protoVer=0.13.1 protoImageName=ghcr.io/cosmos/proto-builder:$(protoVer) protoImage=$(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace $(protoImageName) @@ -184,11 +252,14 @@ proto-gen: @echo "Generating Protobuf files" @$(protoImage) sh ./scripts/protocgen.sh +proto-swagger-gen: + @echo "Generating Protobuf Swagger" + @$(protoImage) sh ./scripts/protoc_swagger_openapi_gen.sh + $(MAKE) update-swagger-docs + proto-format: @echo "Formatting Protobuf files" @$(protoImage) find ./ -name "*.proto" -exec clang-format -i {} \; -proto-swagger-gen: - @./scripts/protoc-swagger-gen.sh proto-lint: @$(DOCKER_BUF) lint --error-format=json @@ -199,4 +270,4 @@ proto-check-breaking: .PHONY: all install install-debug \ go-mod-cache draw-deps clean build format \ test test-all test-build test-cover test-unit test-race \ - test-sim-import-export build-windows-client \ + test-sim-import-export build-windows-client \ \ No newline at end of file diff --git a/README.md b/README.md index 22d28e1..a7a7c30 100644 --- a/README.md +++ b/README.md @@ -3,215 +3,61 @@ [![license](https://img.shields.io/github/license/terpnetwork/terp-core.svg)](https://github.com/terpnetwork/terp-core/blob/main/LICENSE) -This repository hosts `Terp-Core`, the Daemon binary logic of [Terp-Network](https://terp.network). - -This code was forked from the `notional-labs/wasmd` repository as a basis for main-network development. - -For critical security issues & disclosure, see [SECURITY.md](SECURITY.md). -## Compatibility with CosmWasm contracts - -## Compatibility - -A VM can support one or more contract-VM interface versions. The interface -version is communicated by the contract via a Wasm export. This is the current -compatibility list: - -| terpd | wasmvm | cosmwasm-vm | cosmwasm-std | -|--------|--------------|-------------|--------------| -| v1.0.0 | v1.2.0 | | 1.0-1.2 | -| v0.5.0 | v1.2.0 | | 1.0-1.2 | -| v0.4.0 | v1.2.0 | | 1.0-1.1 | - - -Note: `cosmwasm_std v1.0` means it supports contracts compiled by any `v1.0.0-betaX` or `1.0.x`. -It will also run contracts compiled with 1.x assuming they don't opt into any newer features. -The 1.x cosmwasm_vm will support all contracts with 1.0 <= version <= 1.x. - -Note that `cosmwasm-std` version defines which contracts are compatible with this system. The wasm code uploaded must -have been compiled with one of the supported `cosmwasm-std` versions, or will be rejected upon upload (with some error -message about "contract too old?" or "contract too new?"). `cosmwasm-vm` version defines the runtime used. It is a -breaking change to switch runtimes (you will need to organize a chain upgrade). As of `cosmwasm-vm 0.13` we are -using [wasmer](https://github.com/wasmerio/wasmer/) 1.0, which is significantly more performant than the older versions. - -## Supported Systems - -The supported systems are limited by the dlls created in [`wasmvm`](https://github.com/CosmWasm/wasmvm). In particular, **we only support MacOS and Linux**. -However, **M1 macs are not fully supported.** (Experimental support was merged with wasmd 0.24) -For linux, the default is to build for glibc, and we cross-compile with CentOS 7 to provide -backwards compatibility for `glibc 2.12+`. This includes all known supported distributions -using glibc (CentOS 7 uses 2.12, obsolete Debian Jessy uses 2.19). - -As of `0.9.0` we support `muslc` Linux systems, in particular **Alpine linux**, -which is popular in docker distributions. Note that we do **not** store the -static `muslc` build in the repo, so you must compile this yourself, and pass `-tags muslc`. -Please look at the [`Dockerfile`](./Dockerfile) for an example of how we build a static Go -binary for `muslc`. (Or just use this Dockerfile for your production setup). - +For issues & disclosure, see [SECURITY.md](SECURITY.md) ## Stability **This is beta software** It is run in some production systems, but we cannot yet provide a stability guarantee and have not yet gone through and audit of this codebase. -The APIs are pretty stable, but we cannot guarantee their stability until we reach v1.0. - Thank you to all projects who have run this code in your mainnets and testnets and given feedback to improve stability. -## Encoding -The used cosmos-sdk version is in transition migrating from amino encoding to protobuf for state. So are we now. - -We use standard cosmos-sdk encoding (amino) for all sdk Messages. However, the message body sent to all contracts, -as well as the internal state is encoded using JSON. Cosmwasm allows arbitrary bytes with the contract itself -responsible for decoding. For better UX, we often use `json.RawMessage` to contain these bytes, which enforces that it is -valid json, but also give a much more readable interface. If you want to use another encoding in the contracts, that is -a relatively minor change to terpd but would currently require a fork. Please open an issue if this is important for -your use case. - ## Quick Start ``` make install make test ``` -if you are using a linux without X or headless linux, look at [this article](https://ahelpme.com/linux/dbusexception-could-not-get-owner-of-name-org-freedesktop-secrets-no-such-name) or [#31](https://github.com/terpnetwork/terp-core/issues/31#issuecomment-577058321). ## Protobuf -The protobuf files for this project are published automatically to the [buf repository](https://buf.build/) to make integration easier: - -| terpd version | buf tag | -|---------------|---------------------------------------------------------------------------------------------------------------------------------------------| -| 1.0.0 | []() | - -Generate protobuf -```shell script +``` make proto-gen ``` -The generators are executed within a Docker [container](./contrib/prototools-docker), now. ## Dockerized -We provide a docker image to help with test setups. There are two modes to use it - -Build: `docker build -t terpnetwork/terp-core:latest .` or pull from dockerhub - ### Dev server -Bring up a local node with a test account containing tokens - -This is just designed for local testing/CI - do not use these scripts in production. -Very likely you will assign tokens to accounts whose mnemonics are public on github. - -```sh -docker volume rm -f terpd_data - -# pass password (one time) as env variable for setup, so we don't need to keep typing it -# add some addresses that you have private keys for (locally) to give them genesis funds -docker run --rm -it \ - -e PASSWORD=xxxxxxxxx \ - --mount type=volume,source=terpd_data,target=/root \ - terpnetwork/terp-core:latest /opt/setup_terpd.sh cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6 - -# This will start both terpd and rest-server, both are logged -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=terpd_data,target=/root \ - terpnetwork/terp-core:latest /opt/run_terpd.sh -``` ### CI - -For CI, we want to generate a template one time and save to disk/repo. Then we can start a chain copying the initial state, but not modifying it. This lets us get the same, fresh start every time. - +#### Github +Some pre-commit scripts to help with quality code practices: +**Linter** ```sh -# Init chain and pass addresses so they are non-empty accounts -rm -rf ./template && mkdir ./template -docker run --rm -it \ - -e PASSWORD=xxxxxxxxx \ - --mount type=bind,source=$(pwd)/template,target=/root \ - terpnetwork/terp-core:latest /opt/setup_terpd.sh cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6 - -sudo chown -R $(id -u):$(id -g) ./template - -# FIRST TIME -# bind to non-/root and pass an argument to run.sh to copy the template into /root -# we need terpd_data volume mount not just for restart, but also to view logs -docker volume rm -f terpd_data -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 9090:9090 \ - --mount type=bind,source=$(pwd)/template,target=/template \ - --mount type=volume,source=terpd_data,target=/root \ - terpnetwork/terp-core:latest /opt/run_terpd.sh /template - -# RESTART CHAIN with existing state -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=terpd_data,target=/root \ - terpnetwork/terp-core:latest /opt/run_terpd.sh +sh scripts/git/linter.sh ``` +**Markdown Linter** +```sh +sh scripts/git/markdown_lint.sh -## Runtime flags - -We provide a number of variables in `app/app.go` that are intended to be set via `-ldflags -X ...` -compile-time flags. This enables us to avoid copying a new binary directory over for each small change -to the configuration. - -Available flags: - -* `-X github.com/terpnetwork/terp-core/app.NodeDir=.terp` - set the config/data directory for the node (default `~/.terp`) -* `-X github.com/terpnetwork/terp-core/app.Bech32Prefix=terp` - set the bech32 prefix for all accounts (default `terp`) -* `-X github.com/terpnetwork/terp-core/app.ProposalsEnabled=true` - enable all x/wasm governance proposals (default `false`) -* `-X github.com/terpnetwork/terp-core/app.EnableSpecificProposals=MigrateContract,UpdateAdmin,ClearAdmin` - - enable a subset of the x/wasm governance proposal types (overrides `ProposalsEnabled`) - -Examples: - -* [`terpd`](./Makefile#L50-L55) is a generic, permissionless version using the `terp` bech32 prefix - -## Compile Time Parameters - -Besides those above variables (meant for custom terp compilation), there are a few more variables which -we allow blockchains to customize, but at compile time. If you build your own chain and import `x/wasm`, -you can adjust a few items via module parameters, but a few others did not fit in that, as they need to be -used by stateless `ValidateBasic()`. Thus, we made them public `var` and these can be overridden in the `app.go` -file of your custom chain. - -* `wasmtypes.MaxLabelSize = 64` to set the maximum label size on instantiation (default 128) -* `wasmtypes.MaxWasmSize=777000` to set the max size of compiled wasm to be accepted (default 819200) -* `wasmtypes.MaxProposalWasmSize=888000` to set the max size of gov proposal compiled wasm to be accepted (default 3145728) +``` +**Tidy** +```sh +sh scripts/git/markdown_lint.sh -## Genesis Configuration -We strongly suggest **to limit the max block gas in the genesis** and not use the default value (`-1` for infinite). -```json - "consensus_params": { - "block": { - "max_gas": "SET_YOUR_MAX_VALUE", ``` -Tip: if you want to lock this down to a permisisoned network, the following script can edit the genesis file -to only allow permissioned use of code upload or instantiating. (Make sure you set `app.ProposalsEnabled=true` -in this binary): +## Contributors +This framework is like a craft genetics lineage, one that has been fine tuned with love, trial and error, patience, and iterations. The following is a list of teams, companies, and contributors that are impactful to Terp Network's creation, massive respect! + +- CosmosSDK Contributors +- CosmWasm / Wasmd Contributors +- IBC Protocol Contributors +- Juno's Core-1 Contributors +- Hard-nett - TerpNet Foundation DAO +- Xiti - TerpNet Foundation DAO -`sed -i 's/permission": "Everybody"/permission": "Nobody"/' .../config/genesis.json` +If we forgot you in this list, let us know or open a PR ::) -## Contributors -Much thanks to all who have contributed to this project, from this app, to the `cosmwasm` framework, to example contracts and documentation. -Or even testing the app and bringing up critical issues. The following have helped bring this project to life: - -* Ethan Frey [ethanfrey](https://github.com/ethanfrey) -* Simon Warta [webmaster128](https://github.com/webmaster128) -* Alex Peters [alpe](https://github.com/alpe) -* Aaron Craelius [aaronc](https://github.com/aaronc) -* Sunny Aggarwal [sunnya97](https://github.com/sunnya97) -* Cory Levinson [clevinson](https://github.com/clevinson) -* Sahith Narahari [sahith-narahari](https://github.com/sahith-narahari) -* Jehan Tremback [jtremback](https://github.com/jtremback) -* Shane Vitarana [shanev](https://github.com/shanev) -* Billy Rennekamp [okwme](https://github.com/okwme) -* Westaking [westaking](https://github.com/westaking) -* Marko [marbar3778](https://github.com/marbar3778) -* JayB [kogisin](https://github.com/kogisin) -* Rick Dudley [AFDudley](https://github.com/AFDudley) -* KamiD [KamiD](https://github.com/KamiD) -* Valery Litvin [litvintech](https://github.com/litvintech) -* Leonardo Bragagnolo [bragaz](https://github.com/bragaz) - -Sorry if I forgot you from this list, just contact me or add yourself in a PR :) diff --git a/UPGRADING.md b/UPGRADING.md deleted file mode 100644 index 21de9cd..0000000 --- a/UPGRADING.md +++ /dev/null @@ -1,277 +0,0 @@ -# Upgrading - -With stargate, we have access to the `x/upgrade` module, which we can use to perform -inline upgrades. Please first read both the basic -[x/upgrade spec](https://github.com/cosmos/cosmos-sdk/blob/master/x/upgrade/spec/01_concepts.md) -and [go docs](https://godoc.org/github.com/cosmos/cosmos-sdk/x/upgrade#hdr-Performing_Upgrades) -for the background on the module. - -In this case, we will demo an update with no state migration. This is for cases when -there is a state-machine-breaking (but not state-breaking) bugfix or enhancement. -There are some -[open issues running some state migrations](https://github.com/cosmos/cosmos-sdk/issues/8265) -and we will wait for that to be fixed before trying those. - -The following will lead through running an upgrade on a local node, but the same process -would work on a real network (with more ops and governance coordination). - -## Setup - -We need to have two different versions of `wasmd` which depend on state-compatible -versions of the Cosmos SDK. We only focus on upgrade starting with stargate. You will -have to use the "dump state and restart" approach to move from launchpad to stargate. - -For this demo, we will show an upgrade from `v0.14.0` to musselnet branch. - -### Handler - -You will need to register a handler for the upgrade. This is specific to a particular -testnet and upgrade path, and the default `wasmd` will never have a registered handler -on master. In this case, we make a `musselnet` branch off of `v0.14.0` just -registering one handler with a given name. - -Look at [PR 351](https://github.com/terpnetwork/terp-core/pull/351/files) for an example -of a minimal handler. We do not make any state migrations, but rather use this -as a flag to coordinate all validators to stop the old version at one height, and -start the specified v2 version on the next block. - -### Prepare binaries - -Let's get the two binaries we want to test, the pre-upgrade and the post-upgrade -binaries. In this case the pre-release is already a published to docker hub and -can be downloaded simply via: - -`docker pull cosmwasm/wasmd:v0.14.0` - -(If this is not yet released, build it from the tip of master) - -The post-release is not published, so we can build it ourselves. Check out this -`wasmd` repo, and the proper `musselnet` branch: - -``` -# use musselnet-v2 tag once that exists -git checkout musselnet -docker build . -t wasmd:musselnet-v2 -``` - -Verify they are both working for you locally: - -``` -docker run cosmwasm/wasmd:v0.14.0 wasmd version -docker run wasmd:musselnet-v2 wasmd version -``` - -## Start the pre-release chain - -Follow the normal setup stage, but in this case we will want to have super short -governance voting period, 5 minutes rather than 2 days (or 2 weeks!). - -**Setup a client with private key** - -```sh -## TODO: I think we need to do this locally??? -docker volume rm -f musselnet_client - -docker run --rm -it \ - -e PASSWORD=1234567890 \ - --mount type=volume,source=musselnet_client,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/setup_wasmd.sh - -# enter "1234567890" when prompted -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - cosmwasm/wasmd:v0.14.0 wasmd keys show -a validator -# use the address returned above here -CLIENT=wasm1anavj4eyxkdljp27sedrdlt9dm26c8a7a8p44l -``` - -**Setup the blockchain node** - -```sh -docker volume rm -f musselnet - -# add your testing address here, so you can do something with the client -docker run --rm -it \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/setup_wasmd.sh $CLIENT - -# Update the voting times in the genesis file -docker run --rm -it \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 sed -ie 's/172800s/300s/' /root/.terp/config/genesis.json - -# start up the blockchain and all embedded servers as one process -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/run_wasmd.sh -``` - -## Sanity checks - -Let's use our client node to query the current state and send some tokens to a -random address: - -```sh -RCPT=wasm1pypadqklna33nv3gl063rd8z9q8nvauaalz820 - -# note --network=host so it can connect to the other docker image -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $CLIENT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $RCPT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx send validator $RCPT 500000ucosm,600000ustake --chain-id testing - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $RCPT -``` - -## Take majority control of the chain - -In genesis we have a valiator with 250 million `ustake` bonded. We want to be easily -able to pass a proposal with our client. Let us bond 700 million `ustake` to ensure -we have > 67% of the voting power and will pass with the validator not voting. - -```sh -# get the "operator_address" (wasmvaloper...) from here -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query staking validators -VALIDATOR=...... - -# and stake here -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx staking delegate $VALIDATOR 750000000ustake \ - --from validator --chain-id testing -``` - -## Vote on the upgrade - -Now that we see the chain is running and producing blocks, and our client has -enough token to control the netwrok, let's create a governance -upgrade proposal for the new chain to move to `musselnet-v2` (this must be the -same name as we use in the handler we created above, change this to match what -you put in your handler): - -```sh -# create the proposal -# check the current height and add 100-200 or so for the upgrade time -# (the voting period is ~60 blocks) -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx gov submit-proposal software-upgrade musselnet-v2 \ - --upgrade-height=500 --deposit=10000000ustake \ - --title="Upgrade" --description="Upgrade to musselnet-v2" \ - --from validator --chain-id testing - -# make sure it looks good -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov proposal 1 - -# vote for it -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx gov vote 1 yes \ - --from validator --chain-id testing - -# ensure vote was counted -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov votes 1 -``` - -## Swap out binaries - -Now, we just wait about 5 minutes for the vote to pass, and ensure it is passed: - -```sh -# make sure it looks good -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov proposal 1 -``` - -After this, we just let the chain run and open the terminal so you can see the log files. -It should keep producing blocks until it hits height 500 (or whatever you set there), -when the process will print a huge stacktrace and hang. Immediately before the stack trace, you -should see a line like this (burried under tons of tendermint logs): - -`8:50PM ERR UPGRADE "musselnet-v2" NEEDED at height: 100:` - -Kill it with Ctrl-C, and then try to restart with the pre-upgrade version and it should -immediately fail on startup, with the same error message as above. - -```sh -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/run_wasmd.sh -``` - -Then, we start with the post-upgrade version and see it properly update: - -```sh -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - wasmd:musselnet-v2 /opt/run_wasmd.sh -``` - -On a real network, operators will have to be awake when the upgrade plan is activated -and manually perform this switch, or use some automated tooling like -[cosmosvisor](https://github.com/cosmos/cosmos-sdk/blob/master/cosmovisor/README.md). - -## Check final state - -Now that we have upgraded, we can use the new client version. Let's do a brief -sanity check to ensure our balances are proper, and our stake remains -delegated. That and continued block production should be a good sign the upgrade -was successful: - -```sh -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query bank balances $CLIENT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query bank balances $RCPT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query staking delegations $CLIENT -``` diff --git a/api_migration.md b/api_migration.md deleted file mode 100644 index c9aedd8..0000000 --- a/api_migration.md +++ /dev/null @@ -1,36 +0,0 @@ -# Changes to the api - -## [\#196](https://github.com/CosmWasm/wasmd/issues/196) - Move history of contract code migrations to their own prefix store - -The `ContractDetails.initMsg` used in cosmJs was moved into a new entity `ContractCodeHistoryEntry`. They contain code updates to a contract. - -### Route -This data is available via a new route `/wasm/contract/{contractAddr}/history` - -### Response -A list of ContractCodeHistoryEntries with following fields: -* `operation` can be any of `"Init", "Migrate", "Genesis"` -* `code_id` uint64 -* `msg` as raw json - -### Errors -* 404 - for an unknown contract - -### CLI -`wasmd query wasm contract-history [bech32_address] to print all the code changes.` -Example: -`wasmd query wasm contract-history cosmos18r5szma8hm93pvx6lwpjwyxruw27e0k5uw835c` -```json -[ - { - "operation": "Init", - "code_id": 1, - "msg": "\"init-msg\"" - }, - { - "operation": "Migrate", - "code_id": 2, - "msg": "\"migrate-msg\"" - } -] -``` diff --git a/app/ante.go b/app/ante.go index 2d26608..0432ffc 100644 --- a/app/ante.go +++ b/app/ante.go @@ -5,22 +5,45 @@ import ( storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/x/auth/ante" + govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" ibcante "github.com/cosmos/ibc-go/v7/modules/core/ante" "github.com/cosmos/ibc-go/v7/modules/core/keeper" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - wasmTypes "github.com/terpnetwork/terp-core/x/wasm/types" + feeshareante "github.com/terpnetwork/terp-core/v2/x/feeshare/ante" + feesharekeeper "github.com/terpnetwork/terp-core/v2/x/feeshare/keeper" + globalfeeante "github.com/terpnetwork/terp-core/v2/x/globalfee/ante" + globalfeekeeper "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" + + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmTypes "github.com/CosmWasm/wasmd/x/wasm/types" ) +// Lower back to 1 mil after https://github.com/cosmos/relayer/issues/1255 +const maxBypassMinFeeMsgGasUsage = 2_000_000 + // HandlerOptions extend the SDK's AnteHandler options by requiring the IBC // channel keeper. type HandlerOptions struct { ante.HandlerOptions + GovKeeper govkeeper.Keeper IBCKeeper *keeper.Keeper + FeeShareKeeper feesharekeeper.Keeper + BankKeeperFork feeshareante.BankKeeper WasmConfig *wasmTypes.WasmConfig TXCounterStoreKey storetypes.StoreKey + Cdc codec.BinaryCodec + + BypassMinFeeMsgTypes []string + + GlobalFeeKeeper globalfeekeeper.Keeper + StakingKeeper stakingkeeper.Keeper + + TxEncoder sdk.TxEncoder } func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { @@ -49,7 +72,9 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { ante.NewTxTimeoutHeightDecorator(), ante.NewValidateMemoDecorator(options.AccountKeeper), ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), + globalfeeante.NewFeeDecorator(options.BypassMinFeeMsgTypes, options.GlobalFeeKeeper, options.StakingKeeper, maxBypassMinFeeMsgGasUsage), ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker), + feeshareante.NewFeeSharePayoutDecorator(options.BankKeeperFork, options.FeeShareKeeper), ante.NewSetPubKeyDecorator(options.AccountKeeper), // SetPubKeyDecorator must be called before all signature verification decorators ante.NewValidateSigCountDecorator(options.AccountKeeper), ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer), diff --git a/app/app.go b/app/app.go index a9d5c9a..fe834ff 100644 --- a/app/app.go +++ b/app/app.go @@ -6,10 +6,12 @@ import ( "io" "os" "path/filepath" + "reflect" "strings" autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" + errorsmod "cosmossdk.io/errors" dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" @@ -32,6 +34,8 @@ import ( "github.com/cosmos/cosmos-sdk/store/streaming" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/address" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" @@ -115,26 +119,48 @@ import ( ibcclient "github.com/cosmos/ibc-go/v7/modules/core/02-client" ibcclientclient "github.com/cosmos/ibc-go/v7/modules/core/02-client/client" ibcclienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" + ibcchanneltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" ibcmock "github.com/cosmos/ibc-go/v7/testing/mock" - "github.com/terpnetwork/terp-core/x/tokenfactory/bindings" + "github.com/terpnetwork/terp-core/v2/x/feeshare" + feesharekeeper "github.com/terpnetwork/terp-core/v2/x/feeshare/keeper" + feesharetypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" + "github.com/terpnetwork/terp-core/v2/x/globalfee" + globalfeekeeper "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" + globalfeetypes "github.com/terpnetwork/terp-core/v2/x/globalfee/types" + + ibchooks "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7" + ibchookskeeper "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7/keeper" + ibchookstypes "github.com/cosmos/ibc-apps/modules/ibc-hooks/v7/types" + + packetforward "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router" + packetforwardkeeper "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/keeper" + packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/types" + + icq "github.com/cosmos/ibc-apps/modules/async-icq/v7" + icqkeeper "github.com/cosmos/ibc-apps/modules/async-icq/v7/keeper" + icqtypes "github.com/cosmos/ibc-apps/modules/async-icq/v7/types" + + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings" "github.com/spf13/cast" govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - "github.com/terpnetwork/terp-core/x/wasm" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" + v2 "github.com/terpnetwork/terp-core/v2/app/upgrades/v2" + + "github.com/CosmWasm/wasmd/x/wasm" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" // token factory - "github.com/terpnetwork/terp-core/x/tokenfactory" - tokenfactorykeeper "github.com/terpnetwork/terp-core/x/tokenfactory/keeper" - tokenfactorytypes "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory" + tokenfactorykeeper "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" + tokenfactorytypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" // unnamed import of statik for swagger UI support _ "github.com/cosmos/cosmos-sdk/client/docs/statik" // statik for swagger UI support @@ -159,17 +185,23 @@ var ( EnableSpecificProposals = "" ) +var tokenFactoryCapabilities = []string{ + tokenfactorytypes.EnableBurnFrom, + tokenfactorytypes.EnableForceTransfer, + tokenfactorytypes.EnableSetMetadata, +} + // GetEnabledProposals parses the ProposalsEnabled / EnableSpecificProposals values to // produce a list of enabled proposals to pass into wasmd app. -func GetEnabledProposals() []wasm.ProposalType { +func GetEnabledProposals() []wasmtypes.ProposalType { if EnableSpecificProposals == "" { if ProposalsEnabled == "true" { - return wasm.EnableAllProposals + return wasmtypes.EnableAllProposals } - return wasm.DisableAllProposals + return wasmtypes.DisableAllProposals } chunks := strings.Split(EnableSpecificProposals, ",") - proposals, err := wasm.ConvertToProposals(chunks) + proposals, err := wasmtypes.ConvertToProposals(chunks) if err != nil { panic(err) } @@ -197,6 +229,37 @@ var ( Bech32PrefixConsPub = Bech32Prefix + sdk.PrefixValidator + sdk.PrefixConsensus + sdk.PrefixPublic ) +func init() { + SetAddressPrefixes() +} + +// SetAddressPrefixes builds the Config with Bech32 addressPrefix and publKeyPrefix for accounts, validators, and consensus nodes and verifies that addreeses have correct format. +func SetAddressPrefixes() { + config := sdk.GetConfig() + config.SetBech32PrefixForAccount(Bech32PrefixAccAddr, Bech32PrefixAccPub) + config.SetBech32PrefixForValidator(Bech32PrefixValAddr, Bech32PrefixValPub) + config.SetBech32PrefixForConsensusNode(Bech32PrefixConsAddr, Bech32PrefixConsPub) + + // This is copied from the cosmos sdk v0.43.0-beta1 + // source: https://github.com/cosmos/cosmos-sdk/blob/v0.43.0-beta1/types/address.go#L141 + config.SetAddressVerifier(func(bytes []byte) error { + if len(bytes) == 0 { + return errorsmod.Wrap(sdkerrors.ErrUnknownAddress, "addresses cannot be empty") + } + + if len(bytes) > address.MaxAddrLen { + return errorsmod.Wrapf(sdkerrors.ErrUnknownAddress, "address max length is %d, got %d", address.MaxAddrLen, len(bytes)) + } + + // TODO: Do we want to allow addresses of lengths other than 20 and 32 bytes? + if len(bytes) != 20 && len(bytes) != 32 { + return errorsmod.Wrapf(sdkerrors.ErrUnknownAddress, "address length must be 20 or 32 bytes, got %d", len(bytes)) + } + + return nil + }) +} + var ( // ModuleBasics defines the module BasicManager is in charge of setting up basic, // non-dependant module elements, such as codec registration @@ -236,6 +299,11 @@ var ( transfer.AppModuleBasic{}, ica.AppModuleBasic{}, ibcfee.AppModuleBasic{}, + icq.AppModuleBasic{}, + ibchooks.AppModuleBasic{}, + packetforward.AppModuleBasic{}, + feeshare.AppModuleBasic{}, + globalfee.AppModuleBasic{}, tokenfactory.AppModuleBasic{}, ) @@ -250,8 +318,10 @@ var ( nft.ModuleName: nil, ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, ibcfeetypes.ModuleName: nil, + icqtypes.ModuleName: nil, icatypes.ModuleName: nil, - wasm.ModuleName: {authtypes.Burner}, + globalfee.ModuleName: nil, + wasmtypes.ModuleName: {authtypes.Burner}, tokenfactorytypes.ModuleName: {authtypes.Minter, authtypes.Burner}, } ) @@ -296,11 +366,17 @@ type TerpApp struct { IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly IBCFeeKeeper ibcfeekeeper.Keeper + IBCHooksKeeper *ibchookskeeper.Keeper ICAControllerKeeper icacontrollerkeeper.Keeper + FeeShareKeeper feesharekeeper.Keeper + GlobalFeeKeeper globalfeekeeper.Keeper TokenFactoryKeeper tokenfactorykeeper.Keeper + ContractKeeper *wasmkeeper.PermissionedKeeper + PacketForwardKeeper *packetforwardkeeper.Keeper + ICQKeeper icqkeeper.Keeper ICAHostKeeper icahostkeeper.Keeper TransferKeeper ibctransferkeeper.Keeper - WasmKeeper wasm.Keeper + WasmKeeper wasmkeeper.Keeper ScopedIBCKeeper capabilitykeeper.ScopedKeeper ScopedICAHostKeeper capabilitykeeper.ScopedKeeper @@ -317,6 +393,10 @@ type TerpApp struct { // module configurator configurator module.Configurator + + // Middleware wrapper + Ics20WasmHooks *ibchooks.WasmHooks + HooksICS4Wrapper ibchooks.ICS4Middleware } // NewTerpApp returns a reference to an initialized TerpApp. @@ -325,9 +405,9 @@ func NewTerpApp( db dbm.DB, traceStore io.Writer, loadLatest bool, - enabledProposals []wasm.ProposalType, + enabledProposals []wasmtypes.ProposalType, appOpts servertypes.AppOptions, - wasmOpts []wasm.Option, + wasmOpts []wasmkeeper.Option, baseAppOptions ...func(*baseapp.BaseApp), ) *TerpApp { encodingConfig := MakeEncodingConfig() @@ -364,9 +444,14 @@ func NewTerpApp( ibcexported.StoreKey, ibctransfertypes.StoreKey, ibcfeetypes.StoreKey, - wasm.StoreKey, + wasmtypes.StoreKey, icahosttypes.StoreKey, icacontrollertypes.StoreKey, + icqtypes.StoreKey, + packetforwardtypes.StoreKey, + ibchookstypes.StoreKey, + feesharetypes.StoreKey, + globalfeetypes.StoreKey, tokenfactorytypes.StoreKey, ) @@ -397,8 +482,10 @@ func NewTerpApp( tkeys[paramstypes.TStoreKey], ) + govModAddress := authtypes.NewModuleAddress(govtypes.ModuleName).String() + // set the BaseApp's parameter store - app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, keys[consensusparamtypes.StoreKey], authtypes.NewModuleAddress(govtypes.ModuleName).String()) + app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, keys[consensusparamtypes.StoreKey], govModAddress) bApp.SetParamStore(&app.ConsensusParamsKeeper) // add capability keeper and ScopeToModule for ibc module @@ -412,7 +499,8 @@ func NewTerpApp( scopedICAHostKeeper := app.CapabilityKeeper.ScopeToModule(icahosttypes.SubModuleName) scopedICAControllerKeeper := app.CapabilityKeeper.ScopeToModule(icacontrollertypes.SubModuleName) scopedTransferKeeper := app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) - scopedWasmKeeper := app.CapabilityKeeper.ScopeToModule(wasm.ModuleName) + scopedICQKeeper := app.CapabilityKeeper.ScopeToModule(icqtypes.ModuleName) + scopedWasmKeeper := app.CapabilityKeeper.ScopeToModule(wasmtypes.ModuleName) app.CapabilityKeeper.Seal() // add keepers @@ -422,21 +510,21 @@ func NewTerpApp( authtypes.ProtoBaseAccount, maccPerms, Bech32Prefix, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govModAddress, ) app.BankKeeper = bankkeeper.NewBaseKeeper( appCodec, keys[banktypes.StoreKey], app.AccountKeeper, BlockedAddresses(), - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govModAddress, ) app.StakingKeeper = stakingkeeper.NewKeeper( appCodec, keys[stakingtypes.StoreKey], app.AccountKeeper, app.BankKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govModAddress, ) app.FeeGrantKeeper = feegrantkeeper.NewKeeper( appCodec, @@ -451,7 +539,7 @@ func NewTerpApp( app.AccountKeeper, app.BankKeeper, authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govModAddress, ) app.DistrKeeper = distrkeeper.NewKeeper( appCodec, @@ -460,7 +548,7 @@ func NewTerpApp( app.BankKeeper, app.StakingKeeper, authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govModAddress, ) app.SlashingKeeper = slashingkeeper.NewKeeper( @@ -468,15 +556,23 @@ func NewTerpApp( legacyAmino, keys[slashingtypes.StoreKey], app.StakingKeeper, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govModAddress, ) app.TokenFactoryKeeper = tokenfactorykeeper.NewKeeper( - keys[tokenfactorytypes.StoreKey], - app.GetSubspace(tokenfactorytypes.ModuleName), + appCodec, + app.keys[tokenfactorytypes.StoreKey], app.AccountKeeper, app.BankKeeper, app.DistrKeeper, + tokenFactoryCapabilities, + govModAddress, + ) + + // register the staking hooks + // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks + app.StakingKeeper.SetHooks( + stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), ) invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) @@ -491,14 +587,13 @@ func NewTerpApp( app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.AccountKeeper) - // register the staking hooks - // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks - app.StakingKeeper.SetHooks( - stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), + app.AuthzKeeper = authzkeeper.NewKeeper( + keys[authzkeeper.StoreKey], + appCodec, + app.MsgServiceRouter(), + app.AccountKeeper, ) - app.AuthzKeeper = authzkeeper.NewKeeper(keys[authzkeeper.StoreKey], appCodec, app.MsgServiceRouter(), app.AccountKeeper) - groupConfig := group.DefaultConfig() /* Example of setting group params: @@ -519,7 +614,7 @@ func NewTerpApp( appCodec, homePath, app.BaseApp, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govModAddress, ) app.IBCKeeper = ibckeeper.NewKeeper( @@ -554,7 +649,7 @@ func NewTerpApp( app.StakingKeeper, app.MsgServiceRouter(), govConfig, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govModAddress, ) app.GovKeeper = *govKeeper.SetHooks( @@ -580,12 +675,41 @@ func NewTerpApp( // If evidence needs to be handled for the app, set routes in router here and seal app.EvidenceKeeper = *evidenceKeeper + // Configure the hooks keeper + hooksKeeper := ibchookskeeper.NewKeeper( + keys[ibchookstypes.StoreKey], + ) + app.IBCHooksKeeper = &hooksKeeper + + terpPrefix := sdk.GetConfig().GetBech32AccountAddrPrefix() + wasmHooks := ibchooks.NewWasmHooks(app.IBCHooksKeeper, &app.WasmKeeper, terpPrefix) // The contract keeper needs to be set later // The contract keeper needs to be set later + app.Ics20WasmHooks = &wasmHooks + app.HooksICS4Wrapper = ibchooks.NewICS4Middleware( + app.IBCKeeper.ChannelKeeper, + app.Ics20WasmHooks, + ) + // IBC Fee Module keeper app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, keys[ibcfeetypes.StoreKey], - app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware + appCodec, + keys[ibcfeetypes.StoreKey], + app.HooksICS4Wrapper, // replaced with IBC middleware + app.IBCKeeper.ChannelKeeper, + &app.IBCKeeper.PortKeeper, + app.AccountKeeper, + app.BankKeeper, + ) + + // Initialize packet forward middleware router + app.PacketForwardKeeper = packetforwardkeeper.NewKeeper( + appCodec, + keys[packetforwardtypes.StoreKey], + app.GetSubspace(packetforwardtypes.ModuleName), + app.TransferKeeper, // Will be zero-value here. Reference is set later on with SetTransferKeeper. + app.IBCKeeper.ChannelKeeper, + app.DistrKeeper, + app.BankKeeper, app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, ) // Create Transfer Keepers @@ -593,7 +717,8 @@ func NewTerpApp( appCodec, keys[ibctransfertypes.StoreKey], app.GetSubspace(ibctransfertypes.ModuleName), - app.IBCFeeKeeper, // ISC4 Wrapper: fee IBC middleware + // The ICS4Wrapper is replaced by the PacketForwardKeeper instead of the channel so that sending can be overridden by the middleware + app.PacketForwardKeeper, app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, app.AccountKeeper, @@ -601,19 +726,25 @@ func NewTerpApp( scopedTransferKeeper, ) - // IBC Fee Module keeper - app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, keys[ibcfeetypes.StoreKey], - app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware + app.PacketForwardKeeper.SetTransferKeeper(app.TransferKeeper) + + // ICQ Keeper + app.ICQKeeper = icqkeeper.NewKeeper( + appCodec, + keys[icqtypes.StoreKey], + app.GetSubspace(icqtypes.ModuleName), + app.IBCKeeper.ChannelKeeper, // may be replaced with middleware app.IBCKeeper.ChannelKeeper, - &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, + &app.IBCKeeper.PortKeeper, + scopedICQKeeper, + app.BaseApp.GRPCQueryRouter(), ) app.ICAHostKeeper = icahostkeeper.NewKeeper( appCodec, keys[icahosttypes.StoreKey], app.GetSubspace(icahosttypes.SubModuleName), - app.IBCFeeKeeper, // use ics29 fee as ics4Wrapper in middleware stack + app.HooksICS4Wrapper, app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, app.AccountKeeper, @@ -642,13 +773,14 @@ func NewTerpApp( // See https://github.com/CosmWasm/cosmwasm/blob/main/docs/CAPABILITIES-BUILT-IN.md availableCapabilities := "iterator,staking,stargate,cosmwasm_1_1,cosmwasm_1_2,token_factory" wasmOpts = append(bindings.RegisterCustomPlugins(&app.BankKeeper, &app.TokenFactoryKeeper), wasmOpts...) - app.WasmKeeper = wasm.NewKeeper( + app.WasmKeeper = wasmkeeper.NewKeeper( appCodec, - keys[wasm.StoreKey], + keys[wasmtypes.StoreKey], app.AccountKeeper, app.BankKeeper, app.StakingKeeper, distrkeeper.NewQuerier(app.DistrKeeper), + app.IBCFeeKeeper, // ISC4 Wrapper: fee IBC middleware app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, scopedWasmKeeper, @@ -658,13 +790,28 @@ func NewTerpApp( wasmDir, wasmConfig, availableCapabilities, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), + govModAddress, wasmOpts..., ) + app.FeeShareKeeper = feesharekeeper.NewKeeper( + keys[feesharetypes.StoreKey], + appCodec, + app.BankKeeper, + app.WasmKeeper, + app.AccountKeeper, + authtypes.FeeCollectorName, + govModAddress, + ) + + app.GlobalFeeKeeper = globalfeekeeper.NewKeeper( + appCodec, + keys[globalfeetypes.StoreKey], + govModAddress, + ) // The gov proposal types can be individually enabled if len(enabledProposals) != 0 { - govRouter.AddRoute(wasm.RouterKey, wasm.NewWasmProposalHandler(app.WasmKeeper, enabledProposals)) + govRouter.AddRoute(wasmtypes.RouterKey, wasmkeeper.NewWasmProposalHandler(app.WasmKeeper, enabledProposals)) //nolint:staticcheck } // Set legacy router for backwards compatibility with gov v1beta1 app.GovKeeper.SetLegacyRouter(govRouter) @@ -673,6 +820,14 @@ func NewTerpApp( var transferStack porttypes.IBCModule transferStack = transfer.NewIBCModule(app.TransferKeeper) transferStack = ibcfee.NewIBCMiddleware(transferStack, app.IBCFeeKeeper) + transferStack = ibchooks.NewIBCMiddleware(transferStack, &app.HooksICS4Wrapper) + transferStack = packetforward.NewIBCMiddleware( + transferStack, + app.PacketForwardKeeper, + 0, + packetforwardkeeper.DefaultForwardTransferPacketTimeoutTimestamp, + packetforwardkeeper.DefaultRefundTransferPacketTimeoutTimestamp, + ) // Create Interchain Accounts Stack // SendPacket, since it is originating from the application to core IBC: @@ -695,16 +850,22 @@ func NewTerpApp( wasmStack = wasm.NewIBCHandler(app.WasmKeeper, app.IBCKeeper.ChannelKeeper, app.IBCFeeKeeper) wasmStack = ibcfee.NewIBCMiddleware(wasmStack, app.IBCFeeKeeper) + // create ICQ module + icqModule := icq.NewIBCModule(app.ICQKeeper) + // Create static IBC router, add app routes, then set and seal it ibcRouter := porttypes.NewRouter(). AddRoute(ibctransfertypes.ModuleName, transferStack). - AddRoute(wasm.ModuleName, wasmStack). + AddRoute(wasmtypes.ModuleName, wasmStack). AddRoute(icacontrollertypes.SubModuleName, icaControllerStack). - AddRoute(icahosttypes.SubModuleName, icaHostStack) + AddRoute(icahosttypes.SubModuleName, icaHostStack). + AddRoute(icqtypes.ModuleName, icqModule) app.IBCKeeper.SetRouter(ibcRouter) /**** Module Options ****/ + bondDenom := app.GetChainBondDenom() + // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment // we prefer to be more strict in what arguments the modules expect. skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants)) @@ -735,12 +896,17 @@ func NewTerpApp( groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), consensus.NewAppModule(appCodec, app.ConsensusParamsKeeper), - tokenfactory.NewAppModule(app.TokenFactoryKeeper, app.AccountKeeper, app.BankKeeper), + feeshare.NewAppModule(app.FeeShareKeeper, app.AccountKeeper, app.GetSubspace(feesharetypes.ModuleName)), + globalfee.NewAppModule(appCodec, app.GlobalFeeKeeper, bondDenom), + tokenfactory.NewAppModule(app.TokenFactoryKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(tokenfactorytypes.ModuleName)), wasm.NewAppModule(appCodec, &app.WasmKeeper, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.MsgServiceRouter(), app.GetSubspace(wasmtypes.ModuleName)), ibc.NewAppModule(app.IBCKeeper), transfer.NewAppModule(app.TransferKeeper), ibcfee.NewAppModule(app.IBCFeeKeeper), ica.NewAppModule(&app.ICAControllerKeeper, &app.ICAHostKeeper), + icq.NewAppModule(app.ICQKeeper), + packetforward.NewAppModule(app.PacketForwardKeeper), + ibchooks.NewAppModule(app.AccountKeeper), 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 ) @@ -760,8 +926,13 @@ func NewTerpApp( ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, + icqtypes.ModuleName, + packetforwardtypes.ModuleName, + feesharetypes.ModuleName, + globalfee.ModuleName, + ibchookstypes.ModuleName, tokenfactorytypes.ModuleName, - wasm.ModuleName, + wasmtypes.ModuleName, ) app.ModuleManager.SetOrderEndBlockers( @@ -776,8 +947,13 @@ func NewTerpApp( ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, + icqtypes.ModuleName, + packetforwardtypes.ModuleName, + feesharetypes.ModuleName, + globalfee.ModuleName, + ibchookstypes.ModuleName, tokenfactorytypes.ModuleName, - wasm.ModuleName, + wasmtypes.ModuleName, ) // NOTE: The genutils module must occur after staking so that pools are @@ -800,8 +976,13 @@ func NewTerpApp( icatypes.ModuleName, ibcfeetypes.ModuleName, // wasm after ibc transfer + feesharetypes.ModuleName, + globalfee.ModuleName, + icqtypes.ModuleName, + packetforwardtypes.ModuleName, + ibchookstypes.ModuleName, tokenfactorytypes.ModuleName, - wasm.ModuleName, + wasmtypes.ModuleName, } app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...) app.ModuleManager.SetOrderExportGenesis(genesisModuleOrder...) @@ -815,7 +996,7 @@ func NewTerpApp( // RegisterUpgradeHandlers is used for registering any on-chain upgrades. // Make sure it's called after `app.ModuleManager` and `app.configurator` are set. - app.RegisterUpgradeHandlers() + app.setupUpgradeHandlers() autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.ModuleManager.Modules)) @@ -848,7 +1029,7 @@ func NewTerpApp( app.SetInitChainer(app.InitChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) - app.setAnteHandler(encodingConfig.TxConfig, wasmConfig, keys[wasm.StoreKey]) + app.setAnteHandler(encodingConfig.TxConfig, wasmConfig, keys[wasmtypes.StoreKey]) // must be before Loading version // requires the snapshot store to be created and registered as a BaseAppOption @@ -868,25 +1049,9 @@ func NewTerpApp( app.ScopedICAHostKeeper = scopedICAHostKeeper app.ScopedICAControllerKeeper = scopedICAControllerKeeper - // In v0.46, the SDK introduces _postHandlers_. PostHandlers are like - // antehandlers, but are run _after_ the `runMsgs` execution. They are also - // defined as a chain, and have the same signature as antehandlers. - // - // In baseapp, postHandlers are run in the same store branch as `runMsgs`, - // meaning that both `runMsgs` and `postHandler` state will be committed if - // both are successful, and both will be reverted if any of the two fails. - // - // The SDK exposes a default postHandlers chain, which comprises of only - // one decorator: the Transaction Tips decorator. However, some chains do - // not need it by default, so feel free to comment the next line if you do - // not need tips. - // To read more about tips: - // https://docs.cosmos.network/main/core/tips.html - // - // Please note that changing any of the anteHandler or postHandler chain is - // likely to be a state-machine breaking change, which needs a coordinated - // upgrade. - app.setPostHandler() + // set the contract keeper for the Ics20WasmHooks + app.ContractKeeper = wasmkeeper.NewDefaultPermissionKeeper(app.WasmKeeper) + app.Ics20WasmHooks.ContractKeeper = &app.WasmKeeper // In v0.46, the SDK introduces _postHandlers_. PostHandlers are like // antehandlers, but are run _after_ the `runMsgs` execution. They are also @@ -930,13 +1095,23 @@ func (app *TerpApp) setAnteHandler(txConfig client.TxConfig, wasmConfig wasmtype HandlerOptions: ante.HandlerOptions{ AccountKeeper: app.AccountKeeper, BankKeeper: app.BankKeeper, - SignModeHandler: txConfig.SignModeHandler(), FeegrantKeeper: app.FeeGrantKeeper, + SignModeHandler: txConfig.SignModeHandler(), SigGasConsumer: ante.DefaultSigVerificationGasConsumer, }, - IBCKeeper: app.IBCKeeper, + GovKeeper: app.GovKeeper, + IBCKeeper: app.IBCKeeper, + FeeShareKeeper: app.FeeShareKeeper, + BankKeeperFork: app.BankKeeper, // since we need extra methods + WasmConfig: &wasmConfig, TXCounterStoreKey: txCounterStoreKey, + + BypassMinFeeMsgTypes: GetDefaultBypassFeeMessages(), + GlobalFeeKeeper: app.GlobalFeeKeeper, + StakingKeeper: *app.StakingKeeper, + + TxEncoder: app.txConfig.TxEncoder(), }, ) if err != nil { @@ -945,6 +1120,18 @@ func (app *TerpApp) setAnteHandler(txConfig client.TxConfig, wasmConfig wasmtype app.SetAnteHandler(anteHandler) } +func GetDefaultBypassFeeMessages() []string { + return []string{ + // IBC + sdk.MsgTypeURL(&ibcchanneltypes.MsgRecvPacket{}), + sdk.MsgTypeURL(&ibcchanneltypes.MsgAcknowledgement{}), + sdk.MsgTypeURL(&ibcclienttypes.MsgUpdateClient{}), + sdk.MsgTypeURL(&ibctransfertypes.MsgTransfer{}), + sdk.MsgTypeURL(&ibcchanneltypes.MsgTimeout{}), + sdk.MsgTypeURL(&ibcchanneltypes.MsgTimeoutOnClose{}), + } +} + func (app *TerpApp) setPostHandler() { postHandler, err := posthandler.NewPostHandler( posthandler.HandlerOptions{}, @@ -1048,6 +1235,11 @@ func (app *TerpApp) GetSubspace(moduleName string) paramstypes.Subspace { return subspace } +// GetIBCKeeper implements the TestingApp interface. +func (app *TerpApp) GetIBCKeeper() *ibckeeper.Keeper { + return app.IBCKeeper +} + // SimulationManager implements the SimulationApp interface func (app *TerpApp) SimulationManager() *module.SimulationManager { return app.sm @@ -1119,13 +1311,84 @@ func BlockedAddresses() map[string]bool { return modAccAddrs } +func (app *TerpApp) setupUpgradeHandlers() { + // v2 upgrade handler + app.UpgradeKeeper.SetUpgradeHandler( + v2.UpgradeName, + v2.CreateUpgradeHandler( + app.ModuleManager, app.configurator, + app.FeeShareKeeper, app.GlobalFeeKeeper, + app.TokenFactoryKeeper, app.ICQKeeper, + *app.PacketForwardKeeper, + ), + ) + + // !! ATTENTION !! + + // When a planned update height is reached, the old binary will panic + // writing on disk the height and name of the update that triggered it + // This will read that value, and execute the preparations for the upgrade. + upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() + if err != nil { + panic(fmt.Errorf("failed to read upgrade info from disk: %w", err)) + } + + if app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { + return + } + + var storeUpgrades *storetypes.StoreUpgrades + + if upgradeInfo.Name == v2.UpgradeName { + storeUpgrades = &storetypes.StoreUpgrades{ + Added: []string{ + feesharetypes.ModuleName, + globalfeetypes.ModuleName, + packetforwardtypes.StoreKey, + ibchookstypes.StoreKey, + icqtypes.ModuleName, + }, + } + } + + if storeUpgrades != nil { + // configure store loader that checks if version == upgradeHeight and applies store upgrades + app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, storeUpgrades)) + } +} + +// ChainID gets chainID from private fields of BaseApp +// Should be removed once SDK 0.50.x will be adopted +func (app *TerpApp) ChainID() string { + field := reflect.ValueOf(app.BaseApp).Elem().FieldByName("chainID") + return field.String() +} + +func (app *TerpApp) GetChainBondDenom() string { + d := "uterp" + if strings.HasPrefix(app.ChainID(), "90u-") { + d = "uterpx" + } + return d +} + +// ModuleAccountAddrs returns all the app's module account addresses. +func (app *TerpApp) ModuleAccountAddrs() map[string]bool { + modAccAddrs := make(map[string]bool) + for acc := range GetMaccPerms() { + modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true + } + + return modAccAddrs +} + // initParamsKeeper init params keeper and its subspaces func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey storetypes.StoreKey) paramskeeper.Keeper { paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) paramsKeeper.Subspace(authtypes.ModuleName) paramsKeeper.Subspace(banktypes.ModuleName) - paramsKeeper.Subspace(stakingtypes.ModuleName) + paramsKeeper.Subspace(stakingtypes.ModuleName).WithKeyTable(stakingtypes.ParamKeyTable()) // Used for GlobalFee paramsKeeper.Subspace(minttypes.ModuleName) paramsKeeper.Subspace(distrtypes.ModuleName) paramsKeeper.Subspace(slashingtypes.ModuleName) @@ -1136,7 +1399,27 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(tokenfactorytypes.ModuleName) paramsKeeper.Subspace(icahosttypes.SubModuleName) paramsKeeper.Subspace(icacontrollertypes.SubModuleName) - paramsKeeper.Subspace(wasm.ModuleName) + paramsKeeper.Subspace(icqtypes.ModuleName) + paramsKeeper.Subspace(packetforwardtypes.ModuleName) + paramsKeeper.Subspace(globalfee.ModuleName) + paramsKeeper.Subspace(feesharetypes.ModuleName) + paramsKeeper.Subspace(wasmtypes.ModuleName) return paramsKeeper } + +// QuerierWrapper is a local wrapper around BaseApp that exports only the Queryable interface. +// This is used to pass the baseApp to Async ICQ without exposing all methods +type QuerierWrapper struct { + querier sdk.Queryable +} + +var _ sdk.Queryable = QuerierWrapper{} + +func NewQuerierWrapper(querier sdk.Queryable) QuerierWrapper { + return QuerierWrapper{querier: querier} +} + +func (q QuerierWrapper) Query(req abci.RequestQuery) abci.ResponseQuery { + return q.querier.Query(req) +} diff --git a/app/app_test.go b/app/app_test.go deleted file mode 100644 index f7f4ba3..0000000 --- a/app/app_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package app - -import ( - "os" - "testing" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm" -) - -var emptyWasmOpts []wasm.Option - -func TestWasmdExport(t *testing.T) { - db := dbm.NewMemDB() - gapp := NewTerpAppWithCustomOptions(t, false, SetupOptions{ - Logger: log.NewTMLogger(log.NewSyncWriter(os.Stdout)), - DB: db, - AppOpts: simtestutil.NewAppOptionsWithFlagHome(t.TempDir()), - }) - gapp.Commit() - - // Making a new app object with the db, so that initchain hasn't been called - newGapp := NewTerpApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, wasm.EnableAllProposals, simtestutil.NewAppOptionsWithFlagHome(t.TempDir()), emptyWasmOpts) - _, err := newGapp.ExportAppStateAndValidators(false, []string{}, nil) - require.NoError(t, err, "ExportAppStateAndValidators should not have an error") -} - -// ensure that blocked addresses are properly set in bank keeper -func TestBlockedAddrs(t *testing.T) { - gapp := Setup(t) - - for acc := range BlockedAddresses() { - t.Run(acc, func(t *testing.T) { - var addr sdk.AccAddress - if modAddr, err := sdk.AccAddressFromBech32(acc); err == nil { - addr = modAddr - } else { - addr = gapp.AccountKeeper.GetModuleAddress(acc) - } - require.True(t, gapp.BankKeeper.BlockedAddr(addr), "ensure that blocked addresses are properly set in bank keeper") - }) - } -} - -func TestGetMaccPerms(t *testing.T) { - dup := GetMaccPerms() - require.Equal(t, maccPerms, dup, "duplicated module account permissions differed from actual module account permissions") -} - -func TestGetEnabledProposals(t *testing.T) { - cases := map[string]struct { - proposalsEnabled string - specificEnabled string - expected []wasm.ProposalType - }{ - "all disabled": { - proposalsEnabled: "false", - expected: wasm.DisableAllProposals, - }, - "all enabled": { - proposalsEnabled: "true", - expected: wasm.EnableAllProposals, - }, - "some enabled": { - proposalsEnabled: "okay", - specificEnabled: "StoreCode,InstantiateContract", - expected: []wasm.ProposalType{wasm.ProposalTypeStoreCode, wasm.ProposalTypeInstantiateContract}, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - ProposalsEnabled = tc.proposalsEnabled - EnableSpecificProposals = tc.specificEnabled - proposals := GetEnabledProposals() - assert.Equal(t, tc.expected, proposals) - }) - } -} diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go index 6974e77..e13e086 100644 --- a/app/apptesting/test_suite.go +++ b/app/apptesting/test_suite.go @@ -3,16 +3,20 @@ package apptesting import ( "encoding/json" "fmt" - "os" "testing" "time" - "cosmossdk.io/math" + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/crypto/ed25519" "github.com/cometbft/cometbft/libs/log" tmtypes "github.com/cometbft/cometbft/proto/tendermint/types" + + "cosmossdk.io/math" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -22,18 +26,16 @@ import ( "github.com/cosmos/cosmos-sdk/types/tx/signing" authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" "github.com/cosmos/cosmos-sdk/x/authz" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" + banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - authzcodec "github.com/terpnetwork/terp-core/x/tokenfactory/types/authzcodec" - - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - - "github.com/terpnetwork/terp-core/app" + "github.com/terpnetwork/terp-core/v2/app" + appparams "github.com/terpnetwork/terp-core/v2/app/params" ) type KeeperTestHelper struct { @@ -46,14 +48,15 @@ type KeeperTestHelper struct { } var ( - SecondaryDenom = "uthiol" + SecondaryDenom = "uterpx" SecondaryAmount = sdk.NewInt(100000000) ) // Setup sets up basic environment for suite (App, Ctx, and test accounts) func (s *KeeperTestHelper) Setup() { - s.App = app.Setup(s.T()) - s.Ctx = s.App.BaseApp.NewContext(false, tmtypes.Header{Height: 1, ChainID: "osmosis-1", Time: time.Now().UTC()}) + t := s.T() + s.App = app.Setup(t) + s.Ctx = s.App.BaseApp.NewContext(false, tmtypes.Header{Height: 1, ChainID: "testing", Time: time.Now().UTC()}) s.QueryHelper = &baseapp.QueryServiceTestHelper{ GRPCQueryRouter: s.App.GRPCQueryRouter(), Ctx: s.Ctx, @@ -62,13 +65,12 @@ func (s *KeeperTestHelper) Setup() { } func (s *KeeperTestHelper) SetupTestForInitGenesis() { - db := dbm.NewMemDB() - s.App = app.NewTerpAppWithCustomOptions(s.T(), true, app.SetupOptions{ - Logger: log.NewTMLogger(log.NewSyncWriter(os.Stdout)), - DB: db, - AppOpts: simtestutil.NewAppOptionsWithFlagHome(s.T().TempDir()), + t := s.T() + // Setting to True, leads to init genesis not running + s.App = app.Setup(t) + s.Ctx = s.App.BaseApp.NewContext(true, tmtypes.Header{ + ChainID: "testing", }) - s.Ctx = s.App.BaseApp.NewContext(true, tmtypes.Header{}) } // CreateTestContext creates a test context. @@ -92,20 +94,20 @@ func (s *KeeperTestHelper) Commit() { oldHeight := s.Ctx.BlockHeight() oldHeader := s.Ctx.BlockHeader() s.App.Commit() - newHeader := tmtypes.Header{Height: oldHeight + 1, ChainID: oldHeader.ChainID, Time: oldHeader.Time.Add(time.Second)} + newHeader := tmtypes.Header{Height: oldHeight + 1, ChainID: "testing", Time: oldHeader.Time.Add(time.Second)} s.App.BeginBlock(abci.RequestBeginBlock{Header: newHeader}) s.Ctx = s.App.NewContext(false, newHeader) } // FundAcc funds target address with specified amount. func (s *KeeperTestHelper) FundAcc(acc sdk.AccAddress, amounts sdk.Coins) { - err := app.FundAccount(s.App.BankKeeper, s.Ctx, acc, amounts) + err := banktestutil.FundAccount(s.App.BankKeeper, s.Ctx, acc, amounts) s.Require().NoError(err) } // FundModuleAcc funds target modules with specified amount. func (s *KeeperTestHelper) FundModuleAcc(moduleName string, amounts sdk.Coins) { - err := app.FundModuleAccount(s.App.BankKeeper, s.Ctx, moduleName, amounts) + err := banktestutil.FundModuleAccount(s.App.BankKeeper, s.Ctx, moduleName, amounts) s.Require().NoError(err) } @@ -119,14 +121,18 @@ func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sd valPub := secp256k1.GenPrivKey().PubKey() valAddr := sdk.ValAddress(valPub.Address()) bondDenom := s.App.StakingKeeper.GetParams(s.Ctx).BondDenom - selfBond := sdk.NewCoins(sdk.Coin{Amount: sdk.DefaultPowerReduction, Denom: bondDenom}) + selfBond := sdk.NewCoins(sdk.Coin{Amount: sdk.NewInt(100), Denom: bondDenom}) s.FundAcc(sdk.AccAddress(valAddr), selfBond) - stakingCoin := sdk.NewCoin(sdk.DefaultBondDenom, selfBond[0].Amount) + // stakingHandler := staking.NewHandler(s.App.StakingKeeper) + stakingCoin := sdk.NewCoin(appparams.BondDenom, selfBond[0].Amount) ZeroCommission := stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) _, err := stakingtypes.NewMsgCreateValidator(valAddr, valPub, stakingCoin, stakingtypes.Description{}, ZeroCommission, sdk.OneInt()) s.Require().NoError(err) + // res, err := stakingHandler(s.Ctx, msg) + // s.Require().NoError(err) + // s.Require().NotNil(res) val, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) s.Require().True(found) @@ -189,6 +195,7 @@ func (s *KeeperTestHelper) BeginNewBlockWithProposer(proposer sdk.ValAddress) { Validator: abci.Validator{Address: valAddr, Power: 1000}, SignedLastBlock: true, }}, + Round: 0, } reqBeginBlock := abci.RequestBeginBlock{Header: header, LastCommitInfo: lastCommitInfo} @@ -208,13 +215,13 @@ func (s *KeeperTestHelper) AllocateRewardsToValidator(valAddr sdk.ValAddress, re s.Require().True(found) // allocate reward tokens to distribution module - coins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, rewardAmt)} - err := app.FundModuleAccount(s.App.BankKeeper, s.Ctx, distrtypes.ModuleName, coins) + coins := sdk.Coins{sdk.NewCoin(appparams.BondDenom, rewardAmt)} + err := banktestutil.FundModuleAccount(s.App.BankKeeper, s.Ctx, distrtypes.ModuleName, coins) s.Require().NoError(err) // allocate rewards to validator s.Ctx = s.Ctx.WithBlockHeight(s.Ctx.BlockHeight() + 1) - decTokens := sdk.DecCoins{{Denom: sdk.DefaultBondDenom, Amount: sdk.NewDec(20000)}} + decTokens := sdk.DecCoins{{Denom: appparams.BondDenom, Amount: sdk.NewDec(20000)}} s.App.DistrKeeper.AllocateTokensToValidator(s.Ctx, validator, decTokens) } @@ -239,6 +246,21 @@ func (s *KeeperTestHelper) BuildTx( return txBuilder.GetTx() } +func (s *KeeperTestHelper) ConfirmUpgradeSucceeded(upgradeName string, upgradeHeight int64) { + s.Ctx = s.Ctx.WithBlockHeight(upgradeHeight - 1) + plan := upgradetypes.Plan{Name: upgradeName, Height: upgradeHeight} + err := s.App.UpgradeKeeper.ScheduleUpgrade(s.Ctx, plan) + s.Require().NoError(err) + _, exists := s.App.UpgradeKeeper.GetUpgradePlan(s.Ctx) + s.Require().True(exists) + + s.Ctx = s.Ctx.WithBlockHeight(upgradeHeight) + s.Require().NotPanics(func() { + beginBlockRequest := abci.RequestBeginBlock{} + s.App.BeginBlocker(s.Ctx, beginBlockRequest) + }) +} + // CreateRandomAccounts is a function return a list of randomly generated AccAddresses func CreateRandomAccounts(numAccts int) []sdk.AccAddress { testAddrs := make([]sdk.AccAddress, numAccts) @@ -252,8 +274,6 @@ func CreateRandomAccounts(numAccts int) []sdk.AccAddress { func TestMessageAuthzSerialization(t *testing.T, msg sdk.Msg) { someDate := time.Date(1, 1, 1, 1, 1, 1, 1, time.UTC) - var expire *time.Time - const ( mockGranter string = "cosmos1abc" mockGrantee string = "cosmos1xyz" @@ -267,7 +287,8 @@ func TestMessageAuthzSerialization(t *testing.T, msg sdk.Msg) { // Authz: Grant Msg typeURL := sdk.MsgTypeURL(msg) - grant, err := authz.NewGrant(someDate, authz.NewGenericAuthorization(typeURL), expire) + later := someDate.Add(time.Hour) + grant, err := authz.NewGrant(someDate, authz.NewGenericAuthorization(typeURL), &later) require.NoError(t, err) msgGrant := authz.MsgGrant{Granter: mockGranter, Grantee: mockGrantee, Grant: grant} diff --git a/app/encoding.go b/app/encoding.go index b9c0d93..8ebe3ed 100644 --- a/app/encoding.go +++ b/app/encoding.go @@ -3,7 +3,7 @@ package app import ( "github.com/cosmos/cosmos-sdk/std" - "github.com/terpnetwork/terp-core/app/params" + "github.com/terpnetwork/terp-core/v2/app/params" ) // MakeEncodingConfig creates a new EncodingConfig with all modules registered diff --git a/app/helpers/mock.go b/app/helpers/mock.go new file mode 100644 index 0000000..ffbfc82 --- /dev/null +++ b/app/helpers/mock.go @@ -0,0 +1,50 @@ +package helpers + +import ( + "github.com/cometbft/cometbft/crypto" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + tmtypes "github.com/cometbft/cometbft/types" + + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" +) + +var _ tmtypes.PrivValidator = PV{} + +// PV implements PrivValidator without any safety or persistence. +// Only use it for testing. +type PV struct { + PrivKey cryptotypes.PrivKey +} + +func NewPV() PV { + return PV{ed25519.GenPrivKey()} +} + +// GetPubKey implements PrivValidator interface +func (pv PV) GetPubKey() (crypto.PubKey, error) { + return cryptocodec.ToTmPubKeyInterface(pv.PrivKey.PubKey()) +} + +// SignVote implements PrivValidator interface +func (pv PV) SignVote(chainID string, vote *tmproto.Vote) error { + signBytes := tmtypes.VoteSignBytes(chainID, vote) + sig, err := pv.PrivKey.Sign(signBytes) + if err != nil { + return err + } + vote.Signature = sig + return nil +} + +// SignProposal implements PrivValidator interface +func (pv PV) SignProposal(chainID string, proposal *tmproto.Proposal) error { + signBytes := tmtypes.ProposalSignBytes(chainID, proposal) + sig, err := pv.PrivKey.Sign(signBytes) + if err != nil { + return err + } + proposal.Signature = sig + return nil +} diff --git a/app/openapiconsole/console.go b/app/openapiconsole/console.go new file mode 100644 index 0000000..465f5bb --- /dev/null +++ b/app/openapiconsole/console.go @@ -0,0 +1,25 @@ +package openapiconsole + +import ( + "embed" + "html/template" + "net/http" +) + +//go:embed index.tpl +var index embed.FS + +// Handler returns an http handler that servers OpenAPI console for an OpenAPI spec at specURL. +func Handler(title, specURL string) http.HandlerFunc { + t, _ := template.ParseFS(index, "index.tpl") + + return func(w http.ResponseWriter, req *http.Request) { + t.Execute(w, struct { //nolint:errcheck + Title string + URL string + }{ + title, + specURL, + }) + } +} diff --git a/app/openapiconsole/index.tpl b/app/openapiconsole/index.tpl new file mode 100644 index 0000000..d88cd5b --- /dev/null +++ b/app/openapiconsole/index.tpl @@ -0,0 +1,25 @@ + + + + + {{ .Title }} + + + + +
+ + + + + \ No newline at end of file diff --git a/app/params/bech32.go b/app/params/bech32.go index 7d9b8f9..2ab34da 100644 --- a/app/params/bech32.go +++ b/app/params/bech32.go @@ -4,7 +4,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) -// AccountAddressPrefix defines the Paloma network's Bech32 address prefix. +// AccountAddressPrefix defines the Terp network's Bech32 address prefix. const AccountAddressPrefix = "terp" // Account specific Bech32 prefixes. @@ -16,7 +16,7 @@ var ( ConsNodePubKeyPrefix = AccountAddressPrefix + "valconspub" ) -// SetAddressConfig sets Paloma's address configuration. +// SetAddressConfig sets Terp's address configuration. func SetAddressConfig() { config := sdk.GetConfig() config.SetBech32PrefixForAccount(AccountAddressPrefix, AccountPubKeyPrefix) diff --git a/app/params/const.go b/app/params/const.go new file mode 100644 index 0000000..519cbd8 --- /dev/null +++ b/app/params/const.go @@ -0,0 +1,22 @@ +package params + +const ( + // Name defines the application name of Terp network. + Name = "terp" + + // BondDenom defines the native staking token denomination. + BondDenom = "uterp" + + // DisplayBondDenom defines the name, symbol, and display value of the Terp token. + DisplayBondDenom = "TERP" + + // BondDenom defines the native gas token denomination. + GasDenom = "uthiol" + + // DisplayGasDenom defines the name, symbol, and display value of the Thiol token. + DisplayGasDenom = "THIOL" + + // DefaultGasLimit - set to the same value as cosmos-sdk flags.DefaultGasLimit + // this value is currently only used in tests. + DefaultGasLimit = 200000 +) diff --git a/app/params/weights.go b/app/params/weights.go index 997b814..e91b4d5 100644 --- a/app/params/weights.go +++ b/app/params/weights.go @@ -48,4 +48,5 @@ const ( DefaultWeightMsgBurn int = 100 DefaultWeightMsgChangeAdmin int = 100 DefaultWeightMsgSetDenomMetadata int = 100 + DefaultWeightMsgForceTransfer int = 100 ) diff --git a/app/sim_test.go b/app/sim_test.go index 9e84c78..2eca812 100644 --- a/app/sim_test.go +++ b/app/sim_test.go @@ -1,46 +1,31 @@ package app import ( - "encoding/json" "fmt" - "math/rand" "os" - "runtime/debug" - "strings" + "path/filepath" "testing" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + "github.com/stretchr/testify/require" + dbm "github.com/cometbft/cometbft-db" - abci "github.com/cometbft/cometbft/abci/types" "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/store" storetypes "github.com/cosmos/cosmos-sdk/store/types" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/kv" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/cosmos/cosmos-sdk/x/simulation" simcli "github.com/cosmos/cosmos-sdk/x/simulation/client/cli" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm" ) -// SimAppChainID hardcoded chainID for simulation -const SimAppChainID = "simulation-app" +const SimAppChainID = "testing" // Get flags every time the simulator is run func init() { @@ -53,299 +38,107 @@ type StoreKeysPrefixes struct { Prefixes [][]byte } -// fauxMerkleModeOpt returns a BaseApp option to use a dbStoreAdapter instead of -// an IAVLStore for faster simulation speed. -func fauxMerkleModeOpt(bapp *baseapp.BaseApp) { - bapp.SetFauxMerkleMode() -} - -// interBlockCacheOpt returns a BaseApp option function that sets the persistent -// inter-block write-through cache. -func interBlockCacheOpt() func(*baseapp.BaseApp) { - return baseapp.SetInterBlockCache(store.NewCommitKVStoreCacheManager()) -} - -func TestFullAppSimulation(t *testing.T) { - config, db, _, app := setupSimulationApp(t, "skipping application simulation") - // run randomized simulation - _, simParams, simErr := simulation.SimulateFromSeed( - t, - os.Stdout, - app.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), - simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 - simtestutil.SimulationOperations(app, app.AppCodec(), config), - BlockedAddresses(), - config, - app.AppCodec(), - ) - - // export state and simParams before the simulation error is checked - err := simtestutil.CheckExportSimulation(app, config, simParams) - require.NoError(t, err) - require.NoError(t, simErr) +// SetupSimulation wraps simapp.SetupSimulation in order to create any export directory if they do not exist yet +func SetupSimulation() (simtypes.Config, dbm.DB, string, log.Logger, bool, error) { + config := simcli.NewConfigFromFlags() + config.ChainID = SimAppChainID - if config.Commit { - simtestutil.PrintStats(db) + db, dir, logger, skip, err := simtestutil.SetupSimulation(config, "leveldb-app-sim", "Simulation", simcli.FlagVerboseValue, simcli.FlagEnabledValue) + if err != nil { + return simtypes.Config{}, nil, "", nil, false, err } -} -func TestAppImportExport(t *testing.T) { - config, db, appOptions, app := setupSimulationApp(t, "skipping application import/export simulation") + paths := []string{config.ExportParamsPath, config.ExportStatePath, config.ExportStatsPath} + for _, path := range paths { + if len(path) == 0 { + continue + } - // Run randomized simulation - _, simParams, simErr := simulation.SimulateFromSeed( - t, - os.Stdout, - app.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), - simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 - simtestutil.SimulationOperations(app, app.AppCodec(), config), - BlockedAddresses(), - config, - app.AppCodec(), - ) + path = filepath.Dir(path) + if _, err := os.Stat(path); os.IsNotExist(err) { + if err := os.MkdirAll(path, os.ModePerm); err != nil { + panic(err) + } + } + } - // export state and simParams before the simulation error is checked - err := simtestutil.CheckExportSimulation(app, config, simParams) - require.NoError(t, err) - require.NoError(t, simErr) + return config, db, dir, logger, skip, err +} - if config.Commit { - simtestutil.PrintStats(db) +// GetSimulationLog unmarshals the KVPair's Value to the corresponding type based on the +// each's module store key and the prefix bytes of the KVPair's key. +func GetSimulationLog(storeName string, sdr sdk.StoreDecoderRegistry, kvAs, kvBs []kv.Pair) (log string) { + for i := 0; i < len(kvAs); i++ { + if len(kvAs[i].Value) == 0 && len(kvBs[i].Value) == 0 { + // skip if the value doesn't have any bytes + continue + } + decoder, ok := sdr[storeName] + if ok { + log += decoder(kvAs[i], kvBs[i]) + } else { + log += fmt.Sprintf("store A %q => %q\nstore B %q => %q\n", kvAs[i].Key, kvAs[i].Value, kvBs[i].Key, kvBs[i].Value) + } } - fmt.Printf("exporting genesis...\n") - - exported, err := app.ExportAppStateAndValidators(false, []string{}, []string{}) - require.NoError(t, err) + return log +} - fmt.Printf("importing genesis...\n") +// fauxMerkleModeOpt returns a BaseApp option to use a dbStoreAdapter instead of +// an IAVLStore for faster simulation speed. +func fauxMerkleModeOpt(bapp *baseapp.BaseApp) { + bapp.SetFauxMerkleMode() +} - newDB, newDir, _, _, err := simtestutil.SetupSimulation(config, "leveldb-app-sim-2", "Simulation-2", simcli.FlagVerboseValue, simcli.FlagEnabledValue) +func TestFullAppSimulation(t *testing.T) { + config, db, dir, logger, skip, err := SetupSimulation() + if skip { + t.Skip("skipping application simulation") + } require.NoError(t, err, "simulation setup failed") defer func() { - require.NoError(t, newDB.Close()) - require.NoError(t, os.RemoveAll(newDir)) - }() - - newApp := NewTerpApp(log.NewNopLogger(), newDB, nil, true, wasm.EnableAllProposals, appOptions, emptyWasmOpts, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) - require.Equal(t, "TerpApp", newApp.Name()) - - var genesisState GenesisState - err = json.Unmarshal(exported.AppState, &genesisState) - require.NoError(t, err) - - defer func() { - if r := recover(); r != nil { - err := fmt.Sprintf("%v", r) - if !strings.Contains(err, "validator set is empty after InitGenesis") { - panic(r) - } - t.Log("Skipping simulation as all validators have been unbonded") - t.Logf("err: %s stacktrace: %s\n", err, string(debug.Stack())) - } + db.Close() + require.NoError(t, os.RemoveAll(dir)) }() - ctxA := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) - ctxB := newApp.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) - newApp.ModuleManager.InitGenesis(ctxB, app.AppCodec(), genesisState) - newApp.StoreConsensusParams(ctxB, exported.ConsensusParams) - - fmt.Printf("comparing stores...\n") - - storeKeysPrefixes := []StoreKeysPrefixes{ - {app.GetKey(authtypes.StoreKey), newApp.GetKey(authtypes.StoreKey), [][]byte{}}, - { - app.GetKey(stakingtypes.StoreKey), newApp.GetKey(stakingtypes.StoreKey), - [][]byte{ - stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey, - stakingtypes.HistoricalInfoKey, stakingtypes.UnbondingIDKey, stakingtypes.UnbondingIndexKey, stakingtypes.UnbondingTypeKey, stakingtypes.ValidatorUpdatesKey, - }, - }, // ordering may change but it doesn't matter - {app.GetKey(slashingtypes.StoreKey), newApp.GetKey(slashingtypes.StoreKey), [][]byte{}}, - {app.GetKey(minttypes.StoreKey), newApp.GetKey(minttypes.StoreKey), [][]byte{}}, - {app.GetKey(distrtypes.StoreKey), newApp.GetKey(distrtypes.StoreKey), [][]byte{}}, - {app.GetKey(banktypes.StoreKey), newApp.GetKey(banktypes.StoreKey), [][]byte{banktypes.BalancesPrefix}}, - {app.GetKey(paramtypes.StoreKey), newApp.GetKey(paramtypes.StoreKey), [][]byte{}}, - {app.GetKey(govtypes.StoreKey), newApp.GetKey(govtypes.StoreKey), [][]byte{}}, - {app.GetKey(evidencetypes.StoreKey), newApp.GetKey(evidencetypes.StoreKey), [][]byte{}}, - {app.GetKey(capabilitytypes.StoreKey), newApp.GetKey(capabilitytypes.StoreKey), [][]byte{}}, - {app.GetKey(authzkeeper.StoreKey), newApp.GetKey(authzkeeper.StoreKey), [][]byte{authzkeeper.GrantKey, authzkeeper.GrantQueuePrefix}}, - } - - for _, skp := range storeKeysPrefixes { - storeA := ctxA.KVStore(skp.A) - storeB := ctxB.KVStore(skp.B) - - failedKVAs, failedKVBs := sdk.DiffKVStores(storeA, storeB, skp.Prefixes) - require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare") - - fmt.Printf("compared %d different key/value pairs between %s and %s\n", len(failedKVAs), skp.A, skp.B) - require.Equal(t, 0, len(failedKVAs), simtestutil.GetSimulationLog(skp.A.Name(), app.SimulationManager().StoreDecoders, failedKVAs, failedKVBs)) - } -} + appOptions := make(simtestutil.AppOptionsMap, 0) + appOptions[flags.FlagHome] = DefaultNodeHome + appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue -func TestAppSimulationAfterImport(t *testing.T) { - config, db, appOptions, app := setupSimulationApp(t, "skipping application simulation after import") + var emptyWasmOption []wasmkeeper.Option + app := NewTerpApp( + logger, + db, + nil, + true, + wasmtypes.EnableAllProposals, + appOptions, + emptyWasmOption, + fauxMerkleModeOpt, + baseapp.SetChainID(SimAppChainID), + ) + require.Equal(t, "terp", app.Name()) - // Run randomized simulation - stopEarly, simParams, simErr := simulation.SimulateFromSeed( + // run randomized simulation + _, simParams, simErr := simulation.SimulateFromSeed( t, os.Stdout, app.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), + simtestutil.AppStateFn(app.appCodec, app.SimulationManager(), NewDefaultGenesisState(app.appCodec)), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 simtestutil.SimulationOperations(app, app.AppCodec(), config), - BlockedAddresses(), + app.ModuleAccountAddrs(), config, app.AppCodec(), ) // export state and simParams before the simulation error is checked - err := simtestutil.CheckExportSimulation(app, config, simParams) + err = simtestutil.CheckExportSimulation(app, config, simParams) require.NoError(t, err) require.NoError(t, simErr) if config.Commit { simtestutil.PrintStats(db) } - - if stopEarly { - fmt.Println("can't export or import a zero-validator genesis, exiting test...") - return - } - - fmt.Printf("exporting genesis...\n") - - exported, err := app.ExportAppStateAndValidators(true, []string{}, []string{}) - require.NoError(t, err) - - fmt.Printf("importing genesis...\n") - - newDB, newDir, _, _, err := simtestutil.SetupSimulation(config, "leveldb-app-sim-2", "Simulation-2", simcli.FlagVerboseValue, simcli.FlagEnabledValue) - require.NoError(t, err, "simulation setup failed") - - defer func() { - require.NoError(t, newDB.Close()) - require.NoError(t, os.RemoveAll(newDir)) - }() - - newApp := NewTerpApp(log.NewNopLogger(), newDB, nil, true, wasm.EnableAllProposals, appOptions, emptyWasmOpts, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) - require.Equal(t, "TerpApp", newApp.Name()) - - newApp.InitChain(abci.RequestInitChain{ - ChainId: SimAppChainID, - AppStateBytes: exported.AppState, - }) - - _, _, err = simulation.SimulateFromSeed( - t, - os.Stdout, - newApp.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), - simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 - simtestutil.SimulationOperations(newApp, newApp.AppCodec(), config), - BlockedAddresses(), - config, - app.AppCodec(), - ) - require.NoError(t, err) -} - -func setupSimulationApp(t *testing.T, msg string) (simtypes.Config, dbm.DB, simtestutil.AppOptionsMap, *TerpApp) { - t.Helper() - config := simcli.NewConfigFromFlags() - config.ChainID = SimAppChainID - - db, dir, logger, skip, err := simtestutil.SetupSimulation(config, "leveldb-app-sim", "Simulation", simcli.FlagVerboseValue, simcli.FlagEnabledValue) - if skip { - t.Skip(msg) - } - require.NoError(t, err, "simulation setup failed") - - t.Cleanup(func() { - require.NoError(t, db.Close()) - require.NoError(t, os.RemoveAll(dir)) - }) - - appOptions := make(simtestutil.AppOptionsMap, 0) - appOptions[flags.FlagHome] = dir // ensure a unique folder - appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue - - app := NewTerpApp(logger, db, nil, true, wasm.EnableAllProposals, appOptions, emptyWasmOpts, fauxMerkleModeOpt, baseapp.SetChainID(SimAppChainID)) - require.Equal(t, "TerpApp", app.Name()) - return config, db, appOptions, app -} - -// TODO: Make another test for the fuzzer itself, which just has noOp txs -// and doesn't depend on the application. -func TestAppStateDeterminism(t *testing.T) { - if !simcli.FlagEnabledValue { - t.Skip("skipping application simulation") - } - - config := simcli.NewConfigFromFlags() - config.InitialBlockHeight = 1 - config.ExportParamsPath = "" - config.OnOperation = false - config.AllInvariants = false - config.ChainID = SimAppChainID - - numSeeds := 3 - numTimesToRunPerSeed := 5 - appHashList := make([]json.RawMessage, numTimesToRunPerSeed) - - appOptions := make(simtestutil.AppOptionsMap, 0) - appOptions[flags.FlagHome] = t.TempDir() // ensure a unique folder - appOptions[server.FlagInvCheckPeriod] = simcli.FlagPeriodValue - - for i := 0; i < numSeeds; i++ { - config.Seed = rand.Int63() - - for j := 0; j < numTimesToRunPerSeed; j++ { - var logger log.Logger - if simcli.FlagVerboseValue { - logger = log.TestingLogger() - } else { - logger = log.NewNopLogger() - } - - db := dbm.NewMemDB() - app := NewTerpApp(logger, db, nil, true, wasm.EnableAllProposals, appOptions, emptyWasmOpts, interBlockCacheOpt(), baseapp.SetChainID(SimAppChainID)) - - fmt.Printf( - "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", - config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, - ) - - _, _, err := simulation.SimulateFromSeed( - t, - os.Stdout, - app.BaseApp, - simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), - simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 - simtestutil.SimulationOperations(app, app.AppCodec(), config), - BlockedAddresses(), - config, - app.AppCodec(), - ) - require.NoError(t, err) - - if config.Commit { - simtestutil.PrintStats(db) - } - - appHash := app.LastCommitID().Hash - appHashList[j] = appHash - - if j != 0 { - require.Equal( - t, string(appHashList[0]), string(appHashList[j]), - "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, - ) - } - } - } } diff --git a/app/test_helpers.go b/app/test_helpers.go index a448d6d..829d1c5 100644 --- a/app/test_helpers.go +++ b/app/test_helpers.go @@ -2,127 +2,76 @@ package app import ( "encoding/json" - "fmt" - "math/rand" - "os" "path/filepath" "testing" "time" - "cosmossdk.io/math" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + "github.com/stretchr/testify/require" dbm "github.com/cometbft/cometbft-db" abci "github.com/cometbft/cometbft/abci/types" - tmjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" "github.com/cometbft/cometbft/libs/log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" tmtypes "github.com/cometbft/cometbft/types" + + "cosmossdk.io/math" + bam "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/server" - servertypes "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/snapshots" snapshottypes "github.com/cosmos/cosmos-sdk/snapshots/types" - pruningtypes "github.com/cosmos/cosmos-sdk/store/pruning/types" - "github.com/cosmos/cosmos-sdk/testutil/mock" - "github.com/cosmos/cosmos-sdk/testutil/network" simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module/testutil" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/x/wasm" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" + apphelpers "github.com/terpnetwork/terp-core/v2/app/helpers" + appparams "github.com/terpnetwork/terp-core/v2/app/params" ) -// SetupOptions defines arguments that are passed into `TerpApp` constructor. -type SetupOptions struct { - Logger log.Logger - DB *dbm.MemDB - AppOpts servertypes.AppOptions - WasmOpts []wasm.Option -} +// EmptyBaseAppOptions is a stub implementing AppOptions +type EmptyBaseAppOptions struct{} -func setup(tb testing.TB, chainID string, withGenesis bool, invCheckPeriod uint, opts ...wasm.Option) (*TerpApp, GenesisState) { - tb.Helper() - db := dbm.NewMemDB() - nodeHome := tb.TempDir() - snapshotDir := filepath.Join(nodeHome, "data", "snapshots") - - snapshotDB, err := dbm.NewDB("metadata", dbm.GoLevelDBBackend, snapshotDir) - require.NoError(tb, err) - tb.Cleanup(func() { snapshotDB.Close() }) - snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) - require.NoError(tb, err) - - appOptions := make(simtestutil.AppOptionsMap, 0) - appOptions[flags.FlagHome] = nodeHome // ensure unique folder - appOptions[server.FlagInvCheckPeriod] = invCheckPeriod - app := NewTerpApp(log.NewNopLogger(), db, nil, true, wasmtypes.EnableAllProposals, appOptions, opts, bam.SetChainID(chainID), bam.SetSnapshot(snapshotStore, snapshottypes.SnapshotOptions{KeepRecent: 2})) - if withGenesis { - return app, NewDefaultGenesisState(app.AppCodec()) - } - return app, GenesisState{} +// Get implements AppOptions +func (ao EmptyBaseAppOptions) Get(_ string) interface{} { + return nil } -// NewTerpAppWithCustomOptions initializes a new TerpApp with custom options. -func NewTerpAppWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptions) *TerpApp { - 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.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), - } - - app := NewTerpApp(options.Logger, options.DB, nil, true, wasmtypes.EnableAllProposals, options.AppOpts, options.WasmOpts) - genesisState := NewDefaultGenesisState(app.appCodec) - genesisState, err = GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) - require.NoError(t, err) - - if !isCheckTx { - // init chain must be called to stop deliverState from being nil - stateBytes, err := tmjson.MarshalIndent(genesisState, "", " ") - require.NoError(t, err) +// DefaultConsensusParams defines the default Tendermint consensus params used +// in junoApp testing. +var DefaultConsensusParams = &tmproto.ConsensusParams{ + Block: &tmproto.BlockParams{ + MaxBytes: 200000, + MaxGas: 2000000, + }, + Evidence: &tmproto.EvidenceParams{ + MaxAgeNumBlocks: 302400, + MaxAgeDuration: 504 * time.Hour, // 3 weeks is the max duration + MaxBytes: 10000, + }, + Validator: &tmproto.ValidatorParams{ + PubKeyTypes: []string{ + tmtypes.ABCIPubKeyTypeEd25519, + }, + }, +} - // Initialize the chain - app.InitChain( - abci.RequestInitChain{ - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: simtestutil.DefaultConsensusParams, - AppStateBytes: stateBytes, - }, - ) - } +type EmptyAppOptions struct{} - return app -} +func (EmptyAppOptions) Get(_ string) interface{} { return nil } -// Setup initializes a new TerpApp. A Nop logger is set in TerpApp. -func Setup(t *testing.T, opts ...wasm.Option) *TerpApp { +func Setup(t *testing.T) *TerpApp { t.Helper() - privVal := mock.NewPV() + privVal := apphelpers.NewPV() pubKey, err := privVal.GetPubKey() require.NoError(t, err) @@ -135,198 +84,93 @@ func Setup(t *testing.T, opts ...wasm.Option) *TerpApp { acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) balance := banktypes.Balance{ Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), + Coins: sdk.NewCoins(sdk.NewCoin(appparams.BondDenom, sdk.NewInt(100000000000000))), } - chainID := "testing" - app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, chainID, opts, balance) + + app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance) return app } -// SetupWithGenesisValSet initializes a new TerpApp with a validator set and genesis accounts +// SetupWithGenesisValSet initializes a new junoApp 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 in the default token of the TerpApp from first genesis -// account. A Nop logger is set in TerpApp. -func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, chainID string, opts []wasm.Option, balances ...banktypes.Balance) *TerpApp { +// of one consensus engine unit in the default token of the JunoApp from first genesis +// account. A Nop logger is set in JunoApp. +func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *TerpApp { t.Helper() - app, genesisState := setup(t, chainID, true, 5, opts...) - genesisState, err := GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, genAccs, balances...) - require.NoError(t, err) + junoApp, genesisState := setup(t, true) + genesisState = genesisStateWithValSet(t, junoApp, 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 - consensusParams := simtestutil.DefaultConsensusParams - consensusParams.Block.MaxGas = 100 * simtestutil.DefaultGenTxGas - app.InitChain( + junoApp.InitChain( abci.RequestInitChain{ - ChainId: chainID, Validators: []abci.ValidatorUpdate{}, - ConsensusParams: consensusParams, + ConsensusParams: DefaultConsensusParams, AppStateBytes: stateBytes, + ChainId: "testing", + Time: time.Now().UTC(), + InitialHeight: 1, }, ) + // commit genesis changes - app.Commit() - app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{ - ChainID: chainID, - Height: app.LastBlockHeight() + 1, - AppHash: app.LastCommitID().Hash, - Time: time.Now().UTC(), + junoApp.Commit() + junoApp.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{ + ChainID: "testing", + Height: junoApp.LastBlockHeight() + 1, + AppHash: junoApp.LastCommitID().Hash, ValidatorsHash: valSet.Hash(), NextValidatorsHash: valSet.Hash(), + Time: time.Now().UTC(), }}) - return app + return junoApp } -// SetupWithEmptyStore set up a wasmd app instance with empty DB -func SetupWithEmptyStore(tb testing.TB) *TerpApp { - tb.Helper() - app, _ := setup(tb, "testing", false, 0) - return app -} - -// GenesisStateWithSingleValidator initializes GenesisState with a single validator and genesis accounts -// that also act as delegators. -func GenesisStateWithSingleValidator(t *testing.T, app *TerpApp) GenesisState { - t.Helper() +func setup(t *testing.T, withGenesis bool, opts ...wasmkeeper.Option) (*TerpApp, GenesisState) { + db := dbm.NewMemDB() + nodeHome := t.TempDir() + snapshotDir := filepath.Join(nodeHome, "data", "snapshots") - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() + snapshotDB, err := dbm.NewDB("metadata", dbm.GoLevelDBBackend, snapshotDir) 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.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) - balances := []banktypes.Balance{ - { - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), - }, - } - - genesisState := NewDefaultGenesisState(app.appCodec) - genesisState, err = GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...) + t.Cleanup(func() { snapshotDB.Close() }) + snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) require.NoError(t, err) - return genesisState -} - -// AddTestAddrsIncremental constructs and returns accNum amount of accounts with an -// initial balance of accAmt in random order -func AddTestAddrsIncremental(app *TerpApp, ctx sdk.Context, accNum int, accAmt math.Int) []sdk.AccAddress { - return addTestAddrs(app, ctx, accNum, accAmt, simtestutil.CreateIncrementalAccounts) -} - -func addTestAddrs(app *TerpApp, ctx sdk.Context, accNum int, accAmt math.Int, strategy simtestutil.GenerateAccountStrategy) []sdk.AccAddress { - testAddrs := strategy(accNum) - - initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) - - for _, addr := range testAddrs { - initAccountWithCoins(app, ctx, addr, initCoins) - } - - return testAddrs -} - -func initAccountWithCoins(app *TerpApp, ctx sdk.Context, addr sdk.AccAddress, coins sdk.Coins) { - err := app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, coins) - if err != nil { - panic(err) - } - - err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, coins) - if err != nil { - panic(err) - } -} - -// ModuleAccountAddrs provides a list of blocked module accounts from configuration in AppConfig -// -// Ported from TerpApp -func ModuleAccountAddrs() map[string]bool { - return BlockedAddresses() -} - -var emptyWasmOptions []wasm.Option - -// NewTestNetworkFixture returns a new TerpApp AppConstructor for network simulation tests -func NewTestNetworkFixture() network.TestFixture { - dir, err := os.MkdirTemp("", "simapp") - if err != nil { - panic(fmt.Sprintf("failed creating temporary directory: %v", err)) - } - defer os.RemoveAll(dir) - - app := NewTerpApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, wasmtypes.EnableAllProposals, simtestutil.NewAppOptionsWithFlagHome(dir), emptyWasmOptions) - appCtr := func(val network.ValidatorI) servertypes.Application { - return NewTerpApp( - val.GetCtx().Logger, dbm.NewMemDB(), nil, true, wasmtypes.EnableAllProposals, - simtestutil.NewAppOptionsWithFlagHome(val.GetCtx().Config.RootDir), - emptyWasmOptions, - bam.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)), - bam.SetMinGasPrices(val.GetAppConfig().MinGasPrices), - bam.SetChainID(val.GetCtx().Viper.GetString(flags.FlagChainID)), - ) - } - - return network.TestFixture{ - AppConstructor: appCtr, - GenesisState: NewDefaultGenesisState(app.AppCodec()), - EncodingConfig: testutil.TestEncodingConfig{ - InterfaceRegistry: app.InterfaceRegistry(), - Codec: app.AppCodec(), - TxConfig: app.TxConfig(), - Amino: app.LegacyAmino(), - }, - } -} + // var emptyWasmOpts []wasm.Option + appOptions := make(simtestutil.AppOptionsMap, 0) + appOptions[flags.FlagHome] = nodeHome // ensure unique folder -// SignAndDeliverWithoutCommit signs and delivers a transaction. No commit -func SignAndDeliverWithoutCommit( - t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg, - chainID string, accNums, accSeqs []uint64, priv ...cryptotypes.PrivKey, -) (sdk.GasInfo, *sdk.Result, error) { - t.Helper() - tx, err := simtestutil.GenSignedMockTx( - rand.New(rand.NewSource(time.Now().UnixNano())), - txCfg, - msgs, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - simtestutil.DefaultGenTxGas, - chainID, - accNums, - accSeqs, - priv..., + app := NewTerpApp( + log.NewNopLogger(), + db, + nil, + true, + wasmtypes.EnableAllProposals, + EmptyAppOptions{}, + opts, + bam.SetChainID("testing"), + bam.SetSnapshot(snapshotStore, snapshottypes.SnapshotOptions{KeepRecent: 2}), ) - require.NoError(t, err) - - // Simulate a sending a transaction and committing a block - // app.BeginBlock(abci.RequestBeginBlock{Header: header}) - gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx) - // app.EndBlock(abci.RequestEndBlock{}) - // app.Commit() + if withGenesis { + return app, NewDefaultGenesisState(app.AppCodec()) + } - return gInfo, res, err + return app, GenesisState{} } -// GenesisStateWithValSet returns a new genesis state with the validator set -// copied from simtestutil with delegation not added to supply -func GenesisStateWithValSet( - codec codec.Codec, - genesisState map[string]json.RawMessage, - valSet *tmtypes.ValidatorSet, - genAccs []authtypes.GenesisAccount, +func genesisStateWithValSet(t *testing.T, + app *TerpApp, genesisState GenesisState, + valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance, -) (map[string]json.RawMessage, error) { +) GenesisState { + codec := app.AppCodec() + // set genesis accounts authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) genesisState[authtypes.ModuleName] = codec.MustMarshalJSON(authGenesis) @@ -338,15 +182,9 @@ func GenesisStateWithValSet( for _, val := range valSet.Validators { pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) - if err != nil { - return nil, fmt.Errorf("failed to convert pubkey: %w", err) - } - + require.NoError(t, err) pkAny, err := codectypes.NewAnyWithValue(pk) - if err != nil { - return nil, fmt.Errorf("failed to create new any: %w", err) - } - + require.NoError(t, err) validator := stakingtypes.Validator{ OperatorAddress: sdk.ValAddress(val.Address).String(), ConsensusPubkey: pkAny, @@ -362,16 +200,27 @@ func GenesisStateWithValSet( } validators = append(validators, validator) delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), math.LegacyOneDec())) + } + defaultStParams := stakingtypes.DefaultParams() + stParams := stakingtypes.NewParams( + defaultStParams.UnbondingTime, + defaultStParams.MaxValidators, + defaultStParams.MaxEntries, + defaultStParams.HistoricalEntries, + appparams.BondDenom, + defaultStParams.MinCommissionRate, // 5% + ) + // set validators and delegations - stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations) + stakingGenesis := stakingtypes.NewGenesisState(stParams, validators, delegations) genesisState[stakingtypes.ModuleName] = codec.MustMarshalJSON(stakingGenesis) // add bonded amount to bonded pool module account balances = append(balances, banktypes.Balance{ Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, bondAmt.MulRaw(int64(len(valSet.Validators))))}, + Coins: sdk.Coins{sdk.NewCoin(appparams.BondDenom, bondAmt.MulRaw(int64(len(valSet.Validators))))}, }) totalSupply := sdk.NewCoins() @@ -383,34 +232,34 @@ func GenesisStateWithValSet( // update total supply bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, []banktypes.SendEnabled{}) genesisState[banktypes.ModuleName] = codec.MustMarshalJSON(bankGenesis) - println(string(genesisState[banktypes.ModuleName])) - return genesisState, nil + // println("genesisStateWithValSet bankState:", string(genesisState[banktypes.ModuleName])) + + return genesisState } -// FundAccount is a utility function that funds an account by minting and -// sending the coins to the address. This should be used for testing purposes -// only! -// -// Instead of using the mint module account, which has the -// permission of minting, create a "faucet" account. (@fdymylja) -func FundAccount(bankKeeper bankkeeper.Keeper, ctx sdk.Context, addr sdk.AccAddress, amounts sdk.Coins) error { - if err := bankKeeper.MintCoins(ctx, minttypes.ModuleName, amounts); err != nil { - return err - } +func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { + key := ed25519.GenPrivKey() + pub := key.PubKey() + addr := sdk.AccAddress(pub.Address()) + return key, pub, addr +} - return bankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, amounts) +func RandomAccountAddress() sdk.AccAddress { + _, _, addr := keyPubAddr() + return addr } -// FundModuleAccount is a utility function that funds a module account by -// minting and sending the coins to the address. This should be used for testing -// purposes only! -// -// Instead of using the mint module account, which has the -// permission of minting, create a "faucet" account. (@fdymylja) -func FundModuleAccount(bankKeeper bankkeeper.Keeper, ctx sdk.Context, recipientMod string, amounts sdk.Coins) error { - if err := bankKeeper.MintCoins(ctx, minttypes.ModuleName, amounts); err != nil { - return err +func ExecuteRawCustom(t *testing.T, ctx sdk.Context, app *TerpApp, contract sdk.AccAddress, sender sdk.AccAddress, msg json.RawMessage, funds sdk.Coin) error { + t.Helper() + oracleBz, err := json.Marshal(msg) + require.NoError(t, err) + // no funds sent if amount is 0 + var coins sdk.Coins + if !funds.Amount.IsNil() { + coins = sdk.Coins{funds} } - return bankKeeper.SendCoinsFromModuleToModule(ctx, minttypes.ModuleName, recipientMod, amounts) + contractKeeper := wasmkeeper.NewDefaultPermissionKeeper(app.WasmKeeper) + _, err = contractKeeper.Execute(ctx, contract, sender, oracleBz, coins) + return err } diff --git a/app/upgrades.go b/app/upgrades.go deleted file mode 100644 index 6cf7fa0..0000000 --- a/app/upgrades.go +++ /dev/null @@ -1,108 +0,0 @@ -package app - -import ( - "github.com/cosmos/cosmos-sdk/baseapp" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - consensustypes "github.com/cosmos/cosmos-sdk/x/consensus/types" - crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" - icahosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// UpgradeName defines the on-chain upgrade name for the sample SimApp upgrade -// from v046 to v047. -// -// NOTE: This upgrade defines a reference implementation of what an upgrade -// could look like when an application is migrating from Cosmos SDK version -// v0.46.x to v0.47.x. -const UpgradeName = "v046-to-v047" - -func (app TerpApp) RegisterUpgradeHandlers() { - // Set param key table for params module migration - for _, subspace := range app.ParamsKeeper.GetSubspaces() { - subspace := subspace - - var keyTable paramstypes.KeyTable - switch subspace.Name() { - case authtypes.ModuleName: - keyTable = authtypes.ParamKeyTable() //nolint:staticcheck - case banktypes.ModuleName: - keyTable = banktypes.ParamKeyTable() //nolint:staticcheck - case stakingtypes.ModuleName: - keyTable = stakingtypes.ParamKeyTable() - case minttypes.ModuleName: - keyTable = minttypes.ParamKeyTable() //nolint:staticcheck - case distrtypes.ModuleName: - keyTable = distrtypes.ParamKeyTable() //nolint:staticcheck - case slashingtypes.ModuleName: - keyTable = slashingtypes.ParamKeyTable() //nolint:staticcheck - case govtypes.ModuleName: - keyTable = govv1.ParamKeyTable() //nolint:staticcheck - case crisistypes.ModuleName: - keyTable = crisistypes.ParamKeyTable() //nolint:staticcheck - // ibc types - case ibctransfertypes.ModuleName: - keyTable = ibctransfertypes.ParamKeyTable() - case icahosttypes.SubModuleName: - keyTable = icahosttypes.ParamKeyTable() - case icacontrollertypes.SubModuleName: - keyTable = icacontrollertypes.ParamKeyTable() - // wasm - case wasmtypes.ModuleName: - keyTable = wasmtypes.ParamKeyTable() //nolint:staticcheck - default: - continue - } - - if !subspace.HasKeyTable() { - subspace.WithKeyTable(keyTable) - } - } - - baseAppLegacySS := app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramstypes.ConsensusParamsKeyTable()) - - app.UpgradeKeeper.SetUpgradeHandler( - UpgradeName, - func(ctx sdk.Context, _ upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { - // Migrate Tendermint consensus parameters from x/params module to a dedicated x/consensus module. - baseapp.MigrateParams(ctx, baseAppLegacySS, &app.ConsensusParamsKeeper) - - // Note: this migration is optional, - // You can include x/gov proposal migration documented in [UPGRADING.md](https://github.com/cosmos/cosmos-sdk/blob/main/UPGRADING.md) - - return app.ModuleManager.RunMigrations(ctx, app.Configurator(), fromVM) - }, - ) - - upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() - if err != nil { - panic(err) - } - - if upgradeInfo.Name == UpgradeName && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { - storeUpgrades := storetypes.StoreUpgrades{ - Added: []string{ - consensustypes.ModuleName, - crisistypes.ModuleName, - }, - } - - // configure store loader that checks if version == upgradeHeight and applies store upgrades - app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) - } -} diff --git a/app/upgrades/types.go b/app/upgrades/types.go new file mode 100644 index 0000000..61e1d65 --- /dev/null +++ b/app/upgrades/types.go @@ -0,0 +1,12 @@ +package upgrades + +import ( + "strings" +) + +func GetChainsDenomToken(chainID string) string { + if strings.HasPrefix(chainID, "90u-") { + return "uterpx" + } + return "uterp" +} diff --git a/app/upgrades/v2/constants.go b/app/upgrades/v2/constants.go new file mode 100644 index 0000000..589c712 --- /dev/null +++ b/app/upgrades/v2/constants.go @@ -0,0 +1,5 @@ +package v2 + +const ( + UpgradeName = "v2" +) diff --git a/app/upgrades/v2/upgrade.go b/app/upgrades/v2/upgrade.go new file mode 100644 index 0000000..18234aa --- /dev/null +++ b/app/upgrades/v2/upgrade.go @@ -0,0 +1,94 @@ +package v2 + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + + feesharekeeper "github.com/terpnetwork/terp-core/v2/x/feeshare/keeper" + feesharetypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" + + globalfeekeeper "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" + globalfeetypes "github.com/terpnetwork/terp-core/v2/x/globalfee/types" + + tokenfactorykeeper "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" + tokenfactorytypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" + + icqkeeper "github.com/cosmos/ibc-apps/modules/async-icq/v7/keeper" + icqtypes "github.com/cosmos/ibc-apps/modules/async-icq/v7/types" + + packetforwardkeeper "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/keeper" + packetforwardtypes "github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7/router/types" + + "github.com/terpnetwork/terp-core/v2/app/upgrades" +) + +// We now charge 2 million gas * gas price to create a denom. +const NewDenomCreationGasConsume uint64 = 2_000_000 + +// CreateUpgradeHandler creates an SDK upgrade handler for v2 +func CreateUpgradeHandler( + mm *module.Manager, + configurator module.Configurator, + fsk feesharekeeper.Keeper, + gfk globalfeekeeper.Keeper, + tfk tokenfactorykeeper.Keeper, + icqk icqkeeper.Keeper, + pfk packetforwardkeeper.Keeper, +) upgradetypes.UpgradeHandler { + return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { + logger := ctx.Logger().With("upgrade", UpgradeName) + + nativeDenom := upgrades.GetChainsDenomToken(ctx.ChainID()) + logger.Info(fmt.Sprintf("With native denom %s", nativeDenom)) + + // FeeShare + newFeeShareParams := feesharetypes.Params{ + EnableFeeShare: true, + DeveloperShares: sdk.NewDecWithPrec(50, 2), // = 50% + AllowedDenoms: []string{nativeDenom}, + } + if err := fsk.SetParams(ctx, newFeeShareParams); err != nil { + return nil, err + } + logger.Info("set feeshare params") + + // GlobalFee + minGasPrices := sdk.DecCoins{ + // 0.005uthiol + sdk.NewDecCoinFromDec(nativeDenom, sdk.NewDecWithPrec(25, 4)), + } + newGlobalFeeParams := globalfeetypes.Params{ + MinimumGasPrices: minGasPrices, + } + if err := gfk.SetParams(ctx, newGlobalFeeParams); err != nil { + return nil, err + } + logger.Info(fmt.Sprintf("upgraded global fee params to %s", minGasPrices)) + + // x/TokenFactory + // Use denom creation gas consumtion instead of fee for contract developers + updatedTf := tokenfactorytypes.Params{ + DenomCreationFee: nil, + DenomCreationGasConsume: NewDenomCreationGasConsume, + } + + if err := tfk.SetParams(ctx, updatedTf); err != nil { + return nil, err + } + logger.Info(fmt.Sprintf("updated tokenfactory params to %v", updatedTf)) + + // // Interchain Queries + icqParams := icqtypes.NewParams(true, nil) + icqk.SetParams(ctx, icqParams) + + // Packet Forward middleware initial params + pfk.SetParams(ctx, packetforwardtypes.DefaultParams()) + + // Leave modules are as-is to avoid running InitGenesis. + logger.Debug("running module migrations ...") + return mm.RunMigrations(ctx, configurator, vm) + } +} diff --git a/buf.gen.yaml b/buf.gen.yaml new file mode 100644 index 0000000..aaa7db8 --- /dev/null +++ b/buf.gen.yaml @@ -0,0 +1,8 @@ +version: v1 +plugins: + - name: gocosmos + out: . + opt: plugins=interfacetype+grpc,Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types + - name: grpc-gateway + out: . + opt: logtostderr=true,allow_colon_final_segments=true \ No newline at end of file diff --git a/buf.work.yaml b/buf.work.yaml index 1b4a0d9..7a18eb0 100644 --- a/buf.work.yaml +++ b/buf.work.yaml @@ -1,8 +1,3 @@ -# Generated by "buf config migrate-v1beta1". Edit as necessary, and -# remove this comment when you're finished. -# -# This workspace file points to the roots found in your -# previous "buf.yaml" configuration. version: v1 directories: - - proto + - proto \ No newline at end of file diff --git a/chains.yaml b/chains.yaml new file mode 100644 index 0000000..22d3aab --- /dev/null +++ b/chains.yaml @@ -0,0 +1,11 @@ +# This file is used to create docker images using the heighliner binary. +# see: https://github.com/strangelove-ventures/heighliner + +- name: terpnetwork + dockerfile: cosmos + build-target: make install + binaries: + - /go/bin/terpd + build-env: + - LEDGER_ENABLED=false + - BUILD_TAGS=muslc \ No newline at end of file diff --git a/cmd/terpd/cmd/balances_from_state_export.go b/cmd/terpd/cmd/balances_from_state_export.go new file mode 100644 index 0000000..2033484 --- /dev/null +++ b/cmd/terpd/cmd/balances_from_state_export.go @@ -0,0 +1,272 @@ +package cmd + +// modified from osmosis + +import ( + "encoding/csv" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/spf13/cobra" + + tmjson "github.com/cometbft/cometbft/libs/json" + tmtypes "github.com/cometbft/cometbft/types" + + "cosmossdk.io/math" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/server" + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + appparams "github.com/terpnetwork/terp-core/v2/app/params" +) + +const ( + FlagMinimumStakeAmount = "minimum-stake-amount" +) + +type DeriveSnapshot struct { + NumberAccounts uint64 `json:"num_accounts"` + Accounts map[string]DerivedAccount `json:"accounts"` +} + +// DerivedAccount provide fields of snapshot per account +// It is the simplified struct we are presenting in this 'balances from state export' snapshot for people. +type DerivedAccount struct { + Address string `json:"address"` + LiquidBalances sdk.Coins `json:"liquid_balance"` + Staked math.Int `json:"staked"` + UnbondingStake math.Int `json:"unbonding_stake"` + Bonded sdk.Coins `json:"bonded"` + TotalBalances sdk.Coins `json:"total_balances"` +} + +// newDerivedAccount returns a new derived account. +func newDerivedAccount(address string) DerivedAccount { + return DerivedAccount{ + Address: address, + LiquidBalances: sdk.Coins{}, + Staked: sdk.ZeroInt(), + UnbondingStake: sdk.ZeroInt(), + Bonded: sdk.Coins{}, + } +} + +// getGenStateFromPath returns a JSON genState message from inputted path. +func getGenStateFromPath(genesisFilePath string) (map[string]json.RawMessage, error) { + genState := make(map[string]json.RawMessage) + + genesisFile, err := os.Open(filepath.Clean(genesisFilePath)) + if err != nil { + return genState, err + } + defer genesisFile.Close() + + byteValue, _ := io.ReadAll(genesisFile) + + var doc tmtypes.GenesisDoc + err = tmjson.Unmarshal(byteValue, &doc) + if err != nil { + return genState, err + } + + err = json.Unmarshal(doc.AppState, &genState) + if err != nil { + panic(err) + } + return genState, nil +} + +// ExportAirdropSnapshotCmd generates a snapshot.json from a provided exported genesis.json. +func ExportDeriveBalancesCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "export-derive-balances [input-genesis-file] [output-snapshot-json]", + Short: "Export a derive balances from a provided genesis export", + Long: `Export a derive balances from a provided genesis export +Example: + terpd export-derive-balances ../genesis.json ../snapshot.json +`, + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + config.SetRoot(clientCtx.HomeDir) + + genesisFile := args[0] + genState, err := getGenStateFromPath(genesisFile) + if err != nil { + return err + } + snapshotOutput := args[1] + + // Produce the map of address to total terp balance, both staked and UnbondingStake + snapshotAccs := make(map[string]DerivedAccount) + + bankGenesis := banktypes.GenesisState{} + if len(genState["bank"]) > 0 { + clientCtx.Codec.MustUnmarshalJSON(genState["bank"], &bankGenesis) + } + for _, balance := range bankGenesis.Balances { + address := balance.Address + acc, ok := snapshotAccs[address] + if !ok { + acc = newDerivedAccount(address) + } + + acc.LiquidBalances = balance.Coins + snapshotAccs[address] = acc + } + + stakingGenesis := stakingtypes.GenesisState{} + if len(genState["staking"]) > 0 { + clientCtx.Codec.MustUnmarshalJSON(genState["staking"], &stakingGenesis) + } + for _, unbonding := range stakingGenesis.UnbondingDelegations { + address := unbonding.DelegatorAddress + acc, ok := snapshotAccs[address] + if !ok { + acc = newDerivedAccount(address) + } + + unbondingTerps := sdk.NewInt(0) + for _, entry := range unbonding.Entries { + unbondingTerps = unbondingTerps.Add(entry.Balance) + } + + acc.UnbondingStake = acc.UnbondingStake.Add(unbondingTerps) + + snapshotAccs[address] = acc + } + + // Make a map from validator operator address to the v036 validator type + validators := make(map[string]stakingtypes.Validator) + for _, validator := range stakingGenesis.Validators { + validators[validator.OperatorAddress] = validator + } + + for _, delegation := range stakingGenesis.Delegations { + address := delegation.DelegatorAddress + + acc, ok := snapshotAccs[address] + if !ok { + acc = newDerivedAccount(address) + } + + val := validators[delegation.ValidatorAddress] + stakedTerps := delegation.Shares.MulInt(val.Tokens).Quo(val.DelegatorShares).RoundInt() + + acc.Staked = acc.Staked.Add(stakedTerps) + + snapshotAccs[address] = acc + } + + // convert balances to underlying coins and sum up balances to total balance + for addr, account := range snapshotAccs { + // account.LiquidBalances = underlyingCoins(account.LiquidBalances) + // account.Bonded = underlyingCoins(account.Bonded) + account.TotalBalances = sdk.NewCoins(). + Add(account.LiquidBalances...). + Add(sdk.NewCoin(appparams.BondDenom, account.Staked)). + Add(sdk.NewCoin(appparams.BondDenom, account.UnbondingStake)). + Add(account.Bonded...) + snapshotAccs[addr] = account + } + + snapshot := DeriveSnapshot{ + NumberAccounts: uint64(len(snapshotAccs)), + Accounts: snapshotAccs, + } + + fmt.Printf("# accounts: %d\n", len(snapshotAccs)) + + // export snapshot json + snapshotJSON, err := json.MarshalIndent(snapshot, "", " ") + if err != nil { + return fmt.Errorf("failed to marshal snapshot: %w", err) + } + + err = os.WriteFile(snapshotOutput, snapshotJSON, 0o600) + return err + }, + } + + return cmd +} + +// StakedToCSVCmd generates a airdrop.csv from a provided exported balances.json. +func StakedToCSVCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "staked-to-csv [input-balances-file] [output-airdrop-csv]", + Short: "Export a airdrop csv from a provided balances export", + Long: `Export a airdrop csv from a provided balances export (from export-derive-balances) +Example: + terpd staked-to-csv ../balances.json ../airdrop.csv +`, + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + config.SetRoot(clientCtx.HomeDir) + + balancesFile := args[0] + + snapshotOutput := args[1] + + minStakeAmount, _ := cmd.Flags().GetInt64(FlagMinimumStakeAmount) + + var deriveSnapshot DeriveSnapshot + + sourceFile, err := os.Open(balancesFile) + if err != nil { + return err + } + // remember to close the file at the end of the function + defer sourceFile.Close() + + // decode the balances json file into the struct array + if err := json.NewDecoder(sourceFile).Decode(&deriveSnapshot); err != nil { + return err + } + + // create a new file to store CSV data + outputFile, err := os.Create(snapshotOutput) + if err != nil { + return err + } + defer outputFile.Close() + + // write the header of the CSV file + writer := csv.NewWriter(outputFile) + defer writer.Flush() + + header := []string{"address", "staked"} + if err := writer.Write(header); err != nil { + return err + } + + // iterate through all accounts, leave out accounts that do not meet the user provided min stake amount + for _, r := range deriveSnapshot.Accounts { + var csvRow []string + if r.Staked.GT(sdk.NewInt(minStakeAmount)) { + csvRow = append(csvRow, r.Address, r.Staked.String()) + if err := writer.Write(csvRow); err != nil { + return err + } + } + } + + return nil + }, + } + + cmd.Flags().Int64(FlagMinimumStakeAmount, 0, "Specify minimum amount (non inclusive) accounts must stake to be included in airdrop (default: 0)") + + return cmd +} diff --git a/cmd/terpd/cmd/config.go b/cmd/terpd/cmd/config.go new file mode 100644 index 0000000..34e5f86 --- /dev/null +++ b/cmd/terpd/cmd/config.go @@ -0,0 +1,235 @@ +package cmd + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + "text/template" + + "github.com/spf13/cobra" + viper "github.com/spf13/viper" + + tmcli "github.com/cometbft/cometbft/libs/cli" + + "github.com/cosmos/cosmos-sdk/client" + scconfig "github.com/cosmos/cosmos-sdk/client/config" + "github.com/cosmos/cosmos-sdk/client/flags" +) + +type TerpCustomClient struct { + scconfig.ClientConfig + Gas string `mapstructure:"gas" json:"gas"` + GasPrices string `mapstructure:"gas-prices" json:"gas-prices"` + GasAdjustment string `mapstructure:"gas-adjustment" json:"gas-adjustment"` + + Fees string `mapstructure:"fees" json:"fees"` + FeeGranter string `mapstructure:"fee-granter" json:"fee-granter"` + FeePayer string `mapstructure:"fee-payer" json:"fee-payer"` + + Note string `mapstructure:"note" json:"note"` +} + +// ConfigCmd returns a CLI command to interactively create an application CLI +// config file. +func ConfigCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "config [value]", + Short: "Create or query an application CLI configuration file", + RunE: runConfigCmd, + Args: cobra.RangeArgs(0, 2), + } + return cmd +} + +func runConfigCmd(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + configPath := filepath.Join(clientCtx.HomeDir, "config") + + conf, err := getClientConfig(configPath, clientCtx.Viper) + if err != nil { + return fmt.Errorf("couldn't get client config: %v", err) + } + + tcc := TerpCustomClient{ + *conf, + os.Getenv("TERPD_GAS"), + os.Getenv("TERPD_GAS_PRICES"), + os.Getenv("TERPD_GAS_ADJUSTMENT"), + + os.Getenv("TERPD_FEES"), + os.Getenv("TERPD_FEE_GRANTER"), + os.Getenv("TERPD_FEE_PAYER"), + + os.Getenv("TERPD_NOTE"), + } + + switch len(args) { + case 0: + s, err := json.MarshalIndent(tcc, "", "\t") + if err != nil { + return err + } + + cmd.Println(string(s)) + + case 1: + // it's a get + key := args[0] + + switch key { + case flags.FlagChainID: + cmd.Println(conf.ChainID) + case flags.FlagKeyringBackend: + cmd.Println(conf.KeyringBackend) + case tmcli.OutputFlag: + cmd.Println(conf.Output) + case flags.FlagNode: + cmd.Println(conf.Node) + case flags.FlagBroadcastMode: + cmd.Println(conf.BroadcastMode) + + // Custom flags + case flags.FlagGas: + cmd.Println(tcc.Gas) + case flags.FlagGasPrices: + cmd.Println(tcc.GasPrices) + case flags.FlagGasAdjustment: + cmd.Println(tcc.GasAdjustment) + case flags.FlagFees: + cmd.Println(tcc.Fees) + case flags.FlagFeeGranter: + cmd.Println(tcc.FeeGranter) + case flags.FlagFeePayer: + cmd.Println(tcc.FeePayer) + case flags.FlagNote: + cmd.Println(tcc.Note) + default: + err := errUnknownConfigKey(key) + return fmt.Errorf("couldn't get the value for the key: %v, error: %v", key, err) + } + + case 2: + // it's set + key, value := args[0], args[1] + + switch key { + case flags.FlagChainID: + tcc.ChainID = value + case flags.FlagKeyringBackend: + tcc.KeyringBackend = value + case tmcli.OutputFlag: + tcc.Output = value + case flags.FlagNode: + tcc.Node = value + case flags.FlagBroadcastMode: + tcc.BroadcastMode = value + case flags.FlagGas: + tcc.Gas = value + case flags.FlagGasPrices: + tcc.GasPrices = value + tcc.Fees = "" // resets since we can only use 1 at a time + case flags.FlagGasAdjustment: + tcc.GasAdjustment = value + case flags.FlagFees: + tcc.Fees = value + tcc.GasPrices = "" // resets since we can only use 1 at a time + case flags.FlagFeeGranter: + tcc.FeeGranter = value + case flags.FlagFeePayer: + tcc.FeePayer = value + case flags.FlagNote: + tcc.Note = value + default: + return errUnknownConfigKey(key) + } + + confFile := filepath.Join(configPath, "client.toml") + if err := writeConfigToFile(confFile, &tcc); err != nil { + return fmt.Errorf("could not write client config to the file: %v", err) + } + + default: + panic("cound not execute config command") + } + + return nil +} + +const defaultConfigTemplate = `# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +############################################################################### +### Client Configuration ### +############################################################################### + +# The network chain ID +chain-id = "{{ .ChainID }}" +# The keyring's backend, where the keys are stored (os|file|kwallet|pass|test|memory) +keyring-backend = "{{ .KeyringBackend }}" +# CLI output format (text|json) +output = "{{ .Output }}" +# : to Tendermint RPC interface for this chain +node = "{{ .Node }}" +# Transaction broadcasting mode (sync|async|block) +broadcast-mode = "{{ .BroadcastMode }}" + +############################################################################### +### Terp Tx Configuration ### +############################################################################### + +# Amount of gas per transaction +gas = "{{ .Gas }}" +# Price per unit of gas (ex: 0.005uthiol) +gas-prices = "{{ .GasPrices }}" +gas-adjustment = "{{ .GasAdjustment }}" + +# Fees to use instead of set gas prices +fees = "{{ .Fees }}" +fee-granter = "{{ .FeeGranter }}" +fee-payer = "{{ .FeePayer }}" + +# Memo to include in your Transactions +note = "{{ .Note }}" +` + +// writeConfigToFile parses defaultConfigTemplate, renders config using the template and writes it to +// configFilePath. +func writeConfigToFile(configFilePath string, config *TerpCustomClient) error { + var buffer bytes.Buffer + + tmpl := template.New("clientConfigFileTemplate") + configTemplate, err := tmpl.Parse(defaultConfigTemplate) + if err != nil { + return err + } + + if err := configTemplate.Execute(&buffer, config); err != nil { + return err + } + + return os.WriteFile(configFilePath, buffer.Bytes(), 0o600) +} + +// getClientConfig reads values from client.toml file and unmarshalls them into ClientConfig +func getClientConfig(configPath string, v *viper.Viper) (*scconfig.ClientConfig, error) { + v.AddConfigPath(configPath) + v.SetConfigName("client") + v.SetConfigType("toml") + + if err := v.ReadInConfig(); err != nil { + return nil, err + } + + conf := new(scconfig.ClientConfig) + if err := v.Unmarshal(conf); err != nil { + return nil, err + } + + return conf, nil +} + +func errUnknownConfigKey(key string) error { + return fmt.Errorf("unknown configuration key: %q", key) +} diff --git a/cmd/terpd/cmd/debug.go b/cmd/terpd/cmd/debug.go new file mode 100644 index 0000000..71cc578 --- /dev/null +++ b/cmd/terpd/cmd/debug.go @@ -0,0 +1,175 @@ +package cmd + +import ( + "encoding/hex" + "fmt" + "strconv" + "strings" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/bech32" + "github.com/cosmos/cosmos-sdk/version" +) + +// Cmd creates a main CLI command +func DebugCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "debug", + Short: "Tool for helping with debugging your application", + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + PubkeyCmd(), + AddrCmd(), + RawBytesCmd(), + ConvertBech32Cmd(), + ExportDeriveBalancesCmd(), + StakedToCSVCmd(), + ) + + return cmd +} + +var flagBech32Prefix = "prefix" + +// get cmd to convert any bech32 address to a terp prefix. +func ConvertBech32Cmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "bech32-convert [bech32 string]", + Short: "Convert any bech32 string to the terp prefix", + Long: `Convert any bech32 string to the terp prefix +Especially useful for converting cosmos addresses to terp addresses +Example: + terpd bech32-convert terp1ey69r37gfxvxg62sh4r0ktpuc46pzjrm9qvyl8 -p osmo + `, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + bech32prefix, err := cmd.Flags().GetString(flagBech32Prefix) + if err != nil { + return err + } + + _, bz, err := bech32.DecodeAndConvert(args[0]) + if err != nil { + return err + } + + bech32Addr, err := bech32.ConvertAndEncode(bech32prefix, bz) + if err != nil { + panic(err) + } + + cmd.Println(bech32Addr) + + return nil + }, + } + + cmd.Flags().StringP(flagBech32Prefix, "p", "terp", "Bech32 Prefix to encode to") + + return cmd +} + +// getPubKeyFromString decodes SDK PubKey using JSON marshaler. +func getPubKeyFromString(ctx client.Context, pkstr string) (cryptotypes.PubKey, error) { + var pk cryptotypes.PubKey + err := ctx.Codec.UnmarshalInterfaceJSON([]byte(pkstr), &pk) + return pk, err +} + +func PubkeyCmd() *cobra.Command { + return &cobra.Command{ + Use: "pubkey [pubkey]", + Short: "Decode a pubkey from proto JSON", + Long: fmt.Sprintf(`Decode a pubkey from proto JSON and display it's address. + +Example: +$ %s debug pubkey '{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"AurroA7jvfPd1AadmmOvWM2rJSwipXfRf8yD6pLbA2DJ"}' + `, version.AppName), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + pk, err := getPubKeyFromString(clientCtx, args[0]) + if err != nil { + return err + } + cmd.Println("Address:", pk.Address()) + cmd.Println("PubKey Hex:", hex.EncodeToString(pk.Bytes())) + return nil + }, + } +} + +func AddrCmd() *cobra.Command { + return &cobra.Command{ + Use: "addr [address]", + Short: "Convert an address between hex and bech32", + Long: fmt.Sprintf(`Convert an address between hex encoding and bech32. + +Example: +$ %s debug addr cosmos1e0jnq2sun3dzjh8p2xq95kk0expwmd7shwjpfg + `, version.AppName), + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + addrString := args[0] + var addr []byte + + // try hex, then bech32 + var err error + addr, err = hex.DecodeString(addrString) + if err != nil { + var err2 error + addr, err2 = sdk.AccAddressFromBech32(addrString) + if err2 != nil { + var err3 error + addr, err3 = sdk.ValAddressFromBech32(addrString) + + if err3 != nil { + return fmt.Errorf("expected hex or bech32. Got errors: hex: %v, bech32 acc: %v, bech32 val: %v", err, err2, err3) + } + } + } + + cmd.Println("Address:", addr) + cmd.Printf("Address (hex): %X\n", addr) + cmd.Printf("Bech32 Acc: %s\n", sdk.AccAddress(addr)) + cmd.Printf("Bech32 Val: %s\n", sdk.ValAddress(addr)) + return nil + }, + } +} + +func RawBytesCmd() *cobra.Command { + return &cobra.Command{ + Use: "raw-bytes [raw-bytes]", + Short: "Convert raw bytes output (eg. [10 21 13 255]) to hex", + Long: fmt.Sprintf(`Convert raw-bytes to hex. + +Example: +$ %s debug raw-bytes [72 101 108 108 111 44 32 112 108 97 121 103 114 111 117 110 100] + `, version.AppName), + Args: cobra.ExactArgs(1), + RunE: func(_ *cobra.Command, args []string) error { + stringBytes := args[0] + stringBytes = strings.Trim(stringBytes, "[") + stringBytes = strings.Trim(stringBytes, "]") + spl := strings.Split(stringBytes, " ") + + byteArray := []byte{} + for _, s := range spl { + b, err := strconv.ParseInt(s, 10, 8) + if err != nil { + return err + } + byteArray = append(byteArray, byte(b)) + } + fmt.Printf("%X\n", byteArray) + return nil + }, + } +} diff --git a/cmd/terpd/cmd/genica.go b/cmd/terpd/cmd/genica.go new file mode 100644 index 0000000..fe60220 --- /dev/null +++ b/cmd/terpd/cmd/genica.go @@ -0,0 +1,77 @@ +package cmd + +import ( + "encoding/json" + "fmt" + + "github.com/spf13/cobra" + + icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" + icagenesistypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/genesis/types" + icahosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" + icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/server" + "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" +) + +// AddGenesisAccountCmd returns add-genesis-account cobra Command. +func AddGenesisIcaCmd(defaultNodeHome string) *cobra.Command { + cmd := &cobra.Command{ + Use: "add-ica-config", + Short: "Add ICA config to genesis.json", + Long: `Add default ICA configuration to genesis.json`, + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + config.SetRoot(clientCtx.HomeDir) + + genFile := config.GenesisFile() + appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile) + if err != nil { + return fmt.Errorf("failed to unmarshal genesis state: %w", err) + } + + controllerGenesisState := icagenesistypes.DefaultControllerGenesis() + // no params set in upgrade handler, no params set here + controllerGenesisState.Params = icacontrollertypes.Params{} + + hostGenesisState := icagenesistypes.DefaultHostGenesis() + // add the messages we want (from old upgrade handler) + hostGenesisState.Params = icahosttypes.Params{ + HostEnabled: true, + AllowMessages: []string{"*"}, + } + + newIcaGenState := icagenesistypes.NewGenesisState(controllerGenesisState, hostGenesisState) + + icaGenStateBz, err := clientCtx.Codec.MarshalJSON(newIcaGenState) + if err != nil { + return fmt.Errorf("failed to marshal auth genesis state: %w", err) + } + + appState[icatypes.ModuleName] = icaGenStateBz + + appStateJSON, err := json.Marshal(appState) + if err != nil { + return fmt.Errorf("failed to marshal application genesis state: %w", err) + } + + genDoc.AppState = appStateJSON + return genutil.ExportGenesisFile(genDoc, genFile) + }, + } + + cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") + cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/cmd/terpd/cmd/resets.go b/cmd/terpd/cmd/resets.go new file mode 100644 index 0000000..314f531 --- /dev/null +++ b/cmd/terpd/cmd/resets.go @@ -0,0 +1,94 @@ +package cmd + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/spf13/cobra" + + tmos "github.com/cometbft/cometbft/libs/os" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/server" +) + +// Cmd creates a main CLI command +func ResetCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "reset", + Short: "Reset commands for different parts of application state", + RunE: client.ValidateCmd, + } + + cmd.AddCommand(ResetWasmCmd) + cmd.AddCommand(ResetAppCmd) + + return cmd +} + +// ResetWasmCmd removes the database of the specified Tendermint core instance. +var ResetWasmCmd = &cobra.Command{ + Use: "wasm", + Short: "Reset WASM files", + RunE: func(cmd *cobra.Command, args []string) (err error) { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + config.SetRoot(clientCtx.HomeDir) + + return resetWasm(config.DBDir()) + }, +} + +// ResetAppCmd removes the database of the specified Tendermint core instance. +var ResetAppCmd = &cobra.Command{ + Use: "app", + Short: "Reset App files", + RunE: func(cmd *cobra.Command, args []string) (err error) { + clientCtx := client.GetClientContextFromCmd(cmd) + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + config.SetRoot(clientCtx.HomeDir) + + return resetApp(config.DBDir()) + }, +} + +// resetWasm removes wasm files +func resetWasm(dbDir string) error { + wasmDir := filepath.Join(dbDir, "wasm") + + if tmos.FileExists(wasmDir) { + if err := os.RemoveAll(wasmDir); err == nil { + fmt.Println("Removed wasm", "dir", wasmDir) + } else { + return fmt.Errorf("error removing wasm dir: %s; err: %w", wasmDir, err) + } + } + + if err := tmos.EnsureDir(wasmDir, 0o700); err != nil { + return fmt.Errorf("unable to recreate wasm %w", err) + } + return nil +} + +// resetApp removes application.db files +func resetApp(dbDir string) error { + appDir := filepath.Join(dbDir, "application.db") + + if tmos.FileExists(appDir) { + if err := os.RemoveAll(appDir); err == nil { + fmt.Println("Removed application.db", "dir", appDir) + } else { + return fmt.Errorf("error removing application.db dir: %s; err: %w", appDir, err) + } + } + + if err := tmos.EnsureDir(appDir, 0o700); err != nil { + return fmt.Errorf("unable to recreate application.db %w", err) + } + return nil +} diff --git a/cmd/terpd/root.go b/cmd/terpd/cmd/root.go similarity index 75% rename from cmd/terpd/root.go rename to cmd/terpd/cmd/root.go index 28b88bb..0735e58 100644 --- a/cmd/terpd/root.go +++ b/cmd/terpd/cmd/root.go @@ -1,17 +1,29 @@ -package main +package cmd import ( "errors" "io" "os" + "path/filepath" + + "github.com/CosmWasm/wasmd/x/wasm" + wasmcli "github.com/CosmWasm/wasmd/x/wasm/client/cli" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + "github.com/prometheus/client_golang/prometheus" + "github.com/spf13/cast" + "github.com/spf13/cobra" + "github.com/spf13/viper" - rosettaCmd "cosmossdk.io/tools/rosetta/cmd" dbm "github.com/cometbft/cometbft-db" tmcfg "github.com/cometbft/cometbft/config" + tmcli "github.com/cometbft/cometbft/libs/cli" "github.com/cometbft/cometbft/libs/log" + + rosettaCmd "cosmossdk.io/tools/rosetta/cmd" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/config" - "github.com/cosmos/cosmos-sdk/client/debug" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/pruning" @@ -23,18 +35,12 @@ import ( "github.com/cosmos/cosmos-sdk/version" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/crisis" genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" - "github.com/prometheus/client_golang/prometheus" - "github.com/spf13/cast" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/wasm" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" + "github.com/terpnetwork/terp-core/v2/app" + "github.com/terpnetwork/terp-core/v2/app/params" ) // NewRootCmd creates a new root command for terpd. It is called once in the @@ -56,12 +62,17 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { WithLegacyAmino(encodingConfig.Amino). WithInput(os.Stdin). WithAccountRetriever(authtypes.AccountRetriever{}). + WithBroadcastMode(flags.FlagBroadcastMode). WithHomeDir(app.DefaultNodeHome). WithViper("") // In terpd, we don't use any prefix for env variables. + // Allows you to add extra params to your client.toml + // gas, gas-price, gas-adjustment, fees, note, etc. + SetCustomEnvVariablesFromClientToml(initClientCtx) + rootCmd := &cobra.Command{ Use: version.AppName, - Short: "Terp Network Daemon (server)", + Short: "Terp Network Community Network", PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { // set the default command outputs cmd.SetOut(cmd.OutOrStdout()) @@ -145,16 +156,64 @@ func initAppConfig() (string, interface{}) { return customAppTemplate, customAppConfig } +// Reads the custom extra values in the config.toml file if set. +// If they are, then use them. +func SetCustomEnvVariablesFromClientToml(ctx client.Context) { + configFilePath := filepath.Join(ctx.HomeDir, "config", "client.toml") + + if _, err := os.Stat(configFilePath); os.IsNotExist(err) { + return + } + + viper := ctx.Viper + viper.SetConfigFile(configFilePath) + + if err := viper.ReadInConfig(); err != nil { + panic(err) + } + + setEnvFromConfig := func(key string, envVar string) { + // if the user sets the env key manually, then we don't want to override it + if os.Getenv(envVar) != "" { + return + } + + // reads from the config file + val := viper.GetString(key) + if val != "" { + // Sets the env for this instance of the app only. + os.Setenv(envVar, val) + } + } + + // gas + setEnvFromConfig("gas", "TERPD_GAS") + setEnvFromConfig("gas-prices", "TERPD_GAS_PRICES") + setEnvFromConfig("gas-adjustment", "TERPD_GAS_ADJUSTMENT") + // fees + setEnvFromConfig("fees", "TERPD_FEES") + setEnvFromConfig("fee-account", "TERPD_FEE_ACCOUNT") + // memo + setEnvFromConfig("note", "TERPD_NOTE") +} + func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { + ac := appCreator{ + encCfg: encodingConfig, + } + rootCmd.AddCommand( genutilcli.InitCmd(app.ModuleBasics, app.DefaultNodeHome), - // testnetCmd(app.ModuleBasics, banktypes.GenesisBalancesIterator{}), - debug.Cmd(), - config.Cmd(), - pruning.PruningCmd(newApp), + NewTestnetCmd(app.ModuleBasics, banktypes.GenesisBalancesIterator{}), + AddGenesisIcaCmd(app.DefaultNodeHome), + tmcli.NewCompletionCmd(rootCmd, true), + DebugCmd(), + ConfigCmd(), + pruning.PruningCmd(ac.newApp), ) - server.AddCommands(rootCmd, app.DefaultNodeHome, newApp, appExport, addModuleInitFlags) + server.AddCommands(rootCmd, app.DefaultNodeHome, ac.newApp, ac.appExport, addModuleInitFlags) + wasmcli.ExtendUnsafeResetAllCmd(rootCmd) // add keybase, auxiliary RPC, query, and tx child commands rootCmd.AddCommand( @@ -202,6 +261,7 @@ func queryCommand() *cobra.Command { ) app.ModuleBasics.AddQueryCommands(cmd) + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") return cmd } @@ -221,6 +281,7 @@ func txCommand() *cobra.Command { authcmd.GetMultiSignCommand(), authcmd.GetMultiSignBatchCmd(), authcmd.GetValidateSignaturesCommand(), + flags.LineBreak, authcmd.GetBroadcastCommand(), authcmd.GetEncodeCommand(), authcmd.GetDecodeCommand(), @@ -228,26 +289,41 @@ func txCommand() *cobra.Command { ) app.ModuleBasics.AddTxCommands(cmd) + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") return cmd } +type appCreator struct { + encCfg params.EncodingConfig +} + // newApp creates the application -func newApp( +func (ac appCreator) newApp( logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions, ) servertypes.Application { - baseappOptions := server.DefaultBaseappOptions(appOpts) + skipUpgradeHeights := make(map[int64]bool) + for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { + skipUpgradeHeights[int64(h)] = true + } - var wasmOpts []wasm.Option + var wasmOpts []wasmkeeper.Option if cast.ToBool(appOpts.Get("telemetry.enabled")) { wasmOpts = append(wasmOpts, wasmkeeper.WithVMCacheMetrics(prometheus.DefaultRegisterer)) } + loadLatest := true + + baseappOptions := server.DefaultBaseappOptions(appOpts) + return app.NewTerpApp( - logger, db, traceStore, true, + logger, + db, + traceStore, + loadLatest, app.GetEnabledProposals(), appOpts, wasmOpts, @@ -256,7 +332,7 @@ func newApp( } // appExport creates a new wasm app (optionally at a given height) and exports state. -func appExport( +func (ac appCreator) appExport( logger log.Logger, db dbm.DB, traceStore io.Writer, @@ -281,7 +357,7 @@ func appExport( viperAppOpts.Set(server.FlagInvCheckPeriod, 1) appOpts = viperAppOpts - var emptyWasmOpts []wasm.Option + var emptyWasmOpts []wasmkeeper.Option wasmApp = app.NewTerpApp( logger, db, diff --git a/cmd/terpd/cmd/testnet.go b/cmd/terpd/cmd/testnet.go new file mode 100644 index 0000000..69c1c2d --- /dev/null +++ b/cmd/terpd/cmd/testnet.go @@ -0,0 +1,579 @@ +package cmd + +// DONTCOVER + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "os" + "path/filepath" + "time" + + "github.com/CosmWasm/wasmd/app" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + tmconfig "github.com/cometbft/cometbft/config" + tmrand "github.com/cometbft/cometbft/libs/rand" + "github.com/cometbft/cometbft/types" + tmtime "github.com/cometbft/cometbft/types/time" + + "cosmossdk.io/math" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/server" + srvconfig "github.com/cosmos/cosmos-sdk/server/config" + "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/testutil/network" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + "github.com/cosmos/cosmos-sdk/version" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +var ( + flagNodeDirPrefix = "node-dir-prefix" + flagNumValidators = "v" + flagOutputDir = "output-dir" + flagNodeDaemonHome = "node-daemon-home" + flagStartingIPAddress = "starting-ip-address" + flagEnableLogging = "enable-logging" + flagGRPCAddress = "grpc.address" + flagRPCAddress = "rpc.address" + flagAPIAddress = "api.address" + flagPrintMnemonic = "print-mnemonic" + // custom flags + flagCommitTimeout = "commit-timeout" + flagSingleHost = "single-host" +) + +type initArgs struct { + algo string + chainID string + keyringBackend string + minGasPrices string + nodeDaemonHome string + nodeDirPrefix string + numValidators int + outputDir string + startingIPAddress string + singleMachine bool +} + +type startArgs struct { + algo string + apiAddress string + chainID string + enableLogging bool + grpcAddress string + minGasPrices string + numValidators int + outputDir string + printMnemonic bool + rpcAddress string +} + +func addTestnetFlagsToCmd(cmd *cobra.Command) { + cmd.Flags().Int(flagNumValidators, 4, "Number of validators to initialize the testnet with") + cmd.Flags().StringP(flagOutputDir, "o", "./.testnets", "Directory to store initialization data for the testnet") + cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") + cmd.Flags().String(server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") + cmd.Flags().String(flags.FlagKeyType, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for") + + // support old flags name for backwards compatibility + cmd.Flags().SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName { + if name == "algo" { + name = flags.FlagKeyType + } + + return pflag.NormalizedName(name) + }) +} + +// NewTestnetCmd creates a root testnet command with subcommands to run an in-process testnet or initialize +// validator configuration files for running a multi-validator testnet in a separate process +func NewTestnetCmd(mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command { + testnetCmd := &cobra.Command{ + Use: "testnet", + Short: "subcommands for starting or configuring local testnets", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + testnetCmd.AddCommand(testnetStartCmd()) + testnetCmd.AddCommand(testnetInitFilesCmd(mbm, genBalIterator)) + + return testnetCmd +} + +// testnetInitFilesCmd returns a cmd to initialize all files for tendermint testnet and application +func testnetInitFilesCmd(mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command { + cmd := &cobra.Command{ + Use: "init-files", + Short: "Initialize config directories & files for a multi-validator testnet running locally via separate processes (e.g. Docker Compose or similar)", + Long: fmt.Sprintf(`init-files will setup "v" number of directories and populate each with +necessary files (private validator, genesis, config, etc.) for running "v" validator nodes. + +Booting up a network with these validator folders is intended to be used with Docker Compose, +or a similar setup where each node has a manually configurable IP address. + +Note, strict routability for addresses is turned off in the config file. + +Example: + %s testnet init-files --v 4 --output-dir ./.testnets --starting-ip-address 192.168.10.2 + `, version.AppName), + RunE: func(cmd *cobra.Command, _ []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + args := initArgs{} + args.outputDir, _ = cmd.Flags().GetString(flagOutputDir) + args.keyringBackend, _ = cmd.Flags().GetString(flags.FlagKeyringBackend) + args.chainID, _ = cmd.Flags().GetString(flags.FlagChainID) + args.minGasPrices, _ = cmd.Flags().GetString(server.FlagMinGasPrices) + args.nodeDirPrefix, _ = cmd.Flags().GetString(flagNodeDirPrefix) + args.nodeDaemonHome, _ = cmd.Flags().GetString(flagNodeDaemonHome) + args.startingIPAddress, _ = cmd.Flags().GetString(flagStartingIPAddress) + args.numValidators, _ = cmd.Flags().GetInt(flagNumValidators) + args.algo, _ = cmd.Flags().GetString(flags.FlagKeyType) + + args.singleMachine, _ = cmd.Flags().GetBool(flagSingleHost) + config.Consensus.TimeoutCommit, err = cmd.Flags().GetDuration(flagCommitTimeout) + if err != nil { + return err + } + + return initTestnetFiles(clientCtx, cmd, config, mbm, genBalIterator, args) + }, + } + + addTestnetFlagsToCmd(cmd) + cmd.Flags().String(flagNodeDirPrefix, "node", "Prefix the directory name for each node with (node results in node0, node1, ...)") + cmd.Flags().String(flagNodeDaemonHome, "terpd", "Home directory of the node's daemon configuration") + cmd.Flags().String(flagStartingIPAddress, "192.168.0.1", "Starting IP address (192.168.0.1 results in persistent peers list ID0@192.168.0.1:46656, ID1@192.168.0.2:46656, ...)") + cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)") + cmd.Flags().Duration(flagCommitTimeout, 5*time.Second, "Time to wait after a block commit before starting on the new height") + cmd.Flags().Bool(flagSingleHost, false, "Cluster runs on a single host machine with different ports") + + return cmd +} + +// testnetStartCmd returns a cmd to start multi validator in-process testnet +func testnetStartCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "start", + Short: "Launch an in-process multi-validator testnet", + Long: fmt.Sprintf(`testnet will launch an in-process multi-validator testnet, +and generate "v" directories, populated with necessary validator configuration files +(private validator, genesis, config, etc.). + +Example: + %s testnet --v 4 --output-dir ./.testnets + `, version.AppName), + RunE: func(cmd *cobra.Command, _ []string) error { + args := startArgs{} + args.outputDir, _ = cmd.Flags().GetString(flagOutputDir) + args.chainID, _ = cmd.Flags().GetString(flags.FlagChainID) + args.minGasPrices, _ = cmd.Flags().GetString(server.FlagMinGasPrices) + args.numValidators, _ = cmd.Flags().GetInt(flagNumValidators) + args.algo, _ = cmd.Flags().GetString(flags.FlagKeyType) + args.enableLogging, _ = cmd.Flags().GetBool(flagEnableLogging) + args.rpcAddress, _ = cmd.Flags().GetString(flagRPCAddress) + args.apiAddress, _ = cmd.Flags().GetString(flagAPIAddress) + args.grpcAddress, _ = cmd.Flags().GetString(flagGRPCAddress) + args.printMnemonic, _ = cmd.Flags().GetBool(flagPrintMnemonic) + + return startTestnet(cmd, args) + }, + } + + addTestnetFlagsToCmd(cmd) + cmd.Flags().Bool(flagEnableLogging, false, "Enable INFO logging of tendermint validator nodes") + cmd.Flags().String(flagRPCAddress, "tcp://0.0.0.0:26657", "the RPC address to listen on") + cmd.Flags().String(flagAPIAddress, "tcp://0.0.0.0:1317", "the address to listen on for REST API") + cmd.Flags().String(flagGRPCAddress, "0.0.0.0:9090", "the gRPC server address to listen on") + cmd.Flags().Bool(flagPrintMnemonic, true, "print mnemonic of first validator to stdout for manual testing") + return cmd +} + +const nodeDirPerm = 0o755 + +// initTestnetFiles initializes testnet files for a testnet to be run in a separate process +func initTestnetFiles( + clientCtx client.Context, + cmd *cobra.Command, + nodeConfig *tmconfig.Config, + mbm module.BasicManager, + genBalIterator banktypes.GenesisBalancesIterator, + args initArgs, +) error { + if args.chainID == "" { + args.chainID = "chain-" + tmrand.Str(6) + } + nodeIDs := make([]string, args.numValidators) + valPubKeys := make([]cryptotypes.PubKey, args.numValidators) + + appConfig := srvconfig.DefaultConfig() + appConfig.MinGasPrices = args.minGasPrices + appConfig.API.Enable = true + appConfig.Telemetry.Enabled = true + appConfig.Telemetry.PrometheusRetentionTime = 60 + appConfig.Telemetry.EnableHostnameLabel = false + appConfig.Telemetry.GlobalLabels = [][]string{{"chain_id", args.chainID}} + + var ( + genAccounts []authtypes.GenesisAccount + genBalances []banktypes.Balance + genFiles []string + ) + const ( + rpcPort = 26657 + apiPort = 1317 + grpcPort = 9090 + grpcWebPort = 8090 + ) + p2pPortStart := 26656 + + inBuf := bufio.NewReader(cmd.InOrStdin()) + // generate private keys, node IDs, and initial transactions + for i := 0; i < args.numValidators; i++ { + var portOffset int + if args.singleMachine { + portOffset = i + p2pPortStart = 16656 // use different start point to not conflict with rpc port + nodeConfig.P2P.AddrBookStrict = false + nodeConfig.P2P.PexReactor = false + nodeConfig.P2P.AllowDuplicateIP = true + } + + nodeDirName := fmt.Sprintf("%s%d", args.nodeDirPrefix, i) + nodeDir := filepath.Join(args.outputDir, nodeDirName, args.nodeDaemonHome) + gentxsDir := filepath.Join(args.outputDir, "gentxs") + + nodeConfig.SetRoot(nodeDir) + nodeConfig.Moniker = nodeDirName + nodeConfig.RPC.ListenAddress = "tcp://0.0.0.0:26657" + + appConfig.API.Address = fmt.Sprintf("tcp://0.0.0.0:%d", apiPort+portOffset) + appConfig.GRPC.Address = fmt.Sprintf("0.0.0.0:%d", grpcPort+portOffset) + appConfig.GRPCWeb.Address = fmt.Sprintf("0.0.0.0:%d", grpcWebPort+portOffset) + + if err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm); err != nil { + _ = os.RemoveAll(args.outputDir) + return err + } + + ip, err := getIP(i, args.startingIPAddress) + if err != nil { + _ = os.RemoveAll(args.outputDir) + return err + } + + nodeIDs[i], valPubKeys[i], err = genutil.InitializeNodeValidatorFiles(nodeConfig) + if err != nil { + _ = os.RemoveAll(args.outputDir) + return err + } + + memo := fmt.Sprintf("%s@%s:%d", nodeIDs[i], ip, p2pPortStart+portOffset) + genFiles = append(genFiles, nodeConfig.GenesisFile()) + + kb, err := keyring.New(sdk.KeyringServiceName(), args.keyringBackend, nodeDir, inBuf, clientCtx.Codec) + if err != nil { + return err + } + + keyringAlgos, _ := kb.SupportedAlgorithms() + algo, err := keyring.NewSigningAlgoFromString(args.algo, keyringAlgos) + if err != nil { + return err + } + + addr, secret, err := testutil.GenerateSaveCoinKey(kb, nodeDirName, "", true, algo) + if err != nil { + _ = os.RemoveAll(args.outputDir) + return err + } + + info := map[string]string{"secret": secret} + + cliPrint, err := json.Marshal(info) + if err != nil { + return err + } + + // save private key seed words + if err := writeFile(fmt.Sprintf("%v.json", "key_seed"), nodeDir, cliPrint); err != nil { + return err + } + + accTokens := sdk.TokensFromConsensusPower(1000, sdk.DefaultPowerReduction) + accStakingTokens := sdk.TokensFromConsensusPower(500, sdk.DefaultPowerReduction) + coins := sdk.Coins{ + sdk.NewCoin("testtoken", accTokens), + sdk.NewCoin(sdk.DefaultBondDenom, accStakingTokens), + } + + genBalances = append(genBalances, banktypes.Balance{Address: addr.String(), Coins: coins.Sort()}) + genAccounts = append(genAccounts, authtypes.NewBaseAccount(addr, nil, 0, 0)) + + valTokens := sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction) + createValMsg, err := stakingtypes.NewMsgCreateValidator( + sdk.ValAddress(addr), + valPubKeys[i], + sdk.NewCoin(sdk.DefaultBondDenom, valTokens), + stakingtypes.NewDescription(nodeDirName, "", "", "", ""), + stakingtypes.NewCommissionRates(math.LegacyOneDec(), math.LegacyOneDec(), math.LegacyOneDec()), + math.OneInt(), + ) + if err != nil { + return err + } + + txBuilder := clientCtx.TxConfig.NewTxBuilder() + if err := txBuilder.SetMsgs(createValMsg); err != nil { + return err + } + + txBuilder.SetMemo(memo) + + txFactory := tx.Factory{} + txFactory = txFactory. + WithChainID(args.chainID). + WithMemo(memo). + WithKeybase(kb). + WithTxConfig(clientCtx.TxConfig) + + if err := tx.Sign(txFactory, nodeDirName, txBuilder, true); err != nil { + return err + } + + txBz, err := clientCtx.TxConfig.TxJSONEncoder()(txBuilder.GetTx()) + if err != nil { + return err + } + + if err := writeFile(fmt.Sprintf("%v.json", nodeDirName), gentxsDir, txBz); err != nil { + return err + } + + srvconfig.WriteConfigFile(filepath.Join(nodeDir, "config", "app.toml"), appConfig) + } + + if err := initGenFiles(clientCtx, mbm, args.chainID, genAccounts, genBalances, genFiles, args.numValidators); err != nil { + return err + } + + err := collectGenFiles( + clientCtx, nodeConfig, args.chainID, nodeIDs, valPubKeys, args.numValidators, + args.outputDir, args.nodeDirPrefix, args.nodeDaemonHome, genBalIterator, + rpcPort, p2pPortStart, args.singleMachine, + ) + if err != nil { + return err + } + + cmd.PrintErrf("Successfully initialized %d node directories\n", args.numValidators) + return nil +} + +func initGenFiles( + clientCtx client.Context, mbm module.BasicManager, chainID string, + genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, + genFiles []string, numValidators int, +) error { + appGenState := mbm.DefaultGenesis(clientCtx.Codec) + + // set the accounts in the genesis state + var authGenState authtypes.GenesisState + clientCtx.Codec.MustUnmarshalJSON(appGenState[authtypes.ModuleName], &authGenState) + + accounts, err := authtypes.PackAccounts(genAccounts) + if err != nil { + return err + } + + authGenState.Accounts = accounts + appGenState[authtypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(&authGenState) + + // set the balances in the genesis state + var bankGenState banktypes.GenesisState + clientCtx.Codec.MustUnmarshalJSON(appGenState[banktypes.ModuleName], &bankGenState) + + bankGenState.Balances = banktypes.SanitizeGenesisBalances(genBalances) + for _, bal := range bankGenState.Balances { + bankGenState.Supply = bankGenState.Supply.Add(bal.Coins...) + } + appGenState[banktypes.ModuleName] = clientCtx.Codec.MustMarshalJSON(&bankGenState) + + appGenStateJSON, err := json.MarshalIndent(appGenState, "", " ") + if err != nil { + return err + } + + genDoc := types.GenesisDoc{ + ChainID: chainID, + AppState: appGenStateJSON, + Validators: nil, + } + + // generate empty genesis files for each validator and save + for i := 0; i < numValidators; i++ { + if err := genDoc.SaveAs(genFiles[i]); err != nil { + return err + } + } + return nil +} + +func collectGenFiles( + clientCtx client.Context, nodeConfig *tmconfig.Config, chainID string, + nodeIDs []string, valPubKeys []cryptotypes.PubKey, numValidators int, + outputDir, nodeDirPrefix, nodeDaemonHome string, genBalIterator banktypes.GenesisBalancesIterator, + rpcPortStart, p2pPortStart int, + singleMachine bool, +) error { + var appState json.RawMessage + genTime := tmtime.Now() + + for i := 0; i < numValidators; i++ { + var portOffset int + if singleMachine { + portOffset = i + } + + nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i) + nodeDir := filepath.Join(outputDir, nodeDirName, nodeDaemonHome) + gentxsDir := filepath.Join(outputDir, "gentxs") + nodeConfig.Moniker = nodeDirName + nodeConfig.RPC.ListenAddress = fmt.Sprintf("tcp://0.0.0.0:%d", rpcPortStart+portOffset) + nodeConfig.P2P.ListenAddress = fmt.Sprintf("tcp://0.0.0.0:%d", p2pPortStart+portOffset) + + nodeConfig.SetRoot(nodeDir) + + nodeID, valPubKey := nodeIDs[i], valPubKeys[i] + initCfg := genutiltypes.NewInitConfig(chainID, gentxsDir, nodeID, valPubKey) + + genDoc, err := types.GenesisDocFromFile(nodeConfig.GenesisFile()) + if err != nil { + return err + } + + nodeAppState, err := genutil.GenAppStateFromConfig(clientCtx.Codec, clientCtx.TxConfig, nodeConfig, initCfg, *genDoc, genBalIterator, genutiltypes.DefaultMessageValidator) + if err != nil { + return err + } + + if appState == nil { + // set the canonical application state (they should not differ) + appState = nodeAppState + } + + genFile := nodeConfig.GenesisFile() + + // overwrite each validator's genesis file to have a canonical genesis time + if err := genutil.ExportGenesisFileWithTime(genFile, chainID, nil, appState, genTime); err != nil { + return err + } + } + + return nil +} + +func getIP(i int, startingIPAddr string) (ip string, err error) { + if len(startingIPAddr) == 0 { + ip, err = server.ExternalIP() + if err != nil { + return "", err + } + return ip, nil + } + return calculateIP(startingIPAddr, i) +} + +func calculateIP(ip string, i int) (string, error) { + ipv4 := net.ParseIP(ip).To4() + if ipv4 == nil { + return "", fmt.Errorf("%v: non ipv4 address", ip) + } + + for j := 0; j < i; j++ { + ipv4[3]++ + } + + return ipv4.String(), nil +} + +func writeFile(name string, dir string, contents []byte) error { + file := filepath.Join(dir, name) + + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("could not create directory %q: %w", dir, err) + } + + if err := os.WriteFile(file, contents, 0o644); err != nil { //nolint: gosec + return err + } + + return nil +} + +// startTestnet starts an in-process testnet +func startTestnet(cmd *cobra.Command, args startArgs) error { + networkConfig := network.DefaultConfig(app.NewTestNetworkFixture) + + // Default networkConfig.ChainID is random, and we should only override it if chainID provided + // is non-empty + if args.chainID != "" { + networkConfig.ChainID = args.chainID + } + networkConfig.SigningAlgo = args.algo + networkConfig.MinGasPrices = args.minGasPrices + networkConfig.NumValidators = args.numValidators + networkConfig.EnableTMLogging = args.enableLogging + networkConfig.RPCAddress = args.rpcAddress + networkConfig.APIAddress = args.apiAddress + networkConfig.GRPCAddress = args.grpcAddress + networkConfig.PrintMnemonic = args.printMnemonic + networkLogger := network.NewCLILogger(cmd) + + baseDir := fmt.Sprintf("%s/%s", args.outputDir, networkConfig.ChainID) + if _, err := os.Stat(baseDir); !os.IsNotExist(err) { + return fmt.Errorf( + "testnests directory already exists for chain-id '%s': %s, please remove or select a new --chain-id", + networkConfig.ChainID, baseDir) + } + + testnet, err := network.New(networkLogger, baseDir, networkConfig) + if err != nil { + return err + } + + if _, err := testnet.WaitForHeight(1); err != nil { + return err + } + cmd.Println("press the Enter Key to terminate") + if _, err := fmt.Scanln(); err != nil { // wait for Enter Key + return err + } + testnet.Cleanup() + + return nil +} diff --git a/cmd/terpd/main.go b/cmd/terpd/main.go index 4ecbabd..846d63b 100644 --- a/cmd/terpd/main.go +++ b/cmd/terpd/main.go @@ -3,22 +3,20 @@ package main import ( "os" - "github.com/cosmos/cosmos-sdk/server" + "cosmossdk.io/log" + svrcmd "github.com/cosmos/cosmos-sdk/server/cmd" - "github.com/terpnetwork/terp-core/app" + "github.com/terpnetwork/terp-core/v2/app" + "github.com/terpnetwork/terp-core/v2/cmd/terpd/cmd" ) func main() { - rootCmd, _ := NewRootCmd() - - if err := svrcmd.Execute(rootCmd, "", app.DefaultNodeHome); err != nil { - switch e := err.(type) { - case server.ErrorCode: - os.Exit(e.Code) + app.SetAddressPrefixes() + rootCmd, _ := cmd.NewRootCmd() - default: - os.Exit(1) - } + if err := svrcmd.Execute(rootCmd, "TERPD", app.DefaultNodeHome); err != nil { + log.NewLogger(rootCmd.OutOrStderr()).Error("failure when running app", "err", err) + os.Exit(1) } } diff --git a/config.yml b/config.yml index ce1af9f..77b0d9b 100644 --- a/config.yml +++ b/config.yml @@ -1,10 +1,14 @@ accounts: - name: alex - coins: ["20000token", "200000000stake"] + coins: ["444token", "444stake"] + - name: athena + coins: ["10000token", "100000000stake"] - name: bob + oins: ["10000token", "100000000stake"] + - name: jen coins: ["10000token", "100000000stake"] validator: - name: alex + name: athena staked: "100000000stake" client: openapi: diff --git a/contrib/devtools/DockerFile b/contrib/devtools/DockerFile new file mode 100644 index 0000000..a2d91ad --- /dev/null +++ b/contrib/devtools/DockerFile @@ -0,0 +1,36 @@ +## To test locally: +# docker build --pull --rm -f "contrib/devtools/Dockerfile" -t cosmossdk-proto:latest "contrib/devtools" +# docker run --rm -v $(pwd):/workspace --workdir /workspace cosmossdk-proto sh ./scripts/protocgen.sh + +FROM bufbuild/buf:1.9.0 as BUILDER +FROM golang:1.20-alpine + +RUN apk add --no-cache \ + nodejs \ + npm \ + git \ + make \ + clang-extra-tools + +RUN npm install -g swagger-combine + +ARG UNAME=protobuild +ARG UID=1000 +RUN adduser -u $UID -s /bin/sh $UNAME -D +USER $UNAME + +ENV GOLANG_PROTOBUF_VERSION=1.28.1 \ + GRPC_GATEWAY_VERSION=1.16.0 + +RUN go install github.com/cosmos/cosmos-proto/cmd/protoc-gen-go-pulsar@latest && \ + go install google.golang.org/protobuf/cmd/protoc-gen-go@v${GOLANG_PROTOBUF_VERSION} && \ + go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v${GRPC_GATEWAY_VERSION} \ + github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@v${GRPC_GATEWAY_VERSION} + +# install all gogo protobuf binaries +RUN git clone https://github.com/cosmos/gogoproto.git; \ + cd gogoproto; \ + go mod download; \ + make install + +COPY --from=BUILDER /usr/local/bin /usr/local/bin \ No newline at end of file diff --git a/contrib/devtools/Makefile b/contrib/devtools/Makefile index 1f2c3a5..f8a5de4 100644 --- a/contrib/devtools/Makefile +++ b/contrib/devtools/Makefile @@ -49,37 +49,28 @@ BUF_VERSION ?= 0.11.0 TOOLS_DESTDIR ?= $(GOPATH)/bin STATIK = $(TOOLS_DESTDIR)/statik RUNSIM = $(TOOLS_DESTDIR)/runsim -GOLANGCI_LINT = $(TOOLS_DESTDIR)/golangci-lint tools: tools-stamp -tools-stamp: statik runsim golangci-lint +tools-stamp: statik runsim # Create dummy file to satisfy dependency and avoid # rebuilding when this Makefile target is hit twice # in a row. touch $@ +# Install the runsim binary statik: $(STATIK) $(STATIK): @echo "Installing statik..." - @(cd /tmp && go install github.com/rakyll/statik@v0.1.6) + @go install github.com/rakyll/statik@v0.1.6 -# Install the runsim binary with a temporary workaround of entering an outside -# directory as the "go get" command ignores the -mod option and will polute the -# go.{mod, sum} files. -# -# ref: https://github.com/golang/go/issues/30515 +# Install the runsim binary runsim: $(RUNSIM) $(RUNSIM): @echo "Installing runsim..." - @(cd /tmp && go install github.com/cosmos/tools/cmd/runsim@v1.0.0) - -golangci-lint: $(GOLANGCI_LINT) -$(GOLANGCI_LINT): - @echo "Installing golangci-lint..." - @(cd /tmp && go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.47) + @go install github.com/cosmos/tools/cmd/runsim@v1.0.0 tools-clean: rm -f $(STATIK) $(GOLANGCI_LINT) $(RUNSIM) rm -f tools-stamp -.PHONY: tools-clean statik runsim +.PHONY: tools-clean statik runsim \ No newline at end of file diff --git a/contrib/devtools/README.md b/contrib/devtools/README.md index 6cd3450..b005dc2 100644 --- a/contrib/devtools/README.md +++ b/contrib/devtools/README.md @@ -1,6 +1,6 @@ -## Contributors +# Contributors Thanks to the entire Cosmos SDK team and the contributors who put their efforts into making simulation testing easier to implement. 🤗 -https://github.com/cosmos/cosmos-sdk/blob/masSSter/contrib/devtools/Makefile \ No newline at end of file + \ No newline at end of file diff --git a/contrib/local/01-accounts.sh b/contrib/local/01-accounts.sh deleted file mode 100755 index c58e467..0000000 --- a/contrib/local/01-accounts.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail - -BASE_ACCOUNT=$(terpd keys show validator -a --keyring-backend=test) -terpd q account "$BASE_ACCOUNT" -o json | jq - -echo "## Add new account" -terpd keys add fred --keyring-backend=test - -echo "## Check balance" -NEW_ACCOUNT=$(terpd keys show fred -a --keyring-backend=test ) -terpd q bank balances "$NEW_ACCOUNT" -o json || true - -echo "## Transfer tokens" -terpd tx bank send validator "$NEW_ACCOUNT" 1ustake --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b sync -o json | jq --keyring-backend=test - -echo "## Check balance again" -terpd q bank balances "$NEW_ACCOUNT" -o json | jq diff --git a/contrib/local/02-contracts.sh b/contrib/local/02-contracts.sh deleted file mode 100755 index 4544d0b..0000000 --- a/contrib/local/02-contracts.sh +++ /dev/null @@ -1,112 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail -x - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" - -echo "-----------------------" -echo "## Add new CosmWasm contract" -RESP=$(terpd tx wasm store "$DIR/../../x/wasm/keeper/testdata/hackatom.wasm" \ - --from validator --gas 1500000 -y --chain-id=testing --node=http://localhost:26657 -b sync -o json --keyring-backend=test) -sleep 6 -RESP=$(terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json) -CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[]| select(.type=="store_code").attributes[]| select(.key=="code_id").value') -CODE_HASH=$(echo "$RESP" | jq -r '.logs[0].events[]| select(.type=="store_code").attributes[]| select(.key=="code_checksum").value') -echo "* Code id: $CODE_ID" -echo "* Code checksum: $CODE_HASH" - -echo "* Download code" -TMPDIR=$(mktemp -t terpdXXXXXX) -terpd q wasm code "$CODE_ID" "$TMPDIR" -rm -f "$TMPDIR" -echo "-----------------------" -echo "## List code" -terpd query wasm list-code --node=http://localhost:26657 -o json | jq - -echo "-----------------------" -echo "## Create new contract instance" -INIT="{\"verifier\":\"$(terpd keys show validator -a --keyring-backend=test)\", \"beneficiary\":\"$(terpd keys show fred -a --keyring-backend=test)\"}" -RESP=$(terpd tx wasm instantiate "$CODE_ID" "$INIT" --admin="$(terpd keys show validator -a --keyring-backend=test)" \ - --from validator --amount="100ustake" --label "local0.1.0" \ - --gas 1000000 -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - -CONTRACT=$(terpd query wasm list-contract-by-code "$CODE_ID" -o json | jq -r '.contracts[-1]') -echo "* Contract address: $CONTRACT" - -echo "## Create new contract instance with predictable address" -RESP=$(terpd tx wasm instantiate2 "$CODE_ID" "$INIT" $(echo -n "testing" | xxd -ps) \ - --admin="$(terpd keys show validator -a --keyring-backend=test)" \ - --from validator --amount="100ustake" --label "local0.1.0" \ - --fix-msg \ - --gas 1000000 -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - - -predictedAdress=$(terpd q wasm build-address "$CODE_HASH" $(terpd keys show validator -a --keyring-backend=test) $(echo -n "testing" | xxd -ps) "$INIT") -terpd q wasm contract "$predictedAdress" -o json | jq - -echo "### Query all" -RESP=$(terpd query wasm contract-state all "$CONTRACT" -o json) -echo "$RESP" | jq -echo "### Query smart" -terpd query wasm contract-state smart "$CONTRACT" '{"verifier":{}}' -o json | jq -echo "### Query raw" -KEY=$(echo "$RESP" | jq -r ".models[0].key") -terpd query wasm contract-state raw "$CONTRACT" "$KEY" -o json | jq - -echo "-----------------------" -echo "## Execute contract $CONTRACT" -MSG='{"release":{}}' -RESP=$(terpd tx wasm execute "$CONTRACT" "$MSG" \ - --from validator \ - --gas 1000000 -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - - -echo "-----------------------" -echo "## Set new admin" -echo "### Query old admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" -echo "### Update contract" -RESP=$(terpd tx wasm set-contract-admin "$CONTRACT" "$(terpd keys show fred -a --keyring-backend=test)" \ - --from validator -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - -echo "### Query new admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" - -echo "-----------------------" -echo "## Migrate contract" -echo "### Upload new code" -RESP=$(terpd tx wasm store "$DIR/../../x/wasm/keeper/testdata/burner.wasm" \ - --from validator --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b sync -o json --keyring-backend=test) -sleep 6 -RESP=$(terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json) -BURNER_CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[]| select(.type=="store_code").attributes[]| select(.key=="code_id").value') -echo "### Migrate to code id: $BURNER_CODE_ID" - -DEST_ACCOUNT=$(terpd keys show fred -a --keyring-backend=test) -RESP=$(terpd tx wasm migrate "$CONTRACT" "$BURNER_CODE_ID" "{\"payout\": \"$DEST_ACCOUNT\"}" --from fred \ - --chain-id=testing -b sync -y -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - -echo "### Query destination account: $BURNER_CODE_ID" -terpd q bank balances "$DEST_ACCOUNT" -o json | jq -echo "### Query contract meta data: $CONTRACT" -terpd q wasm contract "$CONTRACT" -o json | jq - -echo "### Query contract meta history: $CONTRACT" -terpd q wasm contract-history "$CONTRACT" -o json | jq - -echo "-----------------------" -echo "## Clear contract admin" -echo "### Query old admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" -echo "### Update contract" -RESP=$(terpd tx wasm clear-contract-admin "$CONTRACT" \ - --from fred -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq -echo "### Query new admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" \ No newline at end of file diff --git a/contrib/local/03-grpc-queries.sh b/contrib/local/03-grpc-queries.sh deleted file mode 100755 index 4544d0b..0000000 --- a/contrib/local/03-grpc-queries.sh +++ /dev/null @@ -1,112 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail -x - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" - -echo "-----------------------" -echo "## Add new CosmWasm contract" -RESP=$(terpd tx wasm store "$DIR/../../x/wasm/keeper/testdata/hackatom.wasm" \ - --from validator --gas 1500000 -y --chain-id=testing --node=http://localhost:26657 -b sync -o json --keyring-backend=test) -sleep 6 -RESP=$(terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json) -CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[]| select(.type=="store_code").attributes[]| select(.key=="code_id").value') -CODE_HASH=$(echo "$RESP" | jq -r '.logs[0].events[]| select(.type=="store_code").attributes[]| select(.key=="code_checksum").value') -echo "* Code id: $CODE_ID" -echo "* Code checksum: $CODE_HASH" - -echo "* Download code" -TMPDIR=$(mktemp -t terpdXXXXXX) -terpd q wasm code "$CODE_ID" "$TMPDIR" -rm -f "$TMPDIR" -echo "-----------------------" -echo "## List code" -terpd query wasm list-code --node=http://localhost:26657 -o json | jq - -echo "-----------------------" -echo "## Create new contract instance" -INIT="{\"verifier\":\"$(terpd keys show validator -a --keyring-backend=test)\", \"beneficiary\":\"$(terpd keys show fred -a --keyring-backend=test)\"}" -RESP=$(terpd tx wasm instantiate "$CODE_ID" "$INIT" --admin="$(terpd keys show validator -a --keyring-backend=test)" \ - --from validator --amount="100ustake" --label "local0.1.0" \ - --gas 1000000 -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - -CONTRACT=$(terpd query wasm list-contract-by-code "$CODE_ID" -o json | jq -r '.contracts[-1]') -echo "* Contract address: $CONTRACT" - -echo "## Create new contract instance with predictable address" -RESP=$(terpd tx wasm instantiate2 "$CODE_ID" "$INIT" $(echo -n "testing" | xxd -ps) \ - --admin="$(terpd keys show validator -a --keyring-backend=test)" \ - --from validator --amount="100ustake" --label "local0.1.0" \ - --fix-msg \ - --gas 1000000 -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - - -predictedAdress=$(terpd q wasm build-address "$CODE_HASH" $(terpd keys show validator -a --keyring-backend=test) $(echo -n "testing" | xxd -ps) "$INIT") -terpd q wasm contract "$predictedAdress" -o json | jq - -echo "### Query all" -RESP=$(terpd query wasm contract-state all "$CONTRACT" -o json) -echo "$RESP" | jq -echo "### Query smart" -terpd query wasm contract-state smart "$CONTRACT" '{"verifier":{}}' -o json | jq -echo "### Query raw" -KEY=$(echo "$RESP" | jq -r ".models[0].key") -terpd query wasm contract-state raw "$CONTRACT" "$KEY" -o json | jq - -echo "-----------------------" -echo "## Execute contract $CONTRACT" -MSG='{"release":{}}' -RESP=$(terpd tx wasm execute "$CONTRACT" "$MSG" \ - --from validator \ - --gas 1000000 -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - - -echo "-----------------------" -echo "## Set new admin" -echo "### Query old admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" -echo "### Update contract" -RESP=$(terpd tx wasm set-contract-admin "$CONTRACT" "$(terpd keys show fred -a --keyring-backend=test)" \ - --from validator -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - -echo "### Query new admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" - -echo "-----------------------" -echo "## Migrate contract" -echo "### Upload new code" -RESP=$(terpd tx wasm store "$DIR/../../x/wasm/keeper/testdata/burner.wasm" \ - --from validator --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b sync -o json --keyring-backend=test) -sleep 6 -RESP=$(terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json) -BURNER_CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[]| select(.type=="store_code").attributes[]| select(.key=="code_id").value') -echo "### Migrate to code id: $BURNER_CODE_ID" - -DEST_ACCOUNT=$(terpd keys show fred -a --keyring-backend=test) -RESP=$(terpd tx wasm migrate "$CONTRACT" "$BURNER_CODE_ID" "{\"payout\": \"$DEST_ACCOUNT\"}" --from fred \ - --chain-id=testing -b sync -y -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq - -echo "### Query destination account: $BURNER_CODE_ID" -terpd q bank balances "$DEST_ACCOUNT" -o json | jq -echo "### Query contract meta data: $CONTRACT" -terpd q wasm contract "$CONTRACT" -o json | jq - -echo "### Query contract meta history: $CONTRACT" -terpd q wasm contract-history "$CONTRACT" -o json | jq - -echo "-----------------------" -echo "## Clear contract admin" -echo "### Query old admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" -echo "### Update contract" -RESP=$(terpd tx wasm clear-contract-admin "$CONTRACT" \ - --from fred -y --chain-id=testing -b sync -o json --keyring-backend=test) -sleep 6 -terpd q tx $(echo "$RESP"| jq -r '.txhash') -o json | jq -echo "### Query new admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" \ No newline at end of file diff --git a/contrib/local/README.md b/contrib/local/README.md deleted file mode 100644 index 234e442..0000000 --- a/contrib/local/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Dev scripts -For manual testing. Works on my box(*) ... - - -*) OSX - -``` -make install -cd contrib/local -rm -rf /tmp/trash -HOME=/tmp/trash bash setup_wasmd.sh -HOME=/tmp/trash bash start_node.sh -``` - -Next shell: - -``` -cd contrib/local -./01-accounts.sh -./02-contracts.sh -``` - -## Shell script development - -[Use `shellcheck`](https://www.shellcheck.net/) to avoid common mistakes in shell scripts. -[Use `shfmt`](https://github.com/mvdan/sh) to ensure a consistent code formatting. diff --git a/contrib/local/setup_terpd.sh b/contrib/local/setup_terpd.sh deleted file mode 100755 index 8c25e0b..0000000 --- a/contrib/local/setup_terpd.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail - -PASSWORD=${PASSWORD:-1234567890} -STAKE=${STAKE_TOKEN:-ustake} -FEE=${FEE_TOKEN:-ucosm} -CHAIN_ID=${CHAIN_ID:-testing} -MONIKER=${MONIKER:-node001} - -terpd init --chain-id "$CHAIN_ID" "$MONIKER" -# staking/governance token is hardcoded in config, change this -## OSX requires: -i. -sed -i. "s/\"stake\"/\"$STAKE\"/" "$HOME"/.terp/config/genesis.json -if ! terpd keys show validator --keyring-backend=test; then - ( - echo "$PASSWORD" - echo "$PASSWORD" - ) | terpd keys add validator --keyring-backend=test -fi -# hardcode the validator account for this instance -echo "$PASSWORD" | terpd genesis add-genesis-account validator "1000000000$STAKE,1000000000$FEE" --keyring-backend=test -# (optionally) add a few more genesis accounts -for addr in "$@"; do - echo "$addr" - terpd genesis add-genesis-account "$addr" "1000000000$STAKE,1000000000$FEE" --keyring-backend=test -done -# submit a genesis validator tx -## Workraround for https://github.com/cosmos/cosmos-sdk/issues/8251 -( - echo "$PASSWORD" - echo "$PASSWORD" - echo "$PASSWORD" -) | terpd genesis gentx validator "250000000$STAKE" --chain-id="$CHAIN_ID" --amount="250000000$STAKE" -## should be: -# (echo "$PASSWORD"; echo "$PASSWORD"; echo "$PASSWORD") | terpd gentx validator "250000000$STAKE" --chain-id="$CHAIN_ID" -terpd genesis collect-gentxs diff --git a/contrib/local/start_node.sh b/contrib/local/start_node.sh deleted file mode 100755 index 8bd2a2c..0000000 --- a/contrib/local/start_node.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -set -eu - -terpd start --rpc.laddr tcp://0.0.0.0:26657 --log_level=info --trace #remove trace flag if you don't wantg the stack trace to be printed diff --git a/contrib/prometheus/README.md b/contrib/prometheus/README.md deleted file mode 100644 index c3864e5..0000000 --- a/contrib/prometheus/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# Setup -Enable prometheus metrics in terpd: - -* Edit `$HOME/config/app.toml` -```toml -[telemetry] - -# Enabled enables the application telemetry functionality. When enabled, -# an in-memory sink is also enabled by default. Operators may also enabled -# other sinks such as Prometheus. -enabled =true -# ... - -# PrometheusRetentionTime, when positive, enables a Prometheus metrics sink. -prometheus-retention-time = 15 -``` - -`retention-time` must be >0 (see prometheus scrape config) - - -* Edit `$HOME/config/config.toml` -```toml -[instrumentation] - -# When true, Prometheus metrics are served under /metrics on -# PrometheusListenAddr. -# Check out the documentation for the list of available metrics. -prometheus = true -``` - -Test manually at: -`http://localhost:1317/metrics?format=prometheus` - -Note the `format` parameter in the request for the endpoint: - - -# Local testing -## Run Prometheus -```sh -# port 9090 is used by terpd already -docker run -it -v $(pwd)/contrib/prometheus:/prometheus -p9091:9090 prom/prometheus --config.file=/prometheus/prometheus.yaml -``` -* Open [console](http://localhost:9091) and find `wasm_`service metrics - -## Run Grafana - -```shell -docker run -it -p 3000:3000 grafana/grafana -``` -* Add Prometheus data source -`http://host.docker.internal:9091` -### Labels -* `wasm_contract_create` = nanosec \ No newline at end of file diff --git a/contrib/prometheus/prometheus.yaml b/contrib/prometheus/prometheus.yaml deleted file mode 100644 index e4c7f4d..0000000 --- a/contrib/prometheus/prometheus.yaml +++ /dev/null @@ -1,11 +0,0 @@ -global: - scrape_interval: 15s # By default, scrape targets every 15 seconds. - evaluation_interval: 15s # By default, scrape targets every 15 seconds. -rule_files: - -scrape_configs: -- job_name: terpd - - scrape_interval: 5s - static_configs: - - targets: ['host.docker.internal:26660'] \ No newline at end of file diff --git a/contrib/prototools-docker/Dockerfile b/contrib/prototools-docker/Dockerfile deleted file mode 100644 index 45cd04b..0000000 --- a/contrib/prototools-docker/Dockerfile +++ /dev/null @@ -1,51 +0,0 @@ -FROM golang:1.16.8-alpine3.13 AS build - -#ARG PROTOTOOL_VERSION=1.10.0 -ARG PROTODOC_VERSION=1.3.2 -ARG GRPC_GATEWAY_VERSION=1.16.0 -ARG REGEN_GOGOPROTO_VERSION=0.3.0 -ARG REGEN_PROTOBUF_VERSION=1.3.2-alpha.regen.4 -ARG BUF_VERSION=0.30.0 - -RUN apk --no-cache add --update curl git libc6-compat make upx - -RUN go get -d \ - github.com/gogo/protobuf/gogoproto && \ - mkdir -p /usr/include/google/protobuf/ && \ - mv /go/src/github.com/gogo/protobuf/protobuf/google/protobuf/empty.proto /usr/include/google/protobuf/ && \ - mv /go/src/github.com/gogo/protobuf/protobuf/google/protobuf/descriptor.proto /usr/include/google/protobuf/ - -RUN GO111MODULE=on go get \ - github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v${GRPC_GATEWAY_VERSION} \ - github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@v${GRPC_GATEWAY_VERSION} && \ - mv /go/bin/protoc-gen-grpc-gateway /usr/local/bin/ && \ - mv /go/bin/protoc-gen-swagger /usr/local/bin/ - -# Install regen fork of gogo proto -# To install a fix version this can only be done via this go.mod workaround -WORKDIR /work -RUN GO111MODULE=on go mod init foobar && \ - go mod edit -replace github.com/gogo/protobuf=github.com/regen-network/protobuf@v${REGEN_PROTOBUF_VERSION} && \ - go get github.com/regen-network/cosmos-proto/protoc-gen-gocosmos@v${REGEN_GOGOPROTO_VERSION} && \ - mv /go/bin/protoc-gen-gocosmos* /usr/local/bin/ - -RUN GO111MODULE=on go get \ - github.com/pseudomuto/protoc-gen-doc/cmd/protoc-gen-doc@v${PROTODOC_VERSION} && \ - mv /go/bin/protoc-gen-doc /usr/local/bin/ - -RUN GO111MODULE=on go get \ - github.com/bufbuild/buf/cmd/buf@v${BUF_VERSION} && \ - mv /go/bin/buf /usr/local/bin/ - -RUN upx --lzma /usr/local/bin/* - -FROM golang:1.19-alpine -ENV LD_LIBRARY_PATH=/lib64:/lib - -WORKDIR /work -RUN apk --no-cache add --update curl git libc6-compat make -RUN apk --no-cache add --update ca-certificates libc6-compat protoc - -COPY --from=build /usr/local/bin /usr/local/bin -COPY --from=build /usr/include /usr/include -RUN chmod -R 755 /usr/include diff --git a/contrib/prototools-docker/README.md b/contrib/prototools-docker/README.md deleted file mode 100644 index 600c702..0000000 --- a/contrib/prototools-docker/README.md +++ /dev/null @@ -1,21 +0,0 @@ -Prototool Docker Helper -======================= -Docker container for all the protobuf generation... - -Based on the work by @pseudomuto [prototool-docker](https://github.com/charithe/prototool-docker) project: - -Installs generators and tools from: - -* https://github.com/bufbuild/buf -* https://github.com/grpc-ecosystem -* https://github.com/regen-network/cosmos-proto -* https://github.com/pseudomuto/protoc-gen-doc - -### Build -```shell script -docker build -t cosmwasm/prototools-docker -f ./contrib/prototools-docker/Dockerfile . -``` - -```shell script -docker run -it -v $(go list -f "{{ .Dir }}" -m github.com/cosmos/cosmos-sdk):/workspace/cosmos_sdk_dir -v $(pwd):/workspace --workdir /workspace --env COSMOS_SDK_DIR=/cosmos_sdk_dir cosmwasm/prototool-docker sh -``` diff --git a/docs/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md deleted file mode 100644 index c0261e7..0000000 --- a/docs/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hello@confio.gmbh. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/docs/CODING_GUIDELINES.md b/docs/CODING_GUIDELINES.md deleted file mode 100644 index eda2155..0000000 --- a/docs/CODING_GUIDELINES.md +++ /dev/null @@ -1,51 +0,0 @@ -# Coding Guidelines - -This document is an extension to [CONTRIBUTING](./CONTRIBUTING.md) and provides more details about the coding guidelines and requirements. - -## API & Design - -* Code must be well structured: - * packages must have a limited responsibility (different concerns can go to different packages), - * types must be easy to compose, - * think about maintainbility and testability. -* "Depend upon abstractions, [not] concretions". -* Try to limit the number of methods you are exposing. It's easier to expose something later than to hide it. -* Follow agreed-upon design patterns and naming conventions. -* publicly-exposed functions are named logically, have forward-thinking arguments and return types. -* Avoid global variables and global configurators. -* Favor composable and extensible designs. -* Minimize code duplication. -* Limit third-party dependencies. - -Performance: - -* Avoid unnecessary operations or memory allocations. - -Security: - -* Pay proper attention to exploits involving: - * gas usage - * transaction verification and signatures - * malleability - * code must be always deterministic -* Thread safety. If some functionality is not thread-safe, or uses something that is not thread-safe, then clearly indicate the risk on each level. - -## Best practices - -* Use [goimports](https://pkg.go.dev/golang.org/x/tools/cmd/goimports) as your code formatter. - -* Always wrap returned errors. - * Doing `if err != nil { return err }` does not include each callers' context. Pushing errors up the stack without context makes it harder to test and debug. Additionally, a short context description makes it easier for the reader to understand the code. Example: - - ```go - if !coins.IsZero() { - if err := k.bank.TransferCoins(ctx, caller, contractAddress, coins); err != nil { - return nil, err - } - } - ``` - - * It would be an improvement to return `return nil, sdkerror.Wrap(err, "lock contract coins")` - * Please notice that fmt.Errorf is not used, because the error handling predates fmt.Errorf and errors.Is - -* Limit the use of aliases, when not used during the refactoring process. \ No newline at end of file diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md deleted file mode 100644 index 05cb53b..0000000 --- a/docs/CONTRIBUTING.md +++ /dev/null @@ -1,110 +0,0 @@ -# Contributing - -Thank you for considering making contributions to Wasmd! - -Contributing to this repo can mean many things, such as participating in -discussion or proposing code changes. To ensure a smooth workflow for all -contributors, the general procedure for contributing has been established: - -1. Start by browsing [new issues](https://github.com/terpnetwork/terp-core/issues). - * Looking for a good place to start contributing? How about checking out some [good first issues](https://github.com/terpnetwork/terp-core/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) or [bugs](https://github.com/terpnetwork/terp-core/issues?q=is%3Aopen+is%3Aissue+label%3Abug)? -2. Determine whether a GitHub issue or discussion is more appropriate for your needs: - 1. If the issue you want addressed is a specific proposal or a bug, then open a [new issue](https://github.com/terpnetwork/terp-core/issues/new). - 2. Review existing [issues](https://github.com/terpnetwork/terp-core/issues) to find an issue you'd like to help with. -3. Participate in thoughtful discussion on that issue. -4. If you would like to contribute: - 1. Ensure that the proposal has been accepted. - 2. Ensure that nobody else has already begun working on this issue. If they have, - make sure to contact them to collaborate. - 3. If nobody has been assigned for the issue and you would like to work on it, - make a comment on the issue to inform the community of your intentions - to begin work. -5. To submit your work as a contribution to the repository follow standard GitHub best practices. See [pull request guideline](#pull-requests) below. - -**Note:** For very small or blatantly obvious problems such as typos, you are -not required to an open issue to submit a PR, but be aware that for more complex -problems/features, if a PR is opened before an adequate design discussion has -taken place in a GitHub issue, that PR runs a high likelihood of being rejected. - -## Development Procedure - -* The latest state of development is on `main`. -* `main` must never fail `make lint test test-race`. -* No `--force` onto `main` (except when reverting a broken commit, which should seldom happen). -* Create a branch to start work: - * Fork the repo (core developers must create a branch directly in the Wasmd repo), - branch from the HEAD of `main`, make some commits, and submit a PR to `main`. - * For core developers working within the `wasmd` repo, follow branch name conventions to ensure a clear - ownership of branches: `{issue#}-branch-name`. - * See [Branching Model](#branching-model-and-release) for more details. -* Be sure to run `make format` before every commit. The easiest way - to do this is have your editor run it for you upon saving a file (most of the editors - will do it anyway using a pre-configured setup of the programming language mode). -* Follow the [CODING GUIDELINES](CODING_GUIDELINES.md), which defines criteria for designing and coding a software. - -Code is merged into main through pull request procedure. - -### Testing - -Tests can be executed by running `make test` at the top level of the wasmd repository. - -### Pull Requests - -Before submitting a pull request: - -* merge the latest main `git merge origin/main`, -* run `make lint test` to ensure that all checks and tests pass. - -Then: - -1. If you have something to show, **start with a `Draft` PR**. It's good to have early validation of your work and we highly recommend this practice. A Draft PR also indicates to the community that the work is in progress. - Draft PRs also helps the core team provide early feedback and ensure the work is in the right direction. -2. When the code is complete, change your PR from `Draft` to `Ready for Review`. -3. Be sure to include a relevant changelog entry in the `Unreleased` section of `CHANGELOG.md` (see file for log format). The entry should be on top of all others changes in the section. - -PRs name should start upper case. -Additionally, each PR should only address a single issue. - -NOTE: when merging, GitHub will squash commits and rebase on top of the main. - -## Protobuf - -We use [Protocol Buffers](https://developers.google.com/protocol-buffers) along with [gogoproto](https://github.com/cosmos/gogoproto) to generate code for use in Wasmd. - -For deterministic behavior around Protobuf tooling, everything is containerized using Docker. Make sure to have Docker installed on your machine, or head to [Docker's website](https://docs.docker.com/get-docker/) to install it. - -For formatting code in `.proto` files, you can run `make proto-format` command. - -For linting we use [buf](https://buf.build/). You can use the commands `make proto-lint` to lint your proto files. - -To generate the protobuf stubs, you can run `make proto-gen`. - -We also added the `make proto-all` command to run all the above commands sequentially. - -In order for imports to properly compile in your IDE, you may need to manually set your protobuf path in your IDE's workspace settings/config. - -For example, in vscode your `.vscode/settings.json` should look like: - -```json -{ - "protoc": { - "options": [ - "--proto_path=${workspaceRoot}/proto", - ] - } -} -``` - -## Branching Model and Release - -User-facing repos should adhere to the trunk based development branching model: https://trunkbaseddevelopment.com. User branches should start with a user name, example: `{moniker}/{issue#}-branch-name`. - -Wasmd utilizes [semantic versioning](https://semver.org/). - -### PR Targeting - -Ensure that you base and target your PR on the `main` branch. - -All feature additions and all bug fixes must be targeted against `main`. Exception is for bug fixes which are only related to a released version. In that case, the related bug fix PRs must target against the release branch. - -If needed, we backport a commit from `main` to a release branch (excluding consensus breaking feature, API breaking and similar). \ No newline at end of file diff --git a/docs/EVENTS.md b/docs/EVENTS.md deleted file mode 100644 index 2407b3b..0000000 --- a/docs/EVENTS.md +++ /dev/null @@ -1,420 +0,0 @@ -# Event System - -## Usage in the SDK - -Events are an essential part of the Cosmos SDK. They are similar to "logs" in Ethereum and allow a blockchain -app to attach key-value pairs to a transaction that can later be used to search for it or extract some information -in human readable form. Events are not written to the application state, nor do they form part of the AppHash, -but mainly intended for client use (and become an essential API for any reactive app or app that searches for txs). - -In contrast, transactions also have a binary "data" field that is part of the AppHash (provable with light client proofs, -part of consensus). This data is not searchable, but given a tx hash, you can be guaranteed what the data returned is. -This is often empty, but sometimes custom protobuf formats to return essential information from an execution. - -Every message in the SDK may add events to the EventManager and these are then added to the final ABCI result that is returned -to Tendermint. Events are exposed in 3 different ways over the Tendermint API (which is the only way a client can query). -First of all is the `events` field on the transaction result (when you query a transaction by hash, you can see all event emitted -by it). Secondly is the `log` field on the same transaction result. And third is the query interface to search or subscribe for -transactions. - -The `log` field actually has the best data. It contains an array of array of events. The first array is one entry per incoming message. -Transactions in the Cosmos SDK may consist of multiple messages that are executed atomically. Maybe we send tokens, then issue a swap -on a DEX. Each action would return it's own list of Events and in the logs, these are separated. For each message, it maintains a list -of Events, exactly in the order returned by the application. This is JSON encoded and can be parsed by a client. In fact this is -how [CosmJS](https://github.com/cosmos/cosmjs) gets the events it shows to the client. - -In Tendermint 0.35, the `events` field will be one flattened list of events over all messages. Just as if we concatenated all -the per-message arrays contained in the `log` field. This fix was made as -[part of an event system refactoring](https://github.com/cometbft/cometbft/pull/6634). This refactoring is also giving us -[pluggable event indexing engines](https://github.com/cometbft/cometbft/pull/6411), so we can use eg. PostgreSQL to -store and query the events with more powerful indexes. - -However, currently (until Tendermint 0.34 used in Cosmos SDK 0.40-0.43), all events of one transaction are "flat-mapped" on type. -Meaning all events with type `wasm` get merged into one. This makes the API not very useful to understanding more complex events -currently. There are also a number of limitations of the power of queries in the search interface. - -Given the state of affairs, and given that we seek to provide a stable API for contracts looking into the future, we consider the -`log` output and the Tendermint 0.35 event handling to be the standard that clients should adhere to. And we will expose a similar -API to the smart contracts internally (all events from the message appended, unmerged). -### Data Format - -The event has a string type, and a list of attributes. Each of them being a key value pair. All of these maintain a -consistent order (and avoid dictionaries/hashes). Here is a simple Event in JSON: - -```json -{ - "type": "wasm", - "attributes": [ - {"key": "_contract_address", "value": "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6"}, - {"key": "transfered", "value": "777000"} - ] -} -``` - -And here is a sample log output for a transaction with one message, which emitted 2 events: - -```json -[ - [ - { - "type": "message", - "attributes": [ - {"key": "module", "value": "bank"}, - {"key": "action", "value": "send"} - ] - }, - { - "type": "transfer", - "attributes": [ - {"key": "recipient", "value": "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6"}, - {"key": "amount", "value": "777000uatom"} - ] - } - ] -] -``` - -### Default Events in the SDK - -There are two places events that are emitted in every transaction regardless of the module which is executed. -[The first is `{"type": "message"}`](https://github.com/cosmos/cosmos-sdk/blob/6888de1d86026c25197c1227dae3d7da4d41a441/baseapp/baseapp.go#L746-L748) -defining an `action` attribute. This is emitted for each top-level (user-signed) message, but the action names have changed between -0.42 and 0.43. - -The other place is in the [signature verification AnteHandler](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/auth/ante/sigverify.go#L103-L120), where it emits information on the account sequences and signatures on the transaction. - -These are all handled in BaseApp and the middleware *before* any module is called and thus not exposed to CosmWasm contracts at all. - -### Standard Events in the SDK - -The events that will actually make it to the contracts are the events that are emitted by the other modules / keepers. Let's look -at some good examples of what they look like: - -The most basic one is `bank`, which emits two events on every send, a [custom "transfer" event](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/bank/keeper/send.go#L142-L147) as well as "sender" information under the [standard "message" type](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/bank/keeper/send.go#L148-L151). Replacing variables with string literals, they look like this: - -```go -sdk.NewEvent( - "transfer" - sdk.NewAttribute("recipient", toAddr.String()), - sdk.NewAttribute("sender", fromAddr.String()), - sdk.NewAttribute("amount", amt.String()), // eg 12456uatom -), -sdk.NewEvent( - "message", - sdk.NewAttribute("sender", fromAddr.String()), -), -``` - -The delegation module seems a bit more refined, emitting a generic "message" type event in [`msg_server.go`](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/distribution/keeper/msg_server.go#L42-L46) including the module name, **before** -emitting some custom event types closer to the actual code logic in -[`keeper.go`](https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/distribution/keeper/keeper.go#L74-L77). - -This looks something like: - -```go -sdk.NewEvent( - "message", - sdk.NewAttribute("module", "distribution"), - sdk.NewAttribute("sender", msg.DelegatorAddress), -), -sdk.NewEvent( - "set_withdraw_address", - sdk.NewAttribute("withdraw_address", withdrawAddr.String()), -), -``` - -## Usage in wasmd - -In `x/wasm` we also use Events system. On one hand, the Go implementation of `x/wasm` emits standard events for each -message it processes, using the `distribution` module as an example. Furthermore, it allows contracts to -emit custom events based on their execution state, so they can for example say "dex swap, BTC-ATOM, in 0.23, out 512" -which require internal knowledge of the contract and is very useful for custom dApp UIs. - -`x/wasm` is also a consumer of events, since when a smart contract executes a SubMsg and processes the reply, it receives -not only the `data` response from the message execution, but also the list of events. This makes it even more important for -us to document a standard event processing format. - -### Standard Events in x/wasm - -Following the model of `distribution`, we will split the emitted events into two parts. All calls to the message server, will receive -the following event: - -```go -sdk.NewEvent( - "message", - sdk.NewAttribute("module", "wasm"), - // Note: this was "signer" before 0.18 - sdk.NewAttribute("sender", msg.Sender), -), -``` - -No further information will be added to the generic "message" type, but rather be contained in a more context-specific event type. -Here are some examples: - -```go -// Store Code -sdk.NewEvent( - "store_code", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", codeID)), - // features required by the contract (new in 0.18) - // see https://github.com/CosmWasm/wasmd/issues/574 - sdk.NewAttribute("feature", "stargate"), - sdk.NewAttribute("feature", "staking"), -) - -// Instantiate Contract -sdk.NewEvent( - "instantiate", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Execute Contract -sdk.NewEvent( - "execute", - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Migrate Contract -sdk.NewEvent( - "migrate", - // Note: this is the new code id that is being migrated to - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Set new admin -sdk.NewEvent( - "update_admin", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("admin", msg.NewAdmin), -) - -// Clear admin -sdk.NewEvent( - "clear_admin", - sdk.NewAttribute("_contract_address", contractAddr.String()), -) - -// Pin Code -sdk.NewEvent( - "pin_code", - sdk.NewAttribute("code_id", strconv.FormatUint(msg.CodeID, 10)), -) - -// Unpin Code -sdk.NewEvent( - "unpin_code", - sdk.NewAttribute("code_id", strconv.FormatUint(msg.CodeID, 10)), -) - -// Emitted when processing a submessage reply -sdk.NewEvent( - "reply", - sdk.NewAttribute("_contract_address", contractAddr.String()), - // If the submessage was successful, and reply is processing the success case - sdk.NewAttribute("mode", "handle_success"), - // If the submessage returned an error that was "caught" by the reply block - sdk.NewAttribute("mode", "handle_failure"), -) - -// Emitted when handling sudo -sdk.NewEvent( - "sudo", - sdk.NewAttribute("_contract_address", contractAddr.String()), -) -``` - -Note that every event that affects a contract (not store code, pin or unpin) will return the contract_address as -`_contract_address`. The events that are related to a particular wasm code (store code, instantiate, pin, unpin, and migrate) -will emit that as `code_id`. All attributes prefixed with `_` are reserved and may not be emitted by a smart contract, -so we use the underscore prefix consistently with attributes that may be injected into custom events. - -### Emitted Custom Events from a Contract - -When a CosmWasm contract returns a `Response` from one of the calls, it may return a list of attributes as well as a list -of events (in addition to data and a list of messages to dispatch). These are then processed in `x/wasm` to create events that -are emitted to the blockchain. - -If the response contains a non-empty list of `attributes`, `x/wasm` will emit a `wasm` type event. This event will -always be tagged with `_contract_address` by the Go module, so this is trust-worthy. The contract itself cannot overwrite -this field. Beyond this, the `attributes` returned by the contract, these are appended to the same event. - -A contact may also return custom `events`. These are multiple events, each with their own type as well as attributes. -When they are received, `x/wasm` prepends `wasm-` to the event type returned by the contact to avoid them trying to fake -an eg. `transfer` event from the bank module. The output here may look like: - -```go -sdk.NewEvent( - "wasm-promote" - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("batch_id", "6"), - sdk.NewAttribute("address", "cosmos1234567"), - sdk.NewAttribute("address", "cosmos1765432"), -), -sdk.NewEvent( - "wasm-promote" - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("batch_id", "7"), - sdk.NewAttribute("address", "cosmos19875632"), -) -``` - -Note that these custom events also have the `_contract_address` attribute automatically injected for easier attribution in the clients. -The multiple event API was designed to allow the contract to make logical groupings that are persisted in the event system, -more than flattening them all into one event like: - -```go -sdk.NewEvent( - "wasm" - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("action", "promote"), - sdk.NewAttribute("batch_id", "6"), - sdk.NewAttribute("address", "cosmos1234567"), - sdk.NewAttribute("address", "cosmos1765432"), - sdk.NewAttribute("batch_id", "7"), - sdk.NewAttribute("address", "cosmos19875632"), -) -``` - -If the Response contains neither `event` nor `attributes`, not `wasm*` events will be emitted, just the standard `message` -type as well as the action-dependent event (like `execute` or `migrate`). This is a significant change from pre-0.18 versions -where one could count on the `wasm` event to always be emitted. Now it is recommended to search for `execute._contract_address="foo"` -to find all transactions related to the contract. - -### Validation Rules - -While the `wasm` and `wasm-*` namespacing does sandbox the smart contract events and limits malicious activity they could -undertake, we also perform a number of further validation checks on the contracts: - -* No attribute key may start with `_`. This is currently used for `_contract_address` and is reserved for a - namespace for injecting more *trusted* attributes from the `x/wasm` module as opposed to the contract itself -* Event types are trimmed of whitespace, and must have at least two characters prior to prepending `wasm-`. If the contract returns - " hello\n", the event type will look like `wasm-hello`. If it emits " a ", this will be rejected with an error (aborting execution!) -* Attribute keys and values (both in `attributes` and under `events`) are trimmed of leading/trailing whitespace. If they are empty after - trimming, they are rejected as above (aborting the execution). Otherwise, they are passed verbatim. - -## Event Details for wasmd - -Beyond the basic Event system and emitted events, we must handle more advanced cases in `x/wasm` -and thus add some more logic to the event processing. Remember that CosmWasm contracts dispatch other -messages themselves, so far from the flattened event structure, or even a list of list (separated -by message index in the tx), we actually have a tree of messages, each with their own events. And we must -flatten that in a meaningful way to feed it into the event system. - -Furthermore, with the sub-message reply handlers, we end up with eg. "Contract A execute", "Contract B execute", -"Contract A reply". If we return all events by all of these, we may end up with many repeated event types and -a confusing results. However, we may use the standard "message" events to separate the sub-messages as it marks -where the next one starts. With careful analysis of the "sender" field on these "message" markers, we may be able -to reconstruct much of the tree execution path. We should ensure all this information is exposed in the most -consistent way possible. - -### Combining Events from Sub-Messages - -Each time a contract is executed, it not only returns the `message` event from its call, the `execute` event for the -contact and the `wasm` event with any custom fields from the contract itself. It will also return the same set of information -for all messages that it returned, which were later dispatched. The event system was really designed for one main -action emitting events, so we define a structure to flatten this event tree: - -* We only emit one event of type `message`. This is the top-level call, just like the standard Go modules. For all - dispatched submessages, we filter out this event type. -* All events are returned in execution order as [defined by CosmWasm docs](https://github.com/CosmWasm/cosmwasm/blob/main/SEMANTICS.md#dispatching-messages) -* `x/wasm` keeper emits a custom event for each call to a contract entry point. Not just `execute`, `instantiate`, - and `migrate`, but also `reply`, `sudo` and all ibc entry points. -* This means all `wasm*` events are preceeded by the cosmwasm entry point that returned them. - -To make this more clear, I will provide an example of executing a contract, which returns two messages, one to instantiate a new -contract and the other to set the withdrawl address, while also using `ReplyOnSuccess` for the instantiation (to get the -address). It will emit a series of events that looks something like this: - -```go -/// original execution (top-level message is the only one that gets the message tag) -sdk.NewEvent( - "message", - sdk.NewAttribute("module", "wasm"), - sdk.NewAttribute("sender", msg.Sender), -), - -// top-level exection call -sdk.NewEvent( - "execute", - sdk.NewAttribute("_contract_address", contractAddr.String()), -), -sdk.NewEvent( - "wasm", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("custom", "from contract"), -), - -// instantiating contract (first dipatched message) -sdk.NewEvent( - "instantiate", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", newContract.String()), -) -// didn't emit any attributes, but one event -sdk.NewEvent( - "wasm-custom", - sdk.NewAttribute("_contract_address", newContract.String()), - sdk.NewAttribute("foobar", "baz"), -), - -// handling the reply (this doesn't emit a message event as it never goes through the message server) -sdk.NewEvent( - "reply", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("mode", "handle_success"), -), -sdk.NewEvent( - "wasm", - sdk.NewAttribute("_contract_address", contractAddr.String()), - sdk.NewAttribute("custom", "from contract"), -), - -// calling the distribution module (second dispatched message) -sdk.NewEvent( - "set_withdraw_address", - sdk.NewAttribute("withdraw_address", withdrawAddr.String()), -), -``` - -### Exposing Events to Reply - -When the `reply` clause in a contract is called, it will receive the data returned from the message it -applies to, as well as all events from that message. In the above case, when the `reply` function was called -on `contractAddr` in response to initializing a contact, it would get the binary-encoded `initData` in the `data` -field, and the following in the `events` field: - -```go -sdk.NewEvent( - "instantiate", - sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_address", newContract.String()), -) -sdk.NewEvent( - "wasm-custom", - sdk.NewAttribute("_contract_address", newContract.String()), - sdk.NewAttribute("foobar", "baz"), -), -``` - -If the original contract execution example above was actually the result of a message returned by an eg. factory contract, -and it registered a ReplyOn clause, the `reply` function on that contract would receive the entire 11 events in the example -above, and would need to use the `message` markers to locate the segment of interest. - -## Governance Events -The governance process is handled by the cosmos-sdk `gov` module. We do not emit any events of type "message" anymore in v0.18+. -Context-specific events are emitted as described above. `Execution` and `Migration` return some contract result though that are -emitted as: -```go -sdk.NewEvent( - "gov_contract_result", - sdk.NewAttribute("result", hex.EncodeToString(data)), -) -``` - -## IBC Events - -All IBC entry points are only called by external accounts and not from contracts. They need to contain proofs of state of other blockchains and cannot be called by other contracts on the same chain. Therefore, the event emitted are not essential for cross-contract calls, and `x/wasm` does not emit custom events for these actions. - -There are well-defined events emitted by the IBC base layer and are required for the relayer functionality. If you wish to subscribe to these, you can find them [defined in the `ibc-go` codebase](https://github.com/cosmos/ibc-go/blob/main/modules/core/04-channel/keeper/events.go). diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md deleted file mode 100644 index 177af46..0000000 --- a/docs/INTEGRATION.md +++ /dev/null @@ -1,198 +0,0 @@ - - -# Integration - -If you want to use Wasm in your own app, here is how you can get this working -quickly and easily. -First start with This [article](https://medium.com/cosmwasm/cosmwasm-for-ctos-iv-native-integrations-713140bf75fc) -in the "CosmWasm for CTOs" series that gives you a high level view. -Then check to make sure you fit the pre-requisites, -then integrate the `x/wasm` module as described below, and finally, you -can add custom messages and queries to your custom Go/SDK modules, exposing -them to any chain-specific contract. - -## Prerequisites - -The pre-requisites of integrating `x/wasm` into your custom app is to be using -a compatible version of the Cosmos SDK, and to accept some limits to the -hardware it runs on. - -| wasmd | Cosmos SDK | -|:-----:|:----------:| -| 1.0.0 | v0.47.1 | -| v0.5 | v0.45.14 | -| v0.4.0 | v0.45.9 | - - -We currently only support Intel/AMD64 CPUs and OSX or Linux. For Linux, the standard build -commands work for `glibc` systems (Ubuntu, Debian, CentOS, etc). If you wish to compile -for a `muslc` based system (like alpine), you need to compile a static library wasmvm locally -and compile go with the `muslc` build tag. Or just use the [Dockerfile](./Dockerfile), -which builds a static go binary in an alpine system. - -This limit comes from the Rust dll we use to run the wasm code, which comes -from [`wasmvm`](https://github.com/CosmWasm/wasmvm). There are open issues -for adding [ARM support](https://github.com/CosmWasm/wasmvm/issues/53), and -adding [Windows support](https://github.com/CosmWasm/wasmvm/issues/28). -However, these issues are not high on the roadmap and unless you are championing -them, please count on the current limits for the near future. - -## Quick Trial - -The simplest way to try out CosmWasm is simply to run `wasmd` out of the box, -and focus on writing, uploading, and using your custom contracts. There is -plenty that can be done there, and lots to learn. - -Once you are happy with it and want to use a custom Cosmos SDK app, -you may consider simply forking `wasmd`. *I highly advise against this*. -You should try one of the methods below. - -## Integrating wasmd - -### As external module - -The simplest way to use `wasmd` is just to import `x/wasm` and wire it up -in `app.go`. You now have access to the whole module and you custom modules -running side by side. (But the CosmWasm contracts will only have access -to `bank` and `staking`... more below on [customization](#Adding-Custom-Hooks)). - -The requirement here is that you have imported the standard sdk modules -from the Cosmos SDK, and enabled them in `app.go`. If so, you can just look -at [`wasmd/app/app.go`](https://github.com/terpnetwork/terp-core/blob/master/app/app.go#) -for how to do so (just search there for lines with `wasm`). - -`wasmd` also comes with 2 custom `ante handlers`: -* `CountTXDecorator` adds the TX position in the block into the context and passes it to the contracts -* `LimitSimulationGasDecorator` prevents an "infinite gas" query - -In order to support these features you would need to add our custom -ante handlers into the `ante handler chain` as in: [`app/ante.go`](https://github.com/terpnetwork/terp-core/blob/master/app/ante.go) - -### Copied into your app - -Sometimes, however, you will need to copy `x/wasm` into your app. This should -be in limited cases, and makes upgrading more difficult, so please take the -above path if possible. This is required if you have either disabled some key -SDK modules in your app (eg. using PoA not staking and need to disable those -callbacks and feature support), or if you have copied in the core `x/*` modules -from the Cosmos SDK into your application and customized them somehow. - -In either case, your best approach is to copy the `x/wasm` module from the -latest release into your application. Your goal is to make **minimal changes** -in this module, and rather add your customizations in a separate module. -This is due to the fact that you will have to copy and customize `x/wasm` -from upstream on all future `wasmd` releases, and this should be as simple -as possible. - -If, for example, you have forked the standard SDK libs, you just want to -change the imports (from eg. `github.com/cosmos/cosmos-sdk/x/bank` to -`github.com/YOUR/APP/x/bank`), and adjust any calls if there are compiler -errors due to differing APIs (maybe you use Decimals not Ints for currencies?). - -By the end of this, you should be able to run the standard CosmWasm contracts -in your application, alongside all your custom logic. - -## Adding custom hooks - -Once you have gotten this integration working and are happy with the -flexibility it offers you, you will probably start wishing for deeper -integration with your custom SDK modules. "It sure is nice to have custom -tokens with a bonding curve from my native token, but I would love -to trade them on the exchange I wrote as a Go module. Or maybe use them -to add options to the exchange." - -At this point, you need to dig down deeper and see how you can add this -power without forking either CosmWasm or `wasmd`. - -### Calling contracts from native code - -This is perhaps the easiest part. Let's say your native exchange module -wants to call into a token that lives as a CosmWasm module. You need to -pass the `wasm.Keeper` into your `exchange.Keeper`. If you know the format -for sending messages and querying the contract (exported as json schema -from each contract), and have a way of configuring addresses of supported -token contracts, your exchange code can simply call `wasm.Keeper.Execute` -with a properly formatted message to move funds, or `wasm.Keeper.SmartQuery` -to check balances. - -If you look at the unit tests in [`x/wasm/internal/keeper`](https://github.com/terpnetwork/terp-core/tree/master/x/wasm/internal/keeper), -it should be pretty straight forward. - -### Extending the Contract Interface - -If you want to let the contracts access your native modules, the first -step is to define a set of Messages and Queries that you want to expose, -and then add them as `CosmosMsg::Custom` and `QueryRequest::Custom` -variants. You can see an example of the [bindings for Terra](https://github.com/CosmWasm/terra-contracts/tree/master/packages/bindings). - -Once you have those bindings, use them to build a -[simple contact using much of the API](https://github.com/CosmWasm/terra-contracts/tree/master/contracts/maker). -Don't worry too much about the details, this should be usable, but mainly -you will want to upload it to your chain and use for integration tests -with your native Cosmos SDK modules. Once that is solid, then add more -and more complex contracts. - -You will then likely want to add a `mocks` package so you can provide -mocks for the functionality of your native modules when unit testing -the contracts (provide static data for exchange rates when your contracts -query it). You can see an example of [mocks for Terra contracts](https://github.com/CosmWasm/terra-contracts/tree/master/packages/mocks). - -What these three steps provide is basically a chain-specific extension to the CosmWasm contract SDK. -Any CosmWasm contract can import you library (bindings and mocks) and easily get started using -your custom, chain-specific extensions just as easily as using the standard CosmWasm interfaces. -What is left is actually wiring them up in your chain so they work as desired. - -Note, in order to ensure that no one tries to run the contracts on an unsupported chain, -you will want to include a `requires_XYZ` directive in your `bindings` library, this will -mean that only blockchain apps that explicitly declare their support for the `XYZ` extensions -(please rename XYZ to your project name) will allow the contract to be uploaded, and others -get error messages upon upload, not while running a critical feature later on. -You just need to add [a line like this](https://github.com/CosmWasm/terra-contracts/blob/master/packages/bindings/src/lib.rs#L13-L16) -to your binding library to add the requirement to any contract that imports your `bindings` lib. - -### Calling into the SDK - -Before I show how this works, I want to remind you, if you have copied `x/wasm`, -please **do not make these changes to `x/wasm`**. - -We will add a new module, eg. `x/contracts`, that will contain custom -bindings between CosmWasm contracts and your native modules. There are two entry points -for you to use. The first is -[`CustomQuerier`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/query_plugins.go#L35), -which allows you to handle your custom queries. The second is -[`CustomEncoder`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/handler_plugin.go#L30) -which allows you to convert the `CosmosMsg::Custom(YourMessage)` types to `[]sdk.Msg` to be dispatched. - -Writing stubs for these is rather simple. You can look at the `reflect_test.go` file to see this in action. -In particular, here [we define a `CustomQuerier`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/reflect_test.go#L355-L385), -and here [we define a `CustomHandler`](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/reflect_test.go#L303-L353). -This code is responsible to take `json.RawMessage` from the raw bytes serialized from your custom types in rust and parse it into -Go structs. Then take these go structs and properly convert them for your custom SDK modules. - -You can look at the implementations for the `staking` module to see how to build these for non-trivial -cases, including passing in the `Keeper` via a closure. Here we -[encode staking messages](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/handler_plugin.go#L114-L192). -Note that withdraw returns 2 messages, which is an option you can use if needed to translate into native messages. -When we [handle staking queries](https://github.com/terpnetwork/terp-core/blob/v0.8.0-rc1/x/wasm/internal/keeper/query_plugins.go#L109-L172) -we take in a `Keeper in the closure` and dispatch the custom `QueryRequest` from the contract to the native `Keeper` interface, -then encodes a response. When defining the return types, note that for proper parsing in the Rust contract, you -should properly name the JSON fields and use the `omitempty` keyword if Rust expects `Option`. You must also use -`omitempty` and pointers for all fields that correspond to a Rust `enum`, so exactly one field is serialized. - -### Wiring it all together - -Once you have writen and tested these custom callbacks for your module, you need to enable it in your application. -The first step is to write an integration test with a contract compiled with your custom SDK to ensure it works properly, -then you need to configure this in `app.go`. - -For the test cases, you must -[define the supported feature set](https://github.com/CosmWasm/wasmd/blob/ade03a1d39a9b8882e9a1ce80572d39d57bb9bc3/x/wasm/internal/keeper/reflect_test.go#L52) -to include your custom name (remember `requires_XYZ` above?). Then, when creating `TestInput`, -you can [pass in your custom encoder and querier](https://github.com/CosmWasm/wasmd/blob/ade03a1d39a9b8882e9a1ce80572d39d57bb9bc3/x/wasm/internal/keeper/reflect_test.go#L52). -Run a few tests with your compiled contract, ideally exercising the majority of the interfaces to ensure that all parsing between the contract and -the SDK is implemented properly. - -Once you have tested this and are happy with the results, you can wire it up in `app.go`. -Just edit [the default `NewKeeper` constructor](https://github.com/CosmWasm/wasmd/blob/v0.8.0-rc1/app/app.go#L257-L258) -to have the proper `availableCapabilities` and pass in the `CustomEncoder` and `CustomQuerier` as the last two arguments to `NewKeeper`. -Now you can compile your chain and upload your custom contracts on it. \ No newline at end of file diff --git a/docs/ISSUE_TEMPLATES/bug_report.md b/docs/ISSUE_TEMPLATES/bug_report.md deleted file mode 100644 index bbdf677..0000000 --- a/docs/ISSUE_TEMPLATES/bug_report.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve - ---- - - - -### Prerequisites - -* [Ask questions in the RocketChat](https://chat.terp.network) -* [Look through recent posts on the forum](https://forum.scrt.network) -* [Check issues that have already been filed](https://github.com/issues?utf8=✓&q=is%3Aissue+user%3Aenigmampc) - -### Description - - - -### Steps to Reproduce - -1. -2. -3. - -**Expected behavior:** - - - -**Actual behavior:** - - - -**Reproduces how often:** - - - -### Additional Information - - \ No newline at end of file diff --git a/docs/ISSUE_TEMPLATES/features_request.md b/docs/ISSUE_TEMPLATES/features_request.md deleted file mode 100644 index 9e15a3f..0000000 --- a/docs/ISSUE_TEMPLATES/features_request.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project - ---- - - - -## Summary - - - -## Motivation - - - -## Describe alternatives you've considered - - - -## Additional context - - \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/PR_TEMPLATE.md b/docs/PULL_REQUEST_TEMPLATE/PR_TEMPLATE.md deleted file mode 100644 index 95553a0..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/PR_TEMPLATE.md +++ /dev/null @@ -1,10 +0,0 @@ -👋 Hello there! Welcome. Please follow the steps below to tell us about your contribution. - -1. Use the correct template for your contribution: - - 🐛 [Fixing a Bug](bug_fix.md) - - 📈 [Improving Performance](improve_performance.md) - - 📝 [Updating Documentation](update_docs.md) - - 💻 [Changing Functionality](change_functionality.md) -2. Replace text with the contents of the template -3. Fill in all sections of the template -4. Click "Create pull request" \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/bug_fix.md b/docs/PULL_REQUEST_TEMPLATE/bug_fix.md deleted file mode 100644 index d178815..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/bug_fix.md +++ /dev/null @@ -1,49 +0,0 @@ -### Requirements for Contributing a Bug Fix - -* Fill out the template below. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. -* The pull request must only fix an existing bug. To contribute other changes, you must use a different template. You can see all templates [here](PULL_REQUEST_TEMPLATE.md). - -### Identify the Bug - - - -### Description of the Change - - - -### Alternate Designs - - - -### Possible Drawbacks - - - -### Verification Process - - - -### Release Notes - - \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/change_functionality.md b/docs/PULL_REQUEST_TEMPLATE/change_functionality.md deleted file mode 100644 index c9d08aa..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/change_functionality.md +++ /dev/null @@ -1,44 +0,0 @@ -### Requirements for Adding, Changing, or Removing a Feature - -* Fill out the template below. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. All templates [here](PULL_REQUEST_TEMPLATE.md). -* After you create the pull request, all status checks must pass before a maintainer reviews your contribution. - -### Description of the Change - - - -### Alternate Designs - - - -### Possible Drawbacks - - - -### Verification Process - - - -### Release Notes - - \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/improve_performance.md b/docs/PULL_REQUEST_TEMPLATE/improve_performance.md deleted file mode 100644 index 136a696..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/improve_performance.md +++ /dev/null @@ -1,46 +0,0 @@ -### Requirements for Contributing a Performance Improvement - -* Fill out the template below. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. -* The pull request must only affect performance of existing functionality. To contribute other changes, you must use a different template. You can see all templates [here](PULL_REQUEST_TEMPLATE.md). - -### Description of the Change - - - -### Quantitative Performance Benefits - - - -### Possible Drawbacks - - - -### Verification Process - - - -### Applicable Issues - - - -### Release Notes - - \ No newline at end of file diff --git a/docs/PULL_REQUEST_TEMPLATE/update_docs.md b/docs/PULL_REQUEST_TEMPLATE/update_docs.md deleted file mode 100644 index 696706e..0000000 --- a/docs/PULL_REQUEST_TEMPLATE/update_docs.md +++ /dev/null @@ -1,5 +0,0 @@ -### Requirements for Contributing Documentation -* Fill out the template below. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. -* The pull request must only contribute documentation (for example, markdown files or API docs). To contribute other changes, you must use a different template. You can see all templates [here](./PR_TEMPLATE.md). - -### Description of the Change Release Notes diff --git a/docs/SECURITY.md b/docs/SECURITY.md deleted file mode 100644 index 021b58b..0000000 --- a/docs/SECURITY.md +++ /dev/null @@ -1,13 +0,0 @@ -# Security Policy - -This repository is maintained by Confio as part of the CosmWasm stack. -Please see https://github.com/CosmWasm/advisories/blob/main/SECURITY.md -for our security policy. - -## Supported Versions - -This is alpha software, do not run on a production system. Notably, we currently provide no migration path not even "dump state and restart" to move to future versions. - -We will have a stable v0.x version before the final v1.0.0 version with the same API as the v1.0 version in order to run last testnets and manual testing on it. We have not yet committed to that version number. wasmd 0.25 will support Cosmos SDK 0.44/0.45 and should be quite close to a final API, minus some minor details. - -Our v1.0.0 release plans were also delayed by upstream release cycles, and we have continued to refine APIs while we can. diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md deleted file mode 100644 index 827d7d8..0000000 --- a/docs/UPGRADING.md +++ /dev/null @@ -1,277 +0,0 @@ -# Upgrading - -With stargate, we have access to the `x/upgrade` module, which we can use to perform -inline upgrades. Please first read both the basic -[x/upgrade spec](https://github.com/cosmos/cosmos-sdk/blob/master/x/upgrade/spec/01_concepts.md) -and [go docs](https://godoc.org/github.com/cosmos/cosmos-sdk/x/upgrade#hdr-Performing_Upgrades) -for the background on the module. - -In this case, we will demo an update with no state migration. This is for cases when -there is a state-machine-breaking (but not state-breaking) bugfix or enhancement. -There are some -[open issues running some state migrations](https://github.com/cosmos/cosmos-sdk/issues/8265) -and we will wait for that to be fixed before trying those. - -The following will lead through running an upgrade on a local node, but the same process -would work on a real network (with more ops and governance coordination). - -## Setup - -We need to have two different versions of `wasmd` which depend on state-compatible -versions of the Cosmos SDK. We only focus on upgrade starting with stargate. You will -have to use the "dump state and restart" approach to move from launchpad to stargate. - -For this demo, we will show an upgrade from `v0.14.0` to musselnet branch. - -### Handler - -You will need to register a handler for the upgrade. This is specific to a particular -testnet and upgrade path, and the default `wasmd` will never have a registered handler -on master. In this case, we make a `musselnet` branch off of `v0.14.0` just -registering one handler with a given name. - -Look at [PR 351](https://github.com/CosmWasm/wasmd/pull/351/files) for an example -of a minimal handler. We do not make any state migrations, but rather use this -as a flag to coordinate all validators to stop the old version at one height, and -start the specified v2 version on the next block. - -### Prepare binaries - -Let's get the two binaries we want to test, the pre-upgrade and the post-upgrade -binaries. In this case the pre-release is already a published to docker hub and -can be downloaded simply via: - -`docker pull cosmwasm/wasmd:v0.14.0` - -(If this is not yet released, build it from the tip of master) - -The post-release is not published, so we can build it ourselves. Check out this -`wasmd` repo, and the proper `musselnet` branch: - -``` -# use musselnet-v2 tag once that exists -git checkout musselnet -docker build . -t wasmd:musselnet-v2 -``` - -Verify they are both working for you locally: - -``` -docker run cosmwasm/wasmd:v0.14.0 wasmd version -docker run wasmd:musselnet-v2 wasmd version -``` - -## Start the pre-release chain - -Follow the normal setup stage, but in this case we will want to have super short -governance voting period, 5 minutes rather than 2 days (or 2 weeks!). - -**Setup a client with private key** - -```sh -## TODO: I think we need to do this locally??? -docker volume rm -f musselnet_client - -docker run --rm -it \ - -e PASSWORD=1234567890 \ - --mount type=volume,source=musselnet_client,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/setup_wasmd.sh - -# enter "1234567890" when prompted -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - cosmwasm/wasmd:v0.14.0 wasmd keys show -a validator -# use the address returned above here -CLIENT=wasm1anavj4eyxkdljp27sedrdlt9dm26c8a7a8p44l -``` - -**Setup the blockchain node** - -```sh -docker volume rm -f musselnet - -# add your testing address here, so you can do something with the client -docker run --rm -it \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/setup_wasmd.sh $CLIENT - -# Update the voting times in the genesis file -docker run --rm -it \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 sed -ie 's/172800s/300s/' /root/.terp/config/genesis.json - -# start up the blockchain and all embedded servers as one process -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/run_wasmd.sh -``` - -## Sanity checks - -Let's use our client node to query the current state and send some tokens to a -random address: - -```sh -RCPT=wasm1pypadqklna33nv3gl063rd8z9q8nvauaalz820 - -# note --network=host so it can connect to the other docker image -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $CLIENT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $RCPT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx send validator $RCPT 500000ucosm,600000ustake --chain-id testing - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query bank balances $RCPT -``` - -## Take majority control of the chain - -In genesis we have a valiator with 250 million `ustake` bonded. We want to be easily -able to pass a proposal with our client. Let us bond 700 million `ustake` to ensure -we have > 67% of the voting power and will pass with the validator not voting. - -```sh -# get the "operator_address" (wasmvaloper...) from here -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query staking validators -VALIDATOR=...... - -# and stake here -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx staking delegate $VALIDATOR 750000000ustake \ - --from validator --chain-id testing -``` - -## Vote on the upgrade - -Now that we see the chain is running and producing blocks, and our client has -enough token to control the netwrok, let's create a governance -upgrade proposal for the new chain to move to `musselnet-v2` (this must be the -same name as we use in the handler we created above, change this to match what -you put in your handler): - -```sh -# create the proposal -# check the current height and add 100-200 or so for the upgrade time -# (the voting period is ~60 blocks) -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx gov submit-proposal software-upgrade musselnet-v2 \ - --upgrade-height=500 --deposit=10000000ustake \ - --title="Upgrade" --description="Upgrade to musselnet-v2" \ - --from validator --chain-id testing - -# make sure it looks good -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov proposal 1 - -# vote for it -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - tx gov vote 1 yes \ - --from validator --chain-id testing - -# ensure vote was counted -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov votes 1 -``` - -## Swap out binaries - -Now, we just wait about 5 minutes for the vote to pass, and ensure it is passed: - -```sh -# make sure it looks good -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - cosmwasm/wasmd:v0.14.0 wasmd \ - query gov proposal 1 -``` - -After this, we just let the chain run and open the terminal so you can see the log files. -It should keep producing blocks until it hits height 500 (or whatever you set there), -when the process will print a huge stacktrace and hang. Immediately before the stack trace, you -should see a line like this (burried under tons of tendermint logs): - -`8:50PM ERR UPGRADE "musselnet-v2" NEEDED at height: 100:` - -Kill it with Ctrl-C, and then try to restart with the pre-upgrade version and it should -immediately fail on startup, with the same error message as above. - -```sh -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - cosmwasm/wasmd:v0.14.0 /opt/run_wasmd.sh -``` - -Then, we start with the post-upgrade version and see it properly update: - -```sh -docker run --rm -it -p 26657:26657 -p 26656:26656 -p 1317:1317 \ - --mount type=volume,source=musselnet,target=/root \ - wasmd:musselnet-v2 /opt/run_wasmd.sh -``` - -On a real network, operators will have to be awake when the upgrade plan is activated -and manually perform this switch, or use some automated tooling like -[cosmosvisor](https://github.com/cosmos/cosmos-sdk/blob/master/cosmovisor/README.md). - -## Check final state - -Now that we have upgraded, we can use the new client version. Let's do a brief -sanity check to ensure our balances are proper, and our stake remains -delegated. That and continued block production should be a good sign the upgrade -was successful: - -```sh -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query bank balances $CLIENT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query bank balances $RCPT - -docker run --rm -it \ - --mount type=volume,source=musselnet_client,target=/root \ - --network=host \ - wasmd:musselnet-v2 wasmd \ - query staking delegations $CLIENT -``` diff --git a/docs/api_migration.md b/docs/api_migration.md deleted file mode 100644 index 734099e..0000000 --- a/docs/api_migration.md +++ /dev/null @@ -1,36 +0,0 @@ -# Changes to the api - -## [\#196](https://github.com/CosmWasm/wasmd/issues/196) - Move history of contract code migrations to their own prefix store - -The `ContractDetails.initMsg` used in cosmJs was moved into a new entity `ContractCodeHistoryEntry`. They contain code updates to a contract. - -### Route -This data is available via a new route `/wasm/contract/{contractAddr}/history` - -### Response -A list of ContractCodeHistoryEntries with following fields: -* `operation` can be any of `"Init", "Migrate", "Genesis"` -* `code_id` uint64 -* `msg` as raw json - -### Errors -* 404 - for an unknown contract - -### CLI -`terpd query wasm contract-history [bech32_address] to print all the code changes.` -Example: -`terpd query wasm contract-history cosmos18r5szma8hm93pvx6lwpjwyxruw27e0k5uw835c` -```json -[ - { - "operation": "Init", - "code_id": 1, - "msg": "\"init-msg\"" - }, - { - "operation": "Migrate", - "code_id": 2, - "msg": "\"migrate-msg\"" - } -] -``` diff --git a/docs/docs.go b/docs/docs.go index 92b90ac..1167d56 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -2,5 +2,5 @@ package docs import "embed" -//go:embed * +//go:embed static var Docs embed.FS diff --git a/docs/proto/proto-docs.md b/docs/proto/proto-docs.md deleted file mode 100644 index 5faaa61..0000000 --- a/docs/proto/proto-docs.md +++ /dev/null @@ -1,478 +0,0 @@ - -# Protobuf Documentation - - -## Table of Contents - -- [cosmwasm/tokenfactory/v1beta1/authority_metadata.proto](#cosmwasm/tokenfactory/v1beta1/authority_metadata.proto) - - [DenomAuthorityMetadata](#osmosis.tokenfactory.v1beta1.DenomAuthorityMetadata) - -- [cosmwasm/tokenfactory/v1beta1/params.proto](#cosmwasm/tokenfactory/v1beta1/params.proto) - - [Params](#osmosis.tokenfactory.v1beta1.Params) - -- [cosmwasm/tokenfactory/v1beta1/genesis.proto](#cosmwasm/tokenfactory/v1beta1/genesis.proto) - - [GenesisDenom](#osmosis.tokenfactory.v1beta1.GenesisDenom) - - [GenesisState](#osmosis.tokenfactory.v1beta1.GenesisState) - -- [cosmwasm/tokenfactory/v1beta1/query.proto](#cosmwasm/tokenfactory/v1beta1/query.proto) - - [QueryDenomAuthorityMetadataRequest](#osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataRequest) - - [QueryDenomAuthorityMetadataResponse](#osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataResponse) - - [QueryDenomsFromCreatorRequest](#osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorRequest) - - [QueryDenomsFromCreatorResponse](#osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorResponse) - - [QueryParamsRequest](#osmosis.tokenfactory.v1beta1.QueryParamsRequest) - - [QueryParamsResponse](#osmosis.tokenfactory.v1beta1.QueryParamsResponse) - - - [Query](#osmosis.tokenfactory.v1beta1.Query) - -- [cosmwasm/tokenfactory/v1beta1/tx.proto](#cosmwasm/tokenfactory/v1beta1/tx.proto) - - [MsgBurn](#osmosis.tokenfactory.v1beta1.MsgBurn) - - [MsgBurnResponse](#osmosis.tokenfactory.v1beta1.MsgBurnResponse) - - [MsgChangeAdmin](#osmosis.tokenfactory.v1beta1.MsgChangeAdmin) - - [MsgChangeAdminResponse](#osmosis.tokenfactory.v1beta1.MsgChangeAdminResponse) - - [MsgCreateDenom](#osmosis.tokenfactory.v1beta1.MsgCreateDenom) - - [MsgCreateDenomResponse](#osmosis.tokenfactory.v1beta1.MsgCreateDenomResponse) - - [MsgMint](#osmosis.tokenfactory.v1beta1.MsgMint) - - [MsgMintResponse](#osmosis.tokenfactory.v1beta1.MsgMintResponse) - - [MsgSetDenomMetadata](#osmosis.tokenfactory.v1beta1.MsgSetDenomMetadata) - - [MsgSetDenomMetadataResponse](#osmosis.tokenfactory.v1beta1.MsgSetDenomMetadataResponse) - - - [Msg](#osmosis.tokenfactory.v1beta1.Msg) - -- [Scalar Value Types](#scalar-value-types) - - - - -

Top

- -## cosmwasm/tokenfactory/v1beta1/authority_metadata.proto - - - - - -### DenomAuthorityMetadata -DenomAuthorityMetadata specifies metadata for addresses that have specific -capabilities over a token factory denom. Right now there is only one Admin -permission, but is planned to be extended to the future. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `admin` | [string](#string) | | Can be empty for no admin, or a valid terp address | - - - - - - - - - - - - - - - - -

Top

- -## cosmwasm/tokenfactory/v1beta1/params.proto - - - - - -### Params -Params defines the parameters for the tokenfactory module. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `denom_creation_fee` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | | - - - - - - - - - - - - - - - - -

Top

- -## cosmwasm/tokenfactory/v1beta1/genesis.proto - - - - - -### GenesisDenom -GenesisDenom defines a tokenfactory denom that is defined within genesis -state. The structure contains DenomAuthorityMetadata which defines the -denom's admin. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `denom` | [string](#string) | | | -| `authority_metadata` | [DenomAuthorityMetadata](#osmosis.tokenfactory.v1beta1.DenomAuthorityMetadata) | | | - - - - - - - - -### GenesisState -GenesisState defines the tokenfactory module's genesis state. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `params` | [Params](#osmosis.tokenfactory.v1beta1.Params) | | params defines the paramaters of the module. | -| `factory_denoms` | [GenesisDenom](#osmosis.tokenfactory.v1beta1.GenesisDenom) | repeated | | - - - - - - - - - - - - - - - - -

Top

- -## cosmwasm/tokenfactory/v1beta1/query.proto - - - - - -### QueryDenomAuthorityMetadataRequest -QueryDenomAuthorityMetadataRequest defines the request structure for the -DenomAuthorityMetadata gRPC query. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `denom` | [string](#string) | | | - - - - - - - - -### QueryDenomAuthorityMetadataResponse -QueryDenomAuthorityMetadataResponse defines the response structure for the -DenomAuthorityMetadata gRPC query. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `authority_metadata` | [DenomAuthorityMetadata](#osmosis.tokenfactory.v1beta1.DenomAuthorityMetadata) | | | - - - - - - - - -### QueryDenomsFromCreatorRequest -QueryDenomsFromCreatorRequest defines the request structure for the -DenomsFromCreator gRPC query. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `creator` | [string](#string) | | | - - - - - - - - -### QueryDenomsFromCreatorResponse -QueryDenomsFromCreatorRequest defines the response structure for the -DenomsFromCreator gRPC query. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `denoms` | [string](#string) | repeated | | - - - - - - - - -### QueryParamsRequest -QueryParamsRequest is the request type for the Query/Params RPC method. - - - - - - - - -### QueryParamsResponse -QueryParamsResponse is the response type for the Query/Params RPC method. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `params` | [Params](#osmosis.tokenfactory.v1beta1.Params) | | params defines the parameters of the module. | - - - - - - - - - - - - - - -### Query -Query defines the gRPC querier service. - -| Method Name | Request Type | Response Type | Description | HTTP Verb | Endpoint | -| ----------- | ------------ | ------------- | ------------| ------- | -------- | -| `Params` | [QueryParamsRequest](#osmosis.tokenfactory.v1beta1.QueryParamsRequest) | [QueryParamsResponse](#osmosis.tokenfactory.v1beta1.QueryParamsResponse) | Params defines a gRPC query method that returns the tokenfactory module's parameters. | GET|/osmosis/tokenfactory/v1beta1/params| -| `DenomAuthorityMetadata` | [QueryDenomAuthorityMetadataRequest](#osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataRequest) | [QueryDenomAuthorityMetadataResponse](#osmosis.tokenfactory.v1beta1.QueryDenomAuthorityMetadataResponse) | DenomAuthorityMetadata defines a gRPC query method for fetching DenomAuthorityMetadata for a particular denom. | GET|/osmosis/tokenfactory/v1beta1/denoms/{denom}/authority_metadata| -| `DenomsFromCreator` | [QueryDenomsFromCreatorRequest](#osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorRequest) | [QueryDenomsFromCreatorResponse](#osmosis.tokenfactory.v1beta1.QueryDenomsFromCreatorResponse) | DenomsFromCreator defines a gRPC query method for fetching all denominations created by a specific admin/creator. | GET|/osmosis/tokenfactory/v1beta1/denoms_from_creator/{creator}| - - - - - - -

Top

- -## cosmwasm/tokenfactory/v1beta1/tx.proto - - - - - -### MsgBurn -MsgBurn is the sdk.Msg type for allowing an admin account to burn -a token. For now, we only support burning from the sender account. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | | -| `amount` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | | | - - - - - - - - -### MsgBurnResponse -MsgBurnResponse defines the response structure for an executed -MsgBurn message. - - - - - - - - -### MsgChangeAdmin -MsgChangeAdmin is the sdk.Msg type for allowing an admin account to reassign -adminship of a denom to a new account - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | | -| `denom` | [string](#string) | | | -| `new_admin` | [string](#string) | | | - - - - - - - - -### MsgChangeAdminResponse -MsgChangeAdminResponse defines the response structure for an executed -MsgChangeAdmin message. - - - - - - - - -### MsgCreateDenom -MsgCreateDenom defines the message structure for the CreateDenom gRPC service -method. It allows an account to create a new denom. It requires a sender -address and a sub denomination. The (sender_address, sub_denomination) tuple -must be unique and cannot be re-used. - -The resulting denom created is defined as -. The resulting denom's admin is -originally set to be the creator, but this can be changed later. The token -denom does not indicate the current admin. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | | -| `subdenom` | [string](#string) | | subdenom can be up to 44 "alphanumeric" characters long. | - - - - - - - - -### MsgCreateDenomResponse -MsgCreateDenomResponse is the return value of MsgCreateDenom -It returns the full string of the newly created denom. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `new_token_denom` | [string](#string) | | | - - - - - - - - -### MsgMint -MsgMint is the sdk.Msg type for allowing an admin account to mint -more of a token. For now, we only support minting to the sender account - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | | -| `amount` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | | | - - - - - - - - -### MsgMintResponse -MsgMintResponse defines the response structure for an executed -MsgMint message. - - - - - - - - -### MsgSetDenomMetadata -MsgSetDenomMetadata is the sdk.Msg type for allowing an admin account to set -the denom's bank metadata. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | | -| `metadata` | [cosmos.bank.v1beta1.Metadata](#cosmos.bank.v1beta1.Metadata) | | | - - - - - - - - -### MsgSetDenomMetadataResponse -MsgSetDenomMetadataResponse defines the response structure for an executed -MsgSetDenomMetadata message. - - - - - - - - - - - - - - -### Msg -Msg defines the tokefactory module's gRPC message service. - -| Method Name | Request Type | Response Type | Description | HTTP Verb | Endpoint | -| ----------- | ------------ | ------------- | ------------| ------- | -------- | -| `CreateDenom` | [MsgCreateDenom](#osmosis.tokenfactory.v1beta1.MsgCreateDenom) | [MsgCreateDenomResponse](#osmosis.tokenfactory.v1beta1.MsgCreateDenomResponse) | CreateDenom Creates a denom of factory/{creator address}/{subdenom} given the denom creator address and the subdenom. Subdenoms can contain [a-zA-Z0-9./]. | | -| `Mint` | [MsgMint](#osmosis.tokenfactory.v1beta1.MsgMint) | [MsgMintResponse](#osmosis.tokenfactory.v1beta1.MsgMintResponse) | Mint is message type that represents a request to mint a new denom. | | -| `Burn` | [MsgBurn](#osmosis.tokenfactory.v1beta1.MsgBurn) | [MsgBurnResponse](#osmosis.tokenfactory.v1beta1.MsgBurnResponse) | Burn message type that represents a request to burn (i.e., destroy) a denom. | | -| `ChangeAdmin` | [MsgChangeAdmin](#osmosis.tokenfactory.v1beta1.MsgChangeAdmin) | [MsgChangeAdminResponse](#osmosis.tokenfactory.v1beta1.MsgChangeAdminResponse) | A message type that represents a request to change the administrator of the denom. | | -| `SetDenomMetadata` | [MsgSetDenomMetadata](#osmosis.tokenfactory.v1beta1.MsgSetDenomMetadata) | [MsgSetDenomMetadataResponse](#osmosis.tokenfactory.v1beta1.MsgSetDenomMetadataResponse) | A message type that represents a request to set metadata for a denomination. | | - - - - - -## Scalar Value Types - -| .proto Type | Notes | C++ | Java | Python | Go | C# | PHP | Ruby | -| ----------- | ----- | --- | ---- | ------ | -- | -- | --- | ---- | -| double | | double | double | float | float64 | double | float | Float | -| float | | float | float | float | float32 | float | float | Float | -| int32 | Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint32 instead. | int32 | int | int | int32 | int | integer | Bignum or Fixnum (as required) | -| int64 | Uses variable-length encoding. Inefficient for encoding negative numbers – if your field is likely to have negative values, use sint64 instead. | int64 | long | int/long | int64 | long | integer/string | Bignum | -| uint32 | Uses variable-length encoding. | uint32 | int | int/long | uint32 | uint | integer | Bignum or Fixnum (as required) | -| uint64 | Uses variable-length encoding. | uint64 | long | int/long | uint64 | ulong | integer/string | Bignum or Fixnum (as required) | -| sint32 | Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int32s. | int32 | int | int | int32 | int | integer | Bignum or Fixnum (as required) | -| sint64 | Uses variable-length encoding. Signed int value. These more efficiently encode negative numbers than regular int64s. | int64 | long | int/long | int64 | long | integer/string | Bignum | -| fixed32 | Always four bytes. More efficient than uint32 if values are often greater than 2^28. | uint32 | int | int | uint32 | uint | integer | Bignum or Fixnum (as required) | -| fixed64 | Always eight bytes. More efficient than uint64 if values are often greater than 2^56. | uint64 | long | int/long | uint64 | ulong | integer/string | Bignum | -| sfixed32 | Always four bytes. | int32 | int | int | int32 | int | integer | Bignum or Fixnum (as required) | -| sfixed64 | Always eight bytes. | int64 | long | int/long | int64 | long | integer/string | Bignum | -| bool | | bool | boolean | boolean | bool | bool | boolean | TrueClass/FalseClass | -| string | A string must always contain UTF-8 encoded or 7-bit ASCII text. | string | String | str/unicode | string | string | string | String (UTF-8) | -| bytes | May contain any arbitrary sequence of bytes. | string | ByteString | str | []byte | ByteString | string | String (ASCII-8BIT) | - diff --git a/docs/proto/protodoc-markdown.tmpl b/docs/proto/protodoc-markdown.tmpl deleted file mode 100644 index 2820183..0000000 --- a/docs/proto/protodoc-markdown.tmpl +++ /dev/null @@ -1,105 +0,0 @@ - -# Protobuf Documentation - - -## Table of Contents -{{range .Files}} -{{$file_name := .Name}}- [{{.Name}}](#{{.Name}}) - {{- if .Messages }} - {{range .Messages}} - [{{.LongName}}](#{{.FullName}}) - {{end}} - {{- end -}} - {{- if .Enums }} - {{range .Enums}} - [{{.LongName}}](#{{.FullName}}) - {{end}} - {{- end -}} - {{- if .Extensions }} - {{range .Extensions}} - [File-level Extensions](#{{$file_name}}-extensions) - {{end}} - {{- end -}} - {{- if .Services }} - {{range .Services}} - [{{.Name}}](#{{.FullName}}) - {{end}} - {{- end -}} -{{end}} -- [Scalar Value Types](#scalar-value-types) - -{{range .Files}} -{{$file_name := .Name}} - -

Top

- -## {{.Name}} -{{.Description}} - -{{range .Messages}} - - -### {{.LongName}} -{{.Description}} - -{{if .HasFields}} -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -{{range .Fields -}} - | `{{.Name}}` | [{{.LongType}}](#{{.FullType}}) | {{.Label}} | {{if (index .Options "deprecated"|default false)}}**Deprecated.** {{end}}{{nobr .Description}}{{if .DefaultValue}} Default: {{.DefaultValue}}{{end}} | -{{end}} -{{end}} - -{{if .HasExtensions}} -| Extension | Type | Base | Number | Description | -| --------- | ---- | ---- | ------ | ----------- | -{{range .Extensions -}} - | `{{.Name}}` | {{.LongType}} | {{.ContainingLongType}} | {{.Number}} | {{nobr .Description}}{{if .DefaultValue}} Default: {{.DefaultValue}}{{end}} | -{{end}} -{{end}} - -{{end}} - -{{range .Enums}} - - -### {{.LongName}} -{{.Description}} - -| Name | Number | Description | -| ---- | ------ | ----------- | -{{range .Values -}} - | {{.Name}} | {{.Number}} | {{nobr .Description}} | -{{end}} - -{{end}} - -{{if .HasExtensions}} - - -### File-level Extensions -| Extension | Type | Base | Number | Description | -| --------- | ---- | ---- | ------ | ----------- | -{{range .Extensions -}} - | `{{.Name}}` | {{.LongType}} | {{.ContainingLongType}} | {{.Number}} | {{nobr .Description}}{{if .DefaultValue}} Default: `{{.DefaultValue}}`{{end}} | -{{end}} -{{end}} - -{{range .Services}} - - -### {{.Name}} -{{.Description}} - -| Method Name | Request Type | Response Type | Description | HTTP Verb | Endpoint | -| ----------- | ------------ | ------------- | ------------| ------- | -------- | -{{range .Methods -}} - | `{{.Name}}` | [{{.RequestLongType}}](#{{.RequestFullType}}){{if .RequestStreaming}} stream{{end}} | [{{.ResponseLongType}}](#{{.ResponseFullType}}){{if .ResponseStreaming}} stream{{end}} | {{nobr .Description}} | {{with (index .Options "google.api.http")}}{{range .Rules}}{{.Method}}|{{.Pattern}}{{end}}{{end}}| -{{end}} -{{end}} - -{{end}} - -## Scalar Value Types - -| .proto Type | Notes | C++ | Java | Python | Go | C# | PHP | Ruby | -| ----------- | ----- | --- | ---- | ------ | -- | -- | --- | ---- | -{{range .Scalars -}} - | {{.ProtoType}} | {{.Notes}} | {{.CppType}} | {{.JavaType}} | {{.PythonType}} | {{.GoType}} | {{.CSharp}} | {{.PhpType}} | {{.RubyType}} | -{{end}} diff --git a/.gitattributes b/docs/static/openapi.yml similarity index 100% rename from .gitattributes rename to docs/static/openapi.yml diff --git a/go.mod b/go.mod index ddd2450..3f2c36e 100644 --- a/go.mod +++ b/go.mod @@ -1,58 +1,63 @@ -module github.com/terpnetwork/terp-core +module github.com/terpnetwork/terp-core/v2 go 1.19 require ( - github.com/CosmWasm/wasmvm v1.2.4 - github.com/cometbft/cometbft v0.37.1 - github.com/cometbft/cometbft-db v0.7.0 + github.com/CosmWasm/wasmd v0.41.0 + github.com/CosmWasm/wasmvm v1.3.0 + github.com/cometbft/cometbft v0.37.2 + github.com/cometbft/cometbft-db v0.8.0 github.com/cosmos/cosmos-proto v1.0.0-beta.3 - github.com/cosmos/cosmos-sdk v0.47.3 + github.com/cosmos/cosmos-sdk v0.47.4 github.com/cosmos/gogogateway v1.2.0 // indirect github.com/cosmos/gogoproto v1.4.10 - github.com/cosmos/iavl v0.20.0 - github.com/cosmos/ibc-go/v7 v7.0.1 - github.com/cosmos/ics23/go v0.9.1-0.20221207100636-b1abd8678aab // indirect - github.com/docker/distribution v2.8.2+incompatible + github.com/cosmos/iavl v0.20.0 // indirect + github.com/cosmos/ibc-go/v7 v7.2.0 + github.com/cosmos/ics23/go v0.10.0 // indirect + github.com/docker/distribution v2.8.2+incompatible // indirect github.com/dvsekhvalnov/jose2go v1.5.0 // indirect github.com/golang/protobuf v1.5.3 - github.com/google/gofuzz v1.2.0 + github.com/google/gofuzz v1.2.0 // indirect github.com/gorilla/mux v1.8.0 github.com/grpc-ecosystem/grpc-gateway v1.16.0 - github.com/pkg/errors v0.9.1 - github.com/prometheus/client_golang v1.15.0 + github.com/pkg/errors v0.9.1 // indirect + github.com/prometheus/client_golang v1.16.0 github.com/rakyll/statik v0.1.7 // indirect github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa 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 github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect - google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 - google.golang.org/grpc v1.55.0 - gopkg.in/yaml.v2 v2.4.0 + google.golang.org/genproto v0.0.0-20230706204954-ccb25ca9f130 // indirect + google.golang.org/grpc v1.56.2 + gopkg.in/yaml.v2 v2.4.0 // indirect ) require ( cosmossdk.io/api v0.3.1 - cosmossdk.io/core v0.6.1 - cosmossdk.io/errors v1.0.0-beta.7 + cosmossdk.io/errors v1.0.0 + cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca cosmossdk.io/math v1.0.1 cosmossdk.io/tools/rosetta v0.2.1 + github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7 v7.0.0 + github.com/cosmos/ibc-apps/modules/async-icq/v7 v7.0.0 + github.com/cosmos/ibc-apps/modules/ibc-hooks/v7 v7.0.0-20230906222317-d88d4028e5c9 github.com/spf13/viper v1.16.0 + google.golang.org/genproto/googleapis/api v0.0.0-20230629202037-9506855d4529 ) require ( - cloud.google.com/go v0.110.0 // indirect - cloud.google.com/go/compute v1.19.0 // indirect + cloud.google.com/go v0.110.4 // indirect + cloud.google.com/go/compute v1.20.1 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect - cloud.google.com/go/iam v0.13.0 // indirect - cloud.google.com/go/storage v1.29.0 // indirect + cloud.google.com/go/iam v1.1.0 // indirect + cloud.google.com/go/storage v1.30.1 // indirect + cosmossdk.io/core v0.6.1 // indirect cosmossdk.io/depinject v1.0.0-alpha.3 // indirect - cosmossdk.io/log v1.1.0 // 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/99designs/keyring v1.2.2 // indirect github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect github.com/armon/go-metrics v0.4.1 // indirect github.com/aws/aws-sdk-go v1.44.203 // indirect @@ -69,7 +74,7 @@ require ( github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect - github.com/cosmos/ledger-cosmos-go v0.12.1 // indirect + github.com/cosmos/ledger-cosmos-go v0.12.2 // indirect github.com/cosmos/rosetta-sdk-go v0.10.0 // indirect github.com/creachadair/taskgroup v0.4.2 // indirect github.com/danieljoos/wincred v1.1.2 // indirect @@ -95,10 +100,10 @@ require ( github.com/google/btree v1.1.2 // indirect github.com/google/go-cmp v0.5.9 // indirect github.com/google/orderedcode v0.0.1 // indirect - github.com/google/s2a-go v0.1.3 // indirect + github.com/google/s2a-go v0.1.4 // indirect github.com/google/uuid v1.3.0 // indirect github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect - github.com/googleapis/gax-go/v2 v2.8.0 // indirect + github.com/googleapis/gax-go/v2 v2.11.0 // indirect github.com/gorilla/handlers v1.5.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect @@ -114,6 +119,7 @@ require ( github.com/hashicorp/hcl v1.0.0 // indirect github.com/hdevalence/ed25519consensus v0.1.0 // indirect github.com/huandu/skiplist v1.2.0 // indirect + github.com/iancoleman/orderedmap v0.2.0 // indirect github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect @@ -121,10 +127,11 @@ require ( github.com/klauspost/compress v1.16.3 // indirect github.com/lib/pq v1.10.7 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/manifoldco/promptui v0.9.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.18 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mimoo/StrobeGo v0.0.0-20210601165009-122bf33a46e0 // indirect github.com/minio/highwayhash v1.0.2 // indirect @@ -138,7 +145,7 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect github.com/prometheus/common v0.42.0 // indirect - github.com/prometheus/procfs v0.9.0 // indirect + github.com/prometheus/procfs v0.10.1 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect github.com/rs/cors v1.8.3 // indirect github.com/rs/zerolog v1.29.1 // indirect @@ -146,7 +153,6 @@ require ( github.com/spf13/afero v1.9.5 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/subosito/gotenv v1.4.2 // indirect - github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c // indirect github.com/tendermint/go-amino v0.16.0 // indirect github.com/tidwall/btree v1.6.0 // indirect github.com/ulikunitz/xz v0.5.11 // indirect @@ -154,17 +160,18 @@ 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.9.0 // indirect + golang.org/x/crypto v0.11.0 // indirect golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc // indirect - golang.org/x/net v0.10.0 // indirect - golang.org/x/oauth2 v0.7.0 // indirect - golang.org/x/sys v0.8.0 // indirect - golang.org/x/term v0.8.0 // indirect - golang.org/x/text v0.9.0 // indirect + golang.org/x/net v0.12.0 // indirect + golang.org/x/oauth2 v0.8.0 // indirect + golang.org/x/sys v0.10.0 // indirect + golang.org/x/term v0.10.0 // indirect + golang.org/x/text v0.11.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect - google.golang.org/api v0.122.0 // indirect + google.golang.org/api v0.126.0 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/protobuf v1.30.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect + google.golang.org/protobuf v1.31.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect nhooyr.io/websocket v1.8.6 // indirect diff --git a/go.sum b/go.sum index 46920d3..1cfec24 100644 --- a/go.sum +++ b/go.sum @@ -32,8 +32,8 @@ cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w9 cloud.google.com/go v0.102.0/go.mod h1:oWcCzKlqJ5zgHQt9YsaeTY9KzIvjyy0ArmiBUgpQ+nc= cloud.google.com/go v0.102.1/go.mod h1:XZ77E9qnTEnrgEOvr4xzfdX5TRo7fB4T2F4O6+34hIU= cloud.google.com/go v0.104.0/go.mod h1:OO6xxXdJyvuJPcEPBLN9BJPD+jep5G1+2U5B5gkRYtA= -cloud.google.com/go v0.110.0 h1:Zc8gqp3+a9/Eyph2KDmcGaPtbKRIoqq4YTlL4NMD0Ys= -cloud.google.com/go v0.110.0/go.mod h1:SJnCLqQ0FCFGSZMUNUf84MV3Aia54kn7pi8st7tMzaY= +cloud.google.com/go v0.110.4 h1:1JYyxKMN9hd5dR2MYTPWkGUgcoxVVhg0LKNKEo0qvmk= +cloud.google.com/go v0.110.4/go.mod h1:+EYjdK8e5RME/VY/qLCAtuyALQ9q67dvuum8i+H5xsI= cloud.google.com/go/aiplatform v1.22.0/go.mod h1:ig5Nct50bZlzV6NvKaTwmplLLddFx0YReh9WfTO5jKw= cloud.google.com/go/aiplatform v1.24.0/go.mod h1:67UUvRBKG6GTayHKV8DBv2RtR1t93YRu5B1P3x99mYY= cloud.google.com/go/analytics v0.11.0/go.mod h1:DjEWCu41bVbYcKyvlws9Er60YE4a//bK6mnhWvQeFNI= @@ -70,8 +70,8 @@ cloud.google.com/go/compute v1.6.0/go.mod h1:T29tfhtVbq1wvAPo0E3+7vhgmkOYeXjhFvz cloud.google.com/go/compute v1.6.1/go.mod h1:g85FgpzFvNULZ+S8AYq87axRKuf2Kh7deLqV/jJ3thU= cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQHHZWZxy9U= cloud.google.com/go/compute v1.10.0/go.mod h1:ER5CLbMxl90o2jtNbGSbtfOpQKR0t15FOtRsugnLrlU= -cloud.google.com/go/compute v1.19.0 h1:+9zda3WGgW1ZSTlVppLCYFIr48Pa35q1uG2N1itbCEQ= -cloud.google.com/go/compute v1.19.0/go.mod h1:rikpw2y+UMidAe9tISo04EHNOIf42RLYF/q8Bs93scU= +cloud.google.com/go/compute v1.20.1 h1:6aKEtlUiwEpJzM001l0yFkpXmUVXaN8W+fbkb2AZNbg= +cloud.google.com/go/compute v1.20.1/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM= cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= cloud.google.com/go/containeranalysis v0.5.1/go.mod h1:1D92jd8gRR/c0fGMlymRgxWD3Qw9C1ff6/T7mLgVL8I= @@ -111,13 +111,12 @@ cloud.google.com/go/gkehub v0.10.0/go.mod h1:UIPwxI0DsrpsVoWpLB0stwKCP+WFVG9+y97 cloud.google.com/go/grafeas v0.2.0/go.mod h1:KhxgtF2hb0P191HlY5besjYm6MqTSTj3LSI+M+ByZHc= cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp4bnY= cloud.google.com/go/iam v0.5.0/go.mod h1:wPU9Vt0P4UmCux7mqtRu6jcpPAb74cP1fh50J3QpkUc= -cloud.google.com/go/iam v0.13.0 h1:+CmB+K0J/33d0zSQ9SlFWUeCCEn5XJA0ZMZ3pHE9u8k= -cloud.google.com/go/iam v0.13.0/go.mod h1:ljOg+rcNfzZ5d6f1nAUJ8ZIxOaZUVoS14bKCtaLZ/D0= +cloud.google.com/go/iam v1.1.0 h1:67gSqaPukx7O8WLLHMa0PNs3EBGd2eE4d+psbO/CO94= +cloud.google.com/go/iam v1.1.0/go.mod h1:nxdHjaKfCr7fNYx/HJMM8LgiMugmveWlkatear5gVyk= cloud.google.com/go/language v1.4.0/go.mod h1:F9dRpNFQmJbkaop6g0JhSBXCNlO90e1KWx5iDdxbWic= cloud.google.com/go/language v1.6.0/go.mod h1:6dJ8t3B+lUYfStgls25GusK04NLh3eDLQnWM3mdEbhI= cloud.google.com/go/lifesciences v0.5.0/go.mod h1:3oIKy8ycWGPUyZDR/8RNnTOYevhaMLqh5vLUXs9zvT8= cloud.google.com/go/lifesciences v0.6.0/go.mod h1:ddj6tSX/7BOnhxCSd3ZcETvtNr8NZ6t/iPhY2Tyfu08= -cloud.google.com/go/longrunning v0.4.1 h1:v+yFJOfKC3yZdY6ZUI933pIYdhyhV8S3NpWrXWmg7jM= cloud.google.com/go/mediatranslation v0.5.0/go.mod h1:jGPUhGTybqsPQn91pNXw0xVHfuJ3leR1wj37oU3y1f4= cloud.google.com/go/mediatranslation v0.6.0/go.mod h1:hHdBCTYNigsBxshbznuIMFNe5QXEowAuNmmC7h8pu5w= cloud.google.com/go/memcache v1.4.0/go.mod h1:rTOfiGZtJX1AaFUrOgsMHX5kAzaTQ8azHiuDoTPzNsE= @@ -175,8 +174,8 @@ cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3f cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq6kuBTW58Y= cloud.google.com/go/storage v1.23.0/go.mod h1:vOEEDNFnciUMhBeT6hsJIn3ieU5cFRmzeLgDvXzfIXc= cloud.google.com/go/storage v1.27.0/go.mod h1:x9DOL8TK/ygDUMieqwfhdpQryTeEkhGKMi80i/iqR2s= -cloud.google.com/go/storage v1.29.0 h1:6weCgzRvMg7lzuUurI4697AqIRPU1SvzHhynwpW31jI= -cloud.google.com/go/storage v1.29.0/go.mod h1:4puEjyTKnku6gfKoTfNOU/W+a9JyuVNxjpS5GBrB8h4= +cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM= +cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E= cloud.google.com/go/talent v1.1.0/go.mod h1:Vl4pt9jiHKvOgF9KoZo6Kob9oV4lwd/ZD5Cto54zDRw= cloud.google.com/go/talent v1.2.0/go.mod h1:MoNF9bhFQbiJ6eFD3uSsg0uBALw4n4gaCaEjBw9zo8g= cloud.google.com/go/videointelligence v1.6.0/go.mod h1:w0DIDlVRKtwPCn/C4iwZIJdvC69yInhW0cfi+p546uU= @@ -194,10 +193,10 @@ cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= -cosmossdk.io/errors v1.0.0-beta.7 h1:gypHW76pTQGVnHKo6QBkb4yFOJjC+sUGRc5Al3Odj1w= -cosmossdk.io/errors v1.0.0-beta.7/go.mod h1:mz6FQMJRku4bY7aqS/Gwfcmr/ue91roMEKAmDUDpBfE= -cosmossdk.io/log v1.1.0 h1:v0ogPHYeTzPcBTcPR1A3j1hkei4pZama8kz8LKlCMv0= -cosmossdk.io/log v1.1.0/go.mod h1:6zjroETlcDs+mm62gd8Ig7mZ+N+fVOZS91V17H+M4N4= +cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= +cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= +cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= +cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= cosmossdk.io/tools/rosetta v0.2.1 h1:ddOMatOH+pbxWbrGJKRAawdBkPYLfKXutK9IETnjYxw= @@ -212,8 +211,10 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 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= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d/go.mod h1:URdX5+vg25ts3aCh8H5IFZybJYKWhJHYMTnf+ULtoC4= -github.com/CosmWasm/wasmvm v1.2.4 h1:6OfeZuEcEH/9iqwrg2pkeVtDCkMoj9U6PpKtcrCyVrQ= -github.com/CosmWasm/wasmvm v1.2.4/go.mod h1:vW/E3h8j9xBQs9bCoijDuawKo9kCtxOaS8N8J7KFtkc= +github.com/CosmWasm/wasmd v0.41.0 h1:fmwxSbwb50zZDcBaayYFRLIaSFca+EFld1WOaQi49jg= +github.com/CosmWasm/wasmd v0.41.0/go.mod h1:0Sds1q2IsPaTN1gHa3BNOYcUFgtGvxH7CXEXPgoihns= +github.com/CosmWasm/wasmvm v1.3.0 h1:x12X4bKlUPS7TT9QQP45+fJo2sp30GEbiSSgb9jsec8= +github.com/CosmWasm/wasmvm v1.3.0/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= @@ -304,10 +305,10 @@ github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:z github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= github.com/coinbase/rosetta-sdk-go/types v1.0.0 h1:jpVIwLcPoOeCR6o1tU+Xv7r5bMONNbHU7MuEHboiFuA= github.com/coinbase/rosetta-sdk-go/types v1.0.0/go.mod h1:eq7W2TMRH22GTW0N0beDnN931DW0/WOI1R2sdHNHG4c= -github.com/cometbft/cometbft v0.37.1 h1:KLxkQTK2hICXYq21U2hn1W5hOVYUdQgDQ1uB+90xPIg= -github.com/cometbft/cometbft v0.37.1/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= -github.com/cometbft/cometbft-db v0.7.0 h1:uBjbrBx4QzU0zOEnU8KxoDl18dMNgDh+zZRUE0ucsbo= -github.com/cometbft/cometbft-db v0.7.0/go.mod h1:yiKJIm2WKrt6x8Cyxtq9YTEcIMPcEe4XPxhgX59Fzf0= +github.com/cometbft/cometbft v0.37.2 h1:XB0yyHGT0lwmJlFmM4+rsRnczPlHoAKFX6K8Zgc2/Jc= +github.com/cometbft/cometbft v0.37.2/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft-db v0.8.0 h1:vUMDaH3ApkX8m0KZvOFFy9b5DZHBAjsnEuo9AKVZpjo= +github.com/cometbft/cometbft-db v0.8.0/go.mod h1:6ASCP4pfhmrCBpfk01/9E1SI29nD3HfVHrY4PG8x5c0= github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= github.com/containerd/continuity v0.3.0 h1:nisirsYROK15TAMVukJOUyGJjz4BNQJBVsNvAXZJ/eg= @@ -321,8 +322,8 @@ github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= -github.com/cosmos/cosmos-sdk v0.47.3 h1:r0hGmZoAzP2D+MaPaFGHwAaTdFQq3pNpHaUp1BsffbM= -github.com/cosmos/cosmos-sdk v0.47.3/go.mod h1:c4OfLdAykA9zsj1CqrxBRqXzVz48I++JSvIMPSPcEmk= +github.com/cosmos/cosmos-sdk v0.47.4 h1:FVUpEprm58nMmBX4xkRdMDaIG5Nr4yy92HZAfGAw9bg= +github.com/cosmos/cosmos-sdk v0.47.4/go.mod h1:R5n+uM7vguVPFap4pgkdvQCT1nVo/OtPwrlAU40rvok= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= @@ -333,14 +334,20 @@ github.com/cosmos/gogoproto v1.4.10 h1:QH/yT8X+c0F4ZDacDv3z+xE3WU1P1Z3wQoLMBRJoK github.com/cosmos/gogoproto v1.4.10/go.mod h1:3aAZzeRWpAwr+SS/LLkICX2/kDFyaYVzckBDzygIxek= github.com/cosmos/iavl v0.20.0 h1:fTVznVlepH0KK8NyKq8w+U7c2L6jofa27aFX6YGlm38= github.com/cosmos/iavl v0.20.0/go.mod h1:WO7FyvaZJoH65+HFOsDir7xU9FWk2w9cHXNW1XHcl7A= -github.com/cosmos/ibc-go/v7 v7.0.1 h1:NIBNRWjlOoFvFQu1ZlgwkaSeHO5avf4C1YQiWegt8jw= -github.com/cosmos/ibc-go/v7 v7.0.1/go.mod h1:vEaapV6nuLPQlS+g8IKmxMo6auPi0i7HMv1PhViht/E= -github.com/cosmos/ics23/go v0.9.1-0.20221207100636-b1abd8678aab h1:I9ialKTQo7248V827Bba4OuKPmk+FPzmTVHsLXaIJWw= -github.com/cosmos/ics23/go v0.9.1-0.20221207100636-b1abd8678aab/go.mod h1:2CwqasX5dSD7Hbp/9b6lhK6BwoBDCBldx7gPKRukR60= +github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7 v7.0.0 h1:i9esYyZ5ExpZOgxrLMQhY2jDTVYiaD8yUeqXN9QBgbk= +github.com/cosmos/ibc-apps/middleware/packet-forward-middleware/v7 v7.0.0/go.mod h1:fctjEnz9xaBFOlmYYPdKL8Hs1Y3GUKilSwsJdqBb5QU= +github.com/cosmos/ibc-apps/modules/async-icq/v7 v7.0.0 h1:mMHedP3Q+mz5gpOWNz0P+X8hxPdamylrBKc/P2cFakA= +github.com/cosmos/ibc-apps/modules/async-icq/v7 v7.0.0/go.mod h1:/P6l2bWo2AR3rrsfs0DHuFZO3Imzb93sxFD3ihrIgw4= +github.com/cosmos/ibc-apps/modules/ibc-hooks/v7 v7.0.0-20230906222317-d88d4028e5c9 h1:Ji2ch8iw8qLh0xG/NY+RVsQ0tqiy+tViQxiaOHKpsw0= +github.com/cosmos/ibc-apps/modules/ibc-hooks/v7 v7.0.0-20230906222317-d88d4028e5c9/go.mod h1:JwHFbo1oX/ht4fPpnPvmhZr+dCkYK1Vihw+vZE9umR4= +github.com/cosmos/ibc-go/v7 v7.2.0 h1:dx0DLUl7rxdyZ8NiT6UsrbzKOJx/w7s+BOaewFRH6cg= +github.com/cosmos/ibc-go/v7 v7.2.0/go.mod h1:OOcjKIRku/j1Xs1RgKK0yvKRrJ5iFuZYMetR1n3yMlc= +github.com/cosmos/ics23/go v0.10.0 h1:iXqLLgp2Lp+EdpIuwXTYIQU+AiHj9mOC2X9ab++bZDM= +github.com/cosmos/ics23/go v0.10.0/go.mod h1:ZfJSmng/TBNTBkFemHHHj5YY7VAU/MBU980F4VU1NG0= github.com/cosmos/keyring v1.2.0 h1:8C1lBP9xhImmIabyXW4c3vFjjLiBdGCmfLUfeZlV1Yo= github.com/cosmos/keyring v1.2.0/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA= -github.com/cosmos/ledger-cosmos-go v0.12.1 h1:sMBxza5p/rNK/06nBSNmsI/WDqI0pVJFVNihy1Y984w= -github.com/cosmos/ledger-cosmos-go v0.12.1/go.mod h1:dhO6kj+Y+AHIOgAe4L9HL/6NDdyyth4q238I9yFpD2g= +github.com/cosmos/ledger-cosmos-go v0.12.2 h1:/XYaBlE2BJxtvpkHiBm97gFGSGmYGKunKyF3nNqAXZA= +github.com/cosmos/ledger-cosmos-go v0.12.2/go.mod h1:ZcqYgnfNJ6lAXe4HPtWgarNEY+B74i+2/8MhZw4ziiI= github.com/cosmos/rosetta-sdk-go v0.10.0 h1:E5RhTruuoA7KTIXUcMicL76cffyeoyvNybzUGSKFTcM= github.com/cosmos/rosetta-sdk-go v0.10.0/go.mod h1:SImAZkb96YbwvoRkzSMQB6noNJXFgWl/ENIznEoYQI4= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= @@ -395,9 +402,6 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.m github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c h1:8ISkoahWXwZR41ois5lSJBSVw4D0OV19Ht/JSTzvSv0= -github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 h1:JWuenKqqX8nojtoVVWjGfOF9635RETekkoH6Cc9SX0A= -github.com/facebookgo/subset v0.0.0-20200203212716-c811ad88dec4 h1:7HZCaLC5+BZpmbhCOZJ293Lz68O7PYrF2EzeiFMwCLk= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/felixge/httpsnoop v1.0.2 h1:+nS9g82KMXccJ/wp0zyRW9ZBHFETmMGtkk+2CTTrW4o= @@ -435,8 +439,8 @@ github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs= github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho= github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA= +github.com/go-playground/validator/v10 v10.10.0 h1:I7mrTYv78z8k8VXa/qJlOlEXn/nBh+BF8dHX5nt/dr0= github.com/go-playground/validator/v10 v10.10.0/go.mod h1:74x4gJWsvQexRdW8Pn3dXSGrTK4nAUsbPlLADvpJkos= -github.com/go-playground/validator/v10 v10.11.1 h1:prmOlTVv+YjZjmRmNSF3VmspqJIxJWXmqUsHwfTRRkQ= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0= @@ -445,8 +449,8 @@ github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8= github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo= github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/goccy/go-json v0.9.7 h1:IcB+Aqpx/iMHu5Yooh7jEzJk1JZ7Pjtmys2ukPr7EeM= github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk= github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0= github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= @@ -553,8 +557,8 @@ github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/s2a-go v0.1.3 h1:FAgZmpLl/SXurPEZyCMPBIiiYeTbqfjlbdnCNTAkbGE= -github.com/google/s2a-go v0.1.3/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= +github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= +github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= @@ -573,8 +577,8 @@ github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99 github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK9wbMD5+iXC6c= github.com/googleapis/gax-go/v2 v2.5.1/go.mod h1:h6B0KMMFNtI2ddbGJn3T3ZbwkeT6yqEF02fYlzkUCyo= github.com/googleapis/gax-go/v2 v2.6.0/go.mod h1:1mjbznJAPHFpesgE5ucqfYEscaz5kMdcIDwU/6+DDoY= -github.com/googleapis/gax-go/v2 v2.8.0 h1:UBtEZqx1bjXtOQ5BVTkuYghXrr3N4V123VKJK67vJZc= -github.com/googleapis/gax-go/v2 v2.8.0/go.mod h1:4orTrqY6hXxxaUL4LHIPl6lGo8vAE38/qKbhSAKP6QI= +github.com/googleapis/gax-go/v2 v2.11.0 h1:9V9PWXEsWnPpQhu/PeQIkS4eGzMlTLGgt80cUUI8Ki4= +github.com/googleapis/gax-go/v2 v2.11.0/go.mod h1:DxmR61SGKkGLa2xigwuZIQpkCI2S5iydzRfb3peWZJI= github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= @@ -649,12 +653,13 @@ github.com/huandu/go-assert v1.1.5/go.mod h1:yOLvuqZwmcHIC5rIzrBhT7D3Q9c3GFnd0Jr github.com/huandu/skiplist v1.2.0 h1:gox56QD77HzSC0w+Ws3MH3iie755GBJU1OER3h5VsYw= github.com/huandu/skiplist v1.2.0/go.mod h1:7v3iFjLcSAzO4fN5B8dvebvo/qsfumiLiDXMrPiHF9w= github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= +github.com/iancoleman/orderedmap v0.2.0 h1:sq1N/TFpYH++aViPcaKjys3bDClUEU7s5B+z6jq8pNA= +github.com/iancoleman/orderedmap v0.2.0/go.mod h1:N0Wam8K1arqPXNWjMo21EXnBPOPp36vB07FNRdD2geA= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= 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= @@ -710,6 +715,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -724,8 +731,8 @@ github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98= -github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= @@ -830,8 +837,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_golang v1.15.0 h1:5fCgGYogn0hFdhyhLbw7hEsWxufKtY9klyvdNfFlFhM= -github.com/prometheus/client_golang v1.15.0/go.mod h1:e9yaBhRPU2pPNsZwE+JdQl0KEt1N9XgF6zxWmaC0xOk= +github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8= +github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -854,8 +861,8 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.3.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.9.0 h1:wzCHvIvM5SxWqYvwgVL7yJY8Lz3PKn49KQtpgMYJfhI= -github.com/prometheus/procfs v0.9.0/go.mod h1:+pB4zwohETzFnmlpe6yd2lSc+0/46IYZRB/chUwxUZY= +github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+PymziUAg= +github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM= github.com/rakyll/statik v0.1.7 h1:OF3QCZUuyPxuGEP7B4ypUa7sB/iHtqOTDYZXGM8KOdQ= github.com/rakyll/statik v0.1.7/go.mod h1:AlZONWzMtEnMs7W4e/1LURLiI49pIMmp6V9Unghqrcc= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= @@ -905,8 +912,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= @@ -934,14 +941,13 @@ 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= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= -github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c h1:g+WoO5jjkqGAzHWCjJB1zZfXPIAaDpzXIEJ0eS6B5Ok= -github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c/go.mod h1:ahpPrc7HpcfEWDQRZEmnXMzHY03mLDYMCxeDzy46i+8= github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= github.com/tidwall/btree v1.6.0 h1:LDZfKfQIBHGHWSwckhXI0RPSXzlo+KYdjK7FWSqOzzg= @@ -1010,8 +1016,8 @@ golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g= -golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= +golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= +golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= 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= @@ -1113,8 +1119,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.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= +golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= 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= @@ -1140,8 +1146,8 @@ golang.org/x/oauth2 v0.0.0-20220822191816-0ebed06d0094/go.mod h1:h4gKUeWbJ4rQPri golang.org/x/oauth2 v0.0.0-20220909003341-f21342109be1/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= golang.org/x/oauth2 v0.1.0/go.mod h1:G9FE4dLTsbXUu90h/Pf85g4w1D+SSAgR+q46nJZ8M4A= -golang.org/x/oauth2 v0.7.0 h1:qe6s0zUXlPX80/dITx3440hWZ7GwMwgDDyrSGTPJG/g= -golang.org/x/oauth2 v0.7.0/go.mod h1:hPLQkd9LyjfXTiRohC/41GhcFqxisoUQ99sCUOHO9x4= +golang.org/x/oauth2 v0.8.0 h1:6dkIjl3j3LtZ/O3sTgZTMsLKSftL/B8Zgq4huOIIUu8= +golang.org/x/oauth2 v0.8.0/go.mod h1:yr7u4HXZRm1R1kBWqr/xKNqewf0plRYoB7sla+BCIXE= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1156,7 +1162,7 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= +golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -1254,13 +1260,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.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= +golang.org/x/sys v0.10.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.8.0 h1:n5xxQn2i3PC0yLAbjTpNT85q/Kgzcr2gIoX9OrJUols= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.10.0 h1:3R7pNqamzBraeqj/Tj8qt1aQ2HpmlC+Cx/qL/7hn4/c= +golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= 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= @@ -1272,8 +1278,8 @@ 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.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= 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.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= +golang.org/x/text v0.11.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= @@ -1399,8 +1405,8 @@ google.golang.org/api v0.96.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ google.golang.org/api v0.97.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= google.golang.org/api v0.98.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= google.golang.org/api v0.100.0/go.mod h1:ZE3Z2+ZOr87Rx7dqFsdRQkRBk36kDtp/h+QpHbB7a70= -google.golang.org/api v0.122.0 h1:zDobeejm3E7pEG1mNHvdxvjs5XJoCMzyNH+CmwL94Es= -google.golang.org/api v0.122.0/go.mod h1:gcitW0lvnyWjSp9nKxAbdHKIZ6vF4aajGueeslZOyms= +google.golang.org/api v0.126.0 h1:q4GJq+cAdMAC7XP7njvQ4tvohGLiSlytuL4BQxbIZ+o= +google.golang.org/api v0.126.0/go.mod h1:mBwVAtz+87bEN6CbA1GtZPDOqY2R5ONPqJeIlvyo4Aw= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -1518,8 +1524,12 @@ google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e/go.mod h1:3526vdqw google.golang.org/genproto v0.0.0-20221014173430-6e2ab493f96b/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= google.golang.org/genproto v0.0.0-20221025140454-527a21cfbd71/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= -google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= -google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= +google.golang.org/genproto v0.0.0-20230706204954-ccb25ca9f130 h1:Au6te5hbKUV8pIYWHqOUZ1pva5qK/rwbIhoXEUB9Lu8= +google.golang.org/genproto v0.0.0-20230706204954-ccb25ca9f130/go.mod h1:O9kGHb51iE/nOGvQaDUuadVYqovW56s5emA88lQnj6Y= +google.golang.org/genproto/googleapis/api v0.0.0-20230629202037-9506855d4529 h1:s5YSX+ZH5b5vS9rnpGymvIyMpLRJizowqDlOuyjXnTk= +google.golang.org/genproto/googleapis/api v0.0.0-20230629202037-9506855d4529/go.mod h1:vHYtlOoi6TsQ3Uk2yxR7NI5z8uoV+3pZtR4jmHIkRig= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 h1:bVf09lpb+OJbByTj913DRJioFFAjf/ZGxEz7MajTp2U= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= @@ -1561,8 +1571,8 @@ google.golang.org/grpc v1.48.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACu google.golang.org/grpc v1.49.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= google.golang.org/grpc v1.50.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= google.golang.org/grpc v1.50.1/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= -google.golang.org/grpc v1.55.0 h1:3Oj82/tFSCeUrRTg/5E/7d/W5A1tj6Ky1ABAuZuv5ag= -google.golang.org/grpc v1.55.0/go.mod h1:iYEXKGkEBhg1PjZQvoYEVPTDkHo1/bjTnfwTeGONTY8= +google.golang.org/grpc v1.56.2 h1:fVRFRnXvU+x6C4IlHZewvJOVHoOv1TUuQyoRsYnB4bI= +google.golang.org/grpc v1.56.2/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= @@ -1579,8 +1589,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= @@ -1614,7 +1624,7 @@ gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= -gotest.tools/v3 v3.4.0 h1:ZazjZUfuVeZGLAmlKKuyv3IKP5orXcwtOwDQH6YVr6o= +gotest.tools/v3 v3.5.0 h1:Ljk6PdHdOhAb5aDMWXjDLMMhph+BpztA4v1QdqEW2eY= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/interchaintest/chain_start_test.go b/interchaintest/chain_start_test.go new file mode 100644 index 0000000..310bd79 --- /dev/null +++ b/interchaintest/chain_start_test.go @@ -0,0 +1,27 @@ +package interchaintest + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// TestBasicTerpStart is a basic test to assert that spinning up a Terp network with one validator works properly. +func TestBasicTerpStart(t *testing.T) { + if testing.Short() { + t.Skip() + } + + t.Parallel() + + // Base setup + chains := CreateThisBranchChain(t, 1, 0) + ic, ctx, _, _ := BuildInitialChain(t, chains) + + require.NotNil(t, ic) + require.NotNil(t, ctx) + + t.Cleanup(func() { + _ = ic.Close() + }) +} diff --git a/interchaintest/chain_upgrade_test.go b/interchaintest/chain_upgrade_test.go new file mode 100644 index 0000000..1df6aa7 --- /dev/null +++ b/interchaintest/chain_upgrade_test.go @@ -0,0 +1,140 @@ +package interchaintest + +import ( + "context" + "fmt" + "testing" + "time" + + cosmosproto "github.com/cosmos/gogoproto/proto" + "github.com/docker/docker/client" + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" + + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" +) + +const ( + haltHeightDelta = uint64(9) // will propose upgrade this many blocks in the future + blocksAfterUpgrade = uint64(7) +) + +func TestBasicTerpUpgrade(t *testing.T) { + repo, version := GetDockerImageInfo() + startVersion := "barberry" + upgradeName := "v2" + CosmosChainUpgradeTest(t, "terp", startVersion, version, repo, upgradeName) +} + +func CosmosChainUpgradeTest(t *testing.T, chainName, initialVersion, upgradeBranchVersion, upgradeRepo, upgradeName string) { + if testing.Short() { + t.Skip("skipping in short mode") + } + + t.Parallel() + + t.Log(chainName, initialVersion, upgradeBranchVersion, upgradeRepo, upgradeName) + + numVals, numNodes := 2, 2 + chains := CreateThisBranchChain(t, numVals, numNodes) + chain := chains[0].(*cosmos.CosmosChain) + + ic, ctx, client, _ := BuildInitialChain(t, chains) + + t.Cleanup(func() { + _ = ic.Close() + }) + + const userFunds = int64(10_000_000_000) + users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), userFunds, chain) + chainUser := users[0] + + // upgrade + height, err := chain.Height(ctx) + require.NoError(t, err, "error fetching height before submit upgrade proposal") + + haltHeight := height + haltHeightDelta + proposalID := SubmitUpgradeProposal(t, ctx, chain, chainUser, upgradeName, haltHeight) + + ValidatorVoting(t, ctx, chain, proposalID, height, haltHeight) + + UpgradeNodes(t, ctx, chain, client, haltHeight, upgradeRepo, upgradeBranchVersion) +} + +func UpgradeNodes(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, client *client.Client, haltHeight uint64, upgradeRepo, upgradeBranchVersion string) { + // bring down nodes to prepare for upgrade + t.Log("stopping node(s)") + err := chain.StopAllNodes(ctx) + require.NoError(t, err, "error stopping node(s)") + + // upgrade version on all nodes + t.Log("upgrading node(s)") + chain.UpgradeVersion(ctx, client, upgradeRepo, upgradeBranchVersion) + + // start all nodes back up. + // validators reach consensus on first block after upgrade height + // and chain block production resumes. + t.Log("starting node(s)") + err = chain.StartAllNodes(ctx) + require.NoError(t, err, "error starting upgraded node(s)") + + timeoutCtx, timeoutCtxCancel := context.WithTimeout(ctx, time.Second*60) + defer timeoutCtxCancel() + + err = testutil.WaitForBlocks(timeoutCtx, int(blocksAfterUpgrade), chain) + require.NoError(t, err, "chain did not produce blocks after upgrade") + + height, err := chain.Height(ctx) + require.NoError(t, err, "error fetching height after upgrade") + + require.GreaterOrEqual(t, height, haltHeight+blocksAfterUpgrade, "height did not increment enough after upgrade") +} + +func ValidatorVoting(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, proposalID string, height uint64, haltHeight uint64) { + err := chain.VoteOnProposalAllValidators(ctx, proposalID, cosmos.ProposalVoteYes) + require.NoError(t, err, "failed to submit votes") + + _, err = cosmos.PollForProposalStatus(ctx, chain, height, height+haltHeightDelta, proposalID, cosmos.ProposalStatusPassed) + require.NoError(t, err, "proposal status did not change to passed in expected number of blocks") + + timeoutCtx, timeoutCtxCancel := context.WithTimeout(ctx, time.Second*45) + defer timeoutCtxCancel() + + height, err = chain.Height(ctx) + require.NoError(t, err, "error fetching height before upgrade") + + // this should timeout due to chain halt at upgrade height. + _ = testutil.WaitForBlocks(timeoutCtx, int(haltHeight-height), chain) + + height, err = chain.Height(ctx) + require.NoError(t, err, "error fetching height after chain should have halted") + + // make sure that chain is halted + require.Equal(t, haltHeight, height, "height is not equal to halt height") +} + +func SubmitUpgradeProposal(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, user ibc.Wallet, upgradeName string, haltHeight uint64) string { + // TODO Return proposal id + upgradeMsg := []cosmosproto.Message{ + &upgradetypes.MsgSoftwareUpgrade{ + // gGov Module account + Authority: "terp10d07y265gmmuvt4z0w9aw880jnsr700jag6fuq", + Plan: upgradetypes.Plan{ + Name: upgradeName, + Height: int64(haltHeight), + }, + }, + } + + proposal, err := chain.BuildProposal(upgradeMsg, "Chain Upgrade 1", "Summary desc", "ipfs://CID", fmt.Sprintf(`500000000%s`, chain.Config().Denom)) + require.NoError(t, err, "error building proposal") + + txProp, err := chain.SubmitProposal(ctx, user.KeyName(), proposal) + t.Log("txProp", txProp) + require.NoError(t, err, "error submitting proposal") + + return txProp.ProposalID +} diff --git a/interchaintest/ci_integration.go b/interchaintest/ci_integration.go new file mode 100644 index 0000000..e684fee --- /dev/null +++ b/interchaintest/ci_integration.go @@ -0,0 +1,23 @@ +package interchaintest + +import ( + "os" + "strings" +) + +// GetDockerImageInfo returns the appropriate repo and branch version string for integration with the CI pipeline. +// The remote runner sets the BRANCH_CI env var. If present, interchaintest will use the docker image pushed up to the repo. +// If testing locally, user should run `make local-image` and interchaintest will use the local image. +func GetDockerImageInfo() (repo, version string) { + branchVersion, found := os.LookupEnv("BRANCH_CI") + repo = TerpE2ERepo + if !found { + // make local-image + repo = "terpnetwork" + branchVersion = "local" + } + + // github converts / to - for pushed docker images + branchVersion = strings.ReplaceAll(branchVersion, "/", "-") + return repo, branchVersion +} diff --git a/interchaintest/contracts/cw_template.wasm b/interchaintest/contracts/cw_template.wasm new file mode 100644 index 0000000..909cbdd Binary files /dev/null and b/interchaintest/contracts/cw_template.wasm differ diff --git a/interchaintest/contracts/ibchooks_counter.wasm b/interchaintest/contracts/ibchooks_counter.wasm new file mode 100644 index 0000000..938171e Binary files /dev/null and b/interchaintest/contracts/ibchooks_counter.wasm differ diff --git a/interchaintest/contracts/tokenfactory_core.wasm b/interchaintest/contracts/tokenfactory_core.wasm new file mode 100644 index 0000000..b6994d2 Binary files /dev/null and b/interchaintest/contracts/tokenfactory_core.wasm differ diff --git a/interchaintest/go.mod b/interchaintest/go.mod new file mode 100644 index 0000000..913d313 --- /dev/null +++ b/interchaintest/go.mod @@ -0,0 +1,247 @@ +module github.com/terpnetwork/terp-core/tests/interchaintest + +go 1.20 + +replace ( + // interchaintest supports ICS features so we need this for now + // github.com/cosmos/cosmos-sdk => github.com/cosmos/cosmos-sdk v0.45.13-ics + github.com/ChainSafe/go-schnorrkel => github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d + github.com/ChainSafe/go-schnorrkel/1 => github.com/ChainSafe/go-schnorrkel v1.0.0 + github.com/btcsuite/btcd => github.com/btcsuite/btcd v0.22.2 //indirect + github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 + // For this nested module, you always want to replace the parent reference with the current worktree. + github.com/terpnetwork/terp-core/v2 => ../ + + github.com/vedhavyas/go-subkey => github.com/strangelove-ventures/go-subkey v1.0.7 +) + +require ( + github.com/CosmWasm/wasmd v0.41.0 + github.com/cosmos/cosmos-sdk v0.47.4 + github.com/cosmos/gogoproto v1.4.10 + github.com/cosmos/ibc-go/v7 v7.2.0 + github.com/docker/docker v24.0.4+incompatible + github.com/strangelove-ventures/interchaintest/v7 v7.0.0-20230721183422-fb937bb0e165 + github.com/stretchr/testify v1.8.4 + github.com/terpnetwork/terp-core/v2 v2.0.0-00010101000000-000000000000 + go.uber.org/zap v1.24.0 +) + +require ( + cloud.google.com/go v0.110.4 // indirect + cloud.google.com/go/compute v1.20.1 // indirect + cloud.google.com/go/compute/metadata v0.2.3 // indirect + cloud.google.com/go/iam v1.1.0 // indirect + cloud.google.com/go/storage v1.30.1 // indirect + cosmossdk.io/api v0.3.1 // indirect + cosmossdk.io/core v0.6.1 // indirect + cosmossdk.io/depinject v1.0.0-alpha.3 // indirect + cosmossdk.io/errors v1.0.0 // indirect + cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca // 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.2 // indirect + github.com/BurntSushi/toml v1.3.2 // indirect + github.com/ChainSafe/go-schnorrkel v1.0.0 // indirect + github.com/ChainSafe/go-schnorrkel/1 v0.0.0-00010101000000-000000000000 // indirect + github.com/ComposableFi/go-subkey/v2 v2.0.0-tm03420 // indirect + github.com/CosmWasm/wasmvm v1.3.0 // indirect + github.com/FactomProject/basen v0.0.0-20150613233007-fe3947df716e // indirect + github.com/FactomProject/btcutilecc v0.0.0-20130527213604-d3a63a5752ec // indirect + github.com/Microsoft/go-winio v0.6.0 // indirect + github.com/StirlingMarketingGroup/go-namecase v1.0.0 // indirect + github.com/armon/go-metrics v0.4.1 // indirect + github.com/avast/retry-go/v4 v4.3.4 // indirect + github.com/aws/aws-sdk-go v1.44.203 // indirect + github.com/benbjohnson/clock v1.3.0 // 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/cenkalti/backoff/v4 v4.1.3 // indirect + github.com/cespare/xxhash v1.1.0 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/chzyer/readline v1.5.1 // indirect + github.com/coinbase/rosetta-sdk-go/types v1.0.0 // indirect + github.com/cometbft/cometbft v0.37.2 // indirect + github.com/cometbft/cometbft-db v0.8.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.3 // 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 + github.com/cosmos/ics23/go v0.10.0 // indirect + github.com/cosmos/ledger-cosmos-go v0.12.2 // indirect + github.com/cosmos/rosetta-sdk-go v0.10.0 // indirect + github.com/creachadair/taskgroup v0.4.2 // indirect + github.com/danieljoos/wincred v1.1.2 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/deckarep/golang-set v1.8.0 // indirect + github.com/decred/base58 v1.0.4 // indirect + github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v2 v2.0.1 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect + github.com/dgraph-io/badger/v2 v2.2007.4 // indirect + github.com/dgraph-io/ristretto v0.1.1 // indirect + github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect + github.com/docker/distribution v2.8.2+incompatible // indirect + github.com/docker/go-connections v0.4.0 // indirect + github.com/docker/go-units v0.5.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/dvsekhvalnov/jose2go v1.5.0 // indirect + github.com/ethereum/go-ethereum v1.11.6 // indirect + github.com/felixge/httpsnoop v1.0.2 // indirect + github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/go-kit/kit v0.12.0 // indirect + github.com/go-kit/log v0.2.1 // indirect + github.com/go-logfmt/logfmt v0.6.0 // indirect + github.com/go-stack/stack v1.8.1 // indirect + github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect + github.com/gogo/googleapis v1.4.1 // indirect + github.com/gogo/protobuf v1.3.3 // indirect + github.com/golang/glog v1.1.0 // indirect + github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/mock v1.6.0 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect + github.com/google/btree v1.1.2 // indirect + github.com/google/go-cmp v0.5.9 // indirect + github.com/google/orderedcode v0.0.1 // indirect + github.com/google/s2a-go v0.1.4 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect + github.com/googleapis/gax-go/v2 v2.11.0 // indirect + github.com/gorilla/handlers v1.5.1 // indirect + github.com/gorilla/mux v1.8.0 // indirect + github.com/gorilla/websocket v1.5.0 // indirect + github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 // indirect + github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect + github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect + github.com/gtank/merlin v0.1.1 // indirect + github.com/gtank/ristretto255 v0.1.2 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-getter v1.7.1 // indirect + github.com/hashicorp/go-immutable-radix v1.3.1 // indirect + github.com/hashicorp/go-safetemp v1.0.0 // indirect + github.com/hashicorp/go-version v1.6.0 // indirect + github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/hdevalence/ed25519consensus v0.1.0 // indirect + github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c // indirect + github.com/huandu/skiplist v1.2.0 // indirect + github.com/icza/dyno v0.0.0-20220812133438-f0b6f8a18845 // indirect + github.com/improbable-eng/grpc-web v0.15.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/ipfs/go-cid v0.2.0 // indirect + github.com/jmespath/go-jmespath v0.4.0 // indirect + github.com/jmhodges/levigo v1.0.0 // indirect + github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect + github.com/klauspost/compress v1.16.3 // indirect + github.com/klauspost/cpuid/v2 v2.2.3 // indirect + github.com/lib/pq v1.10.7 // indirect + github.com/libp2p/go-buffer-pool v0.1.0 // indirect + github.com/libp2p/go-libp2p v0.22.0 // indirect + github.com/libp2p/go-openssl v0.1.0 // indirect + github.com/linxGnu/grocksdb v1.7.16 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/manifoldco/promptui v0.9.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-pointer v0.0.1 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect + github.com/mimoo/StrobeGo v0.0.0-20220103164710-9a04d6ca976b // indirect + github.com/minio/highwayhash v1.0.2 // indirect + github.com/minio/sha256-simd v1.0.0 // indirect + github.com/misko9/go-substrate-rpc-client/v4 v4.0.0-20230413215336-5bd2aea337ae // indirect + github.com/mitchellh/go-homedir v1.1.0 // indirect + github.com/mitchellh/go-testing-interface v1.14.1 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/mr-tron/base58 v1.2.0 // indirect + github.com/mtibben/percent v0.2.1 // indirect + github.com/multiformats/go-base32 v0.0.4 // indirect + github.com/multiformats/go-base36 v0.1.0 // indirect + github.com/multiformats/go-multiaddr v0.6.0 // indirect + github.com/multiformats/go-multibase v0.1.1 // indirect + github.com/multiformats/go-multicodec v0.5.0 // indirect + github.com/multiformats/go-multihash v0.2.1 // indirect + github.com/multiformats/go-varint v0.0.6 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.0-rc2 // indirect + github.com/pelletier/go-toml v1.9.5 // indirect + github.com/pelletier/go-toml/v2 v2.0.9 // indirect + github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 // indirect + github.com/pierrec/xxHash v0.1.5 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/prometheus/client_golang v1.16.0 // indirect + github.com/prometheus/client_model v0.3.0 // indirect + github.com/prometheus/common v0.42.0 // indirect + github.com/prometheus/procfs v0.10.1 // indirect + github.com/rakyll/statik v0.1.7 // indirect + github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rs/cors v1.8.3 // indirect + github.com/rs/zerolog v1.29.1 // indirect + github.com/sasha-s/go-deadlock v0.3.1 // indirect + github.com/spacemonkeygo/spacelog v0.0.0-20180420211403-2296661a0572 // indirect + github.com/spaolacci/murmur3 v1.1.0 // indirect + github.com/spf13/afero v1.9.5 // indirect + github.com/spf13/cast v1.5.1 // indirect + github.com/spf13/cobra v1.7.0 // indirect + github.com/spf13/jwalterweatherman v1.1.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/spf13/viper v1.16.0 // indirect + github.com/subosito/gotenv v1.4.2 // indirect + github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect + github.com/tendermint/go-amino v0.16.0 // indirect + github.com/tidwall/btree v1.6.0 // indirect + github.com/tyler-smith/go-bip32 v1.0.0 // indirect + github.com/tyler-smith/go-bip39 v1.1.0 // indirect + github.com/ulikunitz/xz v0.5.11 // indirect + github.com/zondax/hid v0.9.1 // indirect + github.com/zondax/ledger-go v0.14.1 // indirect + go.etcd.io/bbolt v1.3.7 // indirect + go.opencensus.io v0.24.0 // indirect + go.uber.org/atomic v1.10.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/crypto v0.11.0 // indirect + golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc // indirect + golang.org/x/mod v0.12.0 // indirect + golang.org/x/net v0.12.0 // indirect + golang.org/x/oauth2 v0.8.0 // indirect + golang.org/x/sync v0.3.0 // indirect + golang.org/x/sys v0.10.0 // indirect + golang.org/x/term v0.10.0 // indirect + golang.org/x/text v0.11.0 // indirect + golang.org/x/tools v0.11.0 // indirect + golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect + google.golang.org/api v0.126.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/genproto v0.0.0-20230706204954-ccb25ca9f130 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20230629202037-9506855d4529 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect + google.golang.org/grpc v1.56.2 // indirect + google.golang.org/protobuf v1.31.0 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + lukechampine.com/blake3 v1.1.7 // indirect + lukechampine.com/uint128 v1.2.0 // indirect + modernc.org/cc/v3 v3.40.0 // indirect + modernc.org/ccgo/v3 v3.16.13 // indirect + modernc.org/libc v1.22.5 // indirect + modernc.org/mathutil v1.5.0 // indirect + modernc.org/memory v1.5.0 // indirect + modernc.org/opt v0.1.3 // indirect + modernc.org/sqlite v1.24.0 // indirect + modernc.org/strutil v1.1.3 // indirect + modernc.org/token v1.0.1 // indirect + nhooyr.io/websocket v1.8.7 // indirect + pgregory.net/rapid v0.5.5 // indirect + sigs.k8s.io/yaml v1.3.0 // indirect +) diff --git a/interchaintest/go.sum b/interchaintest/go.sum new file mode 100644 index 0000000..838af1a --- /dev/null +++ b/interchaintest/go.sum @@ -0,0 +1,1771 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= +cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= +cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY= +cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= +cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= +cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= +cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY= +cloud.google.com/go v0.84.0/go.mod h1:RazrYuxIK6Kb7YrzzhPoLmCVzl7Sup4NrbKPg8KHSUM= +cloud.google.com/go v0.87.0/go.mod h1:TpDYlFy7vuLzZMMZ+B6iRiELaY7z/gJPaqbMx6mlWcY= +cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aDQ= +cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= +cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW4= +cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= +cloud.google.com/go v0.99.0/go.mod h1:w0Xx2nLzqWJPuozYQX+hFfCSI8WioryfRDzkoI/Y2ZA= +cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w99A= +cloud.google.com/go v0.102.0/go.mod h1:oWcCzKlqJ5zgHQt9YsaeTY9KzIvjyy0ArmiBUgpQ+nc= +cloud.google.com/go v0.102.1/go.mod h1:XZ77E9qnTEnrgEOvr4xzfdX5TRo7fB4T2F4O6+34hIU= +cloud.google.com/go v0.104.0/go.mod h1:OO6xxXdJyvuJPcEPBLN9BJPD+jep5G1+2U5B5gkRYtA= +cloud.google.com/go v0.110.4 h1:1JYyxKMN9hd5dR2MYTPWkGUgcoxVVhg0LKNKEo0qvmk= +cloud.google.com/go v0.110.4/go.mod h1:+EYjdK8e5RME/VY/qLCAtuyALQ9q67dvuum8i+H5xsI= +cloud.google.com/go/aiplatform v1.22.0/go.mod h1:ig5Nct50bZlzV6NvKaTwmplLLddFx0YReh9WfTO5jKw= +cloud.google.com/go/aiplatform v1.24.0/go.mod h1:67UUvRBKG6GTayHKV8DBv2RtR1t93YRu5B1P3x99mYY= +cloud.google.com/go/analytics v0.11.0/go.mod h1:DjEWCu41bVbYcKyvlws9Er60YE4a//bK6mnhWvQeFNI= +cloud.google.com/go/analytics v0.12.0/go.mod h1:gkfj9h6XRf9+TS4bmuhPEShsh3hH8PAZzm/41OOhQd4= +cloud.google.com/go/area120 v0.5.0/go.mod h1:DE/n4mp+iqVyvxHN41Vf1CR602GiHQjFPusMFW6bGR4= +cloud.google.com/go/area120 v0.6.0/go.mod h1:39yFJqWVgm0UZqWTOdqkLhjoC7uFfgXRC8g/ZegeAh0= +cloud.google.com/go/artifactregistry v1.6.0/go.mod h1:IYt0oBPSAGYj/kprzsBjZ/4LnG/zOcHyFHjWPCi6SAQ= +cloud.google.com/go/artifactregistry v1.7.0/go.mod h1:mqTOFOnGZx8EtSqK/ZWcsm/4U8B77rbcLP6ruDU2Ixk= +cloud.google.com/go/asset v1.5.0/go.mod h1:5mfs8UvcM5wHhqtSv8J1CtxxaQq3AdBxxQi2jGW/K4o= +cloud.google.com/go/asset v1.7.0/go.mod h1:YbENsRK4+xTiL+Ofoj5Ckf+O17kJtgp3Y3nn4uzZz5s= +cloud.google.com/go/asset v1.8.0/go.mod h1:mUNGKhiqIdbr8X7KNayoYvyc4HbbFO9URsjbytpUaW0= +cloud.google.com/go/assuredworkloads v1.5.0/go.mod h1:n8HOZ6pff6re5KYfBXcFvSViQjDwxFkAkmUFffJRbbY= +cloud.google.com/go/assuredworkloads v1.6.0/go.mod h1:yo2YOk37Yc89Rsd5QMVECvjaMKymF9OP+QXWlKXUkXw= +cloud.google.com/go/assuredworkloads v1.7.0/go.mod h1:z/736/oNmtGAyU47reJgGN+KVoYoxeLBoj4XkKYscNI= +cloud.google.com/go/automl v1.5.0/go.mod h1:34EjfoFGMZ5sgJ9EoLsRtdPSNZLcfflJR39VbVNS2M0= +cloud.google.com/go/automl v1.6.0/go.mod h1:ugf8a6Fx+zP0D59WLhqgTDsQI9w07o64uf/Is3Nh5p8= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/bigquery v1.42.0/go.mod h1:8dRTJxhtG+vwBKzE5OseQn/hiydoQN3EedCaOdYmxRA= +cloud.google.com/go/billing v1.4.0/go.mod h1:g9IdKBEFlItS8bTtlrZdVLWSSdSyFUZKXNS02zKMOZY= +cloud.google.com/go/billing v1.5.0/go.mod h1:mztb1tBc3QekhjSgmpf/CV4LzWXLzCArwpLmP2Gm88s= +cloud.google.com/go/binaryauthorization v1.1.0/go.mod h1:xwnoWu3Y84jbuHa0zd526MJYmtnVXn0syOjaJgy4+dM= +cloud.google.com/go/binaryauthorization v1.2.0/go.mod h1:86WKkJHtRcv5ViNABtYMhhNWRrD1Vpi//uKEy7aYEfI= +cloud.google.com/go/cloudtasks v1.5.0/go.mod h1:fD92REy1x5woxkKEkLdvavGnPJGEn8Uic9nWuLzqCpY= +cloud.google.com/go/cloudtasks v1.6.0/go.mod h1:C6Io+sxuke9/KNRkbQpihnW93SWDU3uXt92nu85HkYI= +cloud.google.com/go/compute v0.1.0/go.mod h1:GAesmwr110a34z04OlxYkATPBEfVhkymfTBXtfbBFow= +cloud.google.com/go/compute v1.3.0/go.mod h1:cCZiE1NHEtai4wiufUhW8I8S1JKkAnhnQJWM7YD99wM= +cloud.google.com/go/compute v1.5.0/go.mod h1:9SMHyhJlzhlkJqrPAc839t2BZFTSk6Jdj6mkzQJeu0M= +cloud.google.com/go/compute v1.6.0/go.mod h1:T29tfhtVbq1wvAPo0E3+7vhgmkOYeXjhFvz/FMzPu0s= +cloud.google.com/go/compute v1.6.1/go.mod h1:g85FgpzFvNULZ+S8AYq87axRKuf2Kh7deLqV/jJ3thU= +cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQHHZWZxy9U= +cloud.google.com/go/compute v1.10.0/go.mod h1:ER5CLbMxl90o2jtNbGSbtfOpQKR0t15FOtRsugnLrlU= +cloud.google.com/go/compute v1.20.1 h1:6aKEtlUiwEpJzM001l0yFkpXmUVXaN8W+fbkb2AZNbg= +cloud.google.com/go/compute v1.20.1/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM= +cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= +cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= +cloud.google.com/go/containeranalysis v0.5.1/go.mod h1:1D92jd8gRR/c0fGMlymRgxWD3Qw9C1ff6/T7mLgVL8I= +cloud.google.com/go/containeranalysis v0.6.0/go.mod h1:HEJoiEIu+lEXM+k7+qLCci0h33lX3ZqoYFdmPcoO7s4= +cloud.google.com/go/datacatalog v1.3.0/go.mod h1:g9svFY6tuR+j+hrTw3J2dNcmI0dzmSiyOzm8kpLq0a0= +cloud.google.com/go/datacatalog v1.5.0/go.mod h1:M7GPLNQeLfWqeIm3iuiruhPzkt65+Bx8dAKvScX8jvs= +cloud.google.com/go/datacatalog v1.6.0/go.mod h1:+aEyF8JKg+uXcIdAmmaMUmZ3q1b/lKLtXCmXdnc0lbc= +cloud.google.com/go/dataflow v0.6.0/go.mod h1:9QwV89cGoxjjSR9/r7eFDqqjtvbKxAK2BaYU6PVk9UM= +cloud.google.com/go/dataflow v0.7.0/go.mod h1:PX526vb4ijFMesO1o202EaUmouZKBpjHsTlCtB4parQ= +cloud.google.com/go/dataform v0.3.0/go.mod h1:cj8uNliRlHpa6L3yVhDOBrUXH+BPAO1+KFMQQNSThKo= +cloud.google.com/go/dataform v0.4.0/go.mod h1:fwV6Y4Ty2yIFL89huYlEkwUPtS7YZinZbzzj5S9FzCE= +cloud.google.com/go/datalabeling v0.5.0/go.mod h1:TGcJ0G2NzcsXSE/97yWjIZO0bXj0KbVlINXMG9ud42I= +cloud.google.com/go/datalabeling v0.6.0/go.mod h1:WqdISuk/+WIGeMkpw/1q7bK/tFEZxsrFJOJdY2bXvTQ= +cloud.google.com/go/dataqna v0.5.0/go.mod h1:90Hyk596ft3zUQ8NkFfvICSIfHFh1Bc7C4cK3vbhkeo= +cloud.google.com/go/dataqna v0.6.0/go.mod h1:1lqNpM7rqNLVgWBJyk5NF6Uen2PHym0jtVJonplVsDA= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/datastream v1.2.0/go.mod h1:i/uTP8/fZwgATHS/XFu0TcNUhuA0twZxxQ3EyCUQMwo= +cloud.google.com/go/datastream v1.3.0/go.mod h1:cqlOX8xlyYF/uxhiKn6Hbv6WjwPPuI9W2M9SAXwaLLQ= +cloud.google.com/go/dialogflow v1.15.0/go.mod h1:HbHDWs33WOGJgn6rfzBW1Kv807BE3O1+xGbn59zZWI4= +cloud.google.com/go/dialogflow v1.16.1/go.mod h1:po6LlzGfK+smoSmTBnbkIZY2w8ffjz/RcGSS+sh1el0= +cloud.google.com/go/dialogflow v1.17.0/go.mod h1:YNP09C/kXA1aZdBgC/VtXX74G/TKn7XVCcVumTflA+8= +cloud.google.com/go/documentai v1.7.0/go.mod h1:lJvftZB5NRiFSX4moiye1SMxHx0Bc3x1+p9e/RfXYiU= +cloud.google.com/go/documentai v1.8.0/go.mod h1:xGHNEB7CtsnySCNrCFdCyyMz44RhFEEX2Q7UD0c5IhU= +cloud.google.com/go/domains v0.6.0/go.mod h1:T9Rz3GasrpYk6mEGHh4rymIhjlnIuB4ofT1wTxDeT4Y= +cloud.google.com/go/domains v0.7.0/go.mod h1:PtZeqS1xjnXuRPKE/88Iru/LdfoRyEHYA9nFQf4UKpg= +cloud.google.com/go/edgecontainer v0.1.0/go.mod h1:WgkZ9tp10bFxqO8BLPqv2LlfmQF1X8lZqwW4r1BTajk= +cloud.google.com/go/edgecontainer v0.2.0/go.mod h1:RTmLijy+lGpQ7BXuTDa4C4ssxyXT34NIuHIgKuP4s5w= +cloud.google.com/go/functions v1.6.0/go.mod h1:3H1UA3qiIPRWD7PeZKLvHZ9SaQhR26XIJcC0A5GbvAk= +cloud.google.com/go/functions v1.7.0/go.mod h1:+d+QBcWM+RsrgZfV9xo6KfA1GlzJfxcfZcRPEhDDfzg= +cloud.google.com/go/gaming v1.5.0/go.mod h1:ol7rGcxP/qHTRQE/RO4bxkXq+Fix0j6D4LFPzYTIrDM= +cloud.google.com/go/gaming v1.6.0/go.mod h1:YMU1GEvA39Qt3zWGyAVA9bpYz/yAhTvaQ1t2sK4KPUA= +cloud.google.com/go/gkeconnect v0.5.0/go.mod h1:c5lsNAg5EwAy7fkqX/+goqFsU1Da/jQFqArp+wGNr/o= +cloud.google.com/go/gkeconnect v0.6.0/go.mod h1:Mln67KyU/sHJEBY8kFZ0xTeyPtzbq9StAVvEULYK16A= +cloud.google.com/go/gkehub v0.9.0/go.mod h1:WYHN6WG8w9bXU0hqNxt8rm5uxnk8IH+lPY9J2TV7BK0= +cloud.google.com/go/gkehub v0.10.0/go.mod h1:UIPwxI0DsrpsVoWpLB0stwKCP+WFVG9+y977wO+hBH0= +cloud.google.com/go/grafeas v0.2.0/go.mod h1:KhxgtF2hb0P191HlY5besjYm6MqTSTj3LSI+M+ByZHc= +cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp4bnY= +cloud.google.com/go/iam v0.5.0/go.mod h1:wPU9Vt0P4UmCux7mqtRu6jcpPAb74cP1fh50J3QpkUc= +cloud.google.com/go/iam v1.1.0 h1:67gSqaPukx7O8WLLHMa0PNs3EBGd2eE4d+psbO/CO94= +cloud.google.com/go/iam v1.1.0/go.mod h1:nxdHjaKfCr7fNYx/HJMM8LgiMugmveWlkatear5gVyk= +cloud.google.com/go/language v1.4.0/go.mod h1:F9dRpNFQmJbkaop6g0JhSBXCNlO90e1KWx5iDdxbWic= +cloud.google.com/go/language v1.6.0/go.mod h1:6dJ8t3B+lUYfStgls25GusK04NLh3eDLQnWM3mdEbhI= +cloud.google.com/go/lifesciences v0.5.0/go.mod h1:3oIKy8ycWGPUyZDR/8RNnTOYevhaMLqh5vLUXs9zvT8= +cloud.google.com/go/lifesciences v0.6.0/go.mod h1:ddj6tSX/7BOnhxCSd3ZcETvtNr8NZ6t/iPhY2Tyfu08= +cloud.google.com/go/mediatranslation v0.5.0/go.mod h1:jGPUhGTybqsPQn91pNXw0xVHfuJ3leR1wj37oU3y1f4= +cloud.google.com/go/mediatranslation v0.6.0/go.mod h1:hHdBCTYNigsBxshbznuIMFNe5QXEowAuNmmC7h8pu5w= +cloud.google.com/go/memcache v1.4.0/go.mod h1:rTOfiGZtJX1AaFUrOgsMHX5kAzaTQ8azHiuDoTPzNsE= +cloud.google.com/go/memcache v1.5.0/go.mod h1:dk3fCK7dVo0cUU2c36jKb4VqKPS22BTkf81Xq617aWM= +cloud.google.com/go/metastore v1.5.0/go.mod h1:2ZNrDcQwghfdtCwJ33nM0+GrBGlVuh8rakL3vdPY3XY= +cloud.google.com/go/metastore v1.6.0/go.mod h1:6cyQTls8CWXzk45G55x57DVQ9gWg7RiH65+YgPsNh9s= +cloud.google.com/go/networkconnectivity v1.4.0/go.mod h1:nOl7YL8odKyAOtzNX73/M5/mGZgqqMeryi6UPZTk/rA= +cloud.google.com/go/networkconnectivity v1.5.0/go.mod h1:3GzqJx7uhtlM3kln0+x5wyFvuVH1pIBJjhCpjzSt75o= +cloud.google.com/go/networksecurity v0.5.0/go.mod h1:xS6fOCoqpVC5zx15Z/MqkfDwH4+m/61A3ODiDV1xmiQ= +cloud.google.com/go/networksecurity v0.6.0/go.mod h1:Q5fjhTr9WMI5mbpRYEbiexTzROf7ZbDzvzCrNl14nyU= +cloud.google.com/go/notebooks v1.2.0/go.mod h1:9+wtppMfVPUeJ8fIWPOq1UnATHISkGXGqTkxeieQ6UY= +cloud.google.com/go/notebooks v1.3.0/go.mod h1:bFR5lj07DtCPC7YAAJ//vHskFBxA5JzYlH68kXVdk34= +cloud.google.com/go/osconfig v1.7.0/go.mod h1:oVHeCeZELfJP7XLxcBGTMBvRO+1nQ5tFG9VQTmYS2Fs= +cloud.google.com/go/osconfig v1.8.0/go.mod h1:EQqZLu5w5XA7eKizepumcvWx+m8mJUhEwiPqWiZeEdg= +cloud.google.com/go/oslogin v1.4.0/go.mod h1:YdgMXWRaElXz/lDk1Na6Fh5orF7gvmJ0FGLIs9LId4E= +cloud.google.com/go/oslogin v1.5.0/go.mod h1:D260Qj11W2qx/HVF29zBg+0fd6YCSjSqLUkY/qEenQU= +cloud.google.com/go/phishingprotection v0.5.0/go.mod h1:Y3HZknsK9bc9dMi+oE8Bim0lczMU6hrX0UpADuMefr0= +cloud.google.com/go/phishingprotection v0.6.0/go.mod h1:9Y3LBLgy0kDTcYET8ZH3bq/7qni15yVUoAxiFxnlSUA= +cloud.google.com/go/privatecatalog v0.5.0/go.mod h1:XgosMUvvPyxDjAVNDYxJ7wBW8//hLDDYmnsNcMGq1K0= +cloud.google.com/go/privatecatalog v0.6.0/go.mod h1:i/fbkZR0hLN29eEWiiwue8Pb+GforiEIBnV9yrRUOKI= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/recaptchaenterprise v1.3.1/go.mod h1:OdD+q+y4XGeAlxRaMn1Y7/GveP6zmq76byL6tjPE7d4= +cloud.google.com/go/recaptchaenterprise/v2 v2.1.0/go.mod h1:w9yVqajwroDNTfGuhmOjPDN//rZGySaf6PtFVcSCa7o= +cloud.google.com/go/recaptchaenterprise/v2 v2.2.0/go.mod h1:/Zu5jisWGeERrd5HnlS3EUGb/D335f9k51B/FVil0jk= +cloud.google.com/go/recaptchaenterprise/v2 v2.3.0/go.mod h1:O9LwGCjrhGHBQET5CA7dd5NwwNQUErSgEDit1DLNTdo= +cloud.google.com/go/recommendationengine v0.5.0/go.mod h1:E5756pJcVFeVgaQv3WNpImkFP8a+RptV6dDLGPILjvg= +cloud.google.com/go/recommendationengine v0.6.0/go.mod h1:08mq2umu9oIqc7tDy8sx+MNJdLG0fUi3vaSVbztHgJ4= +cloud.google.com/go/recommender v1.5.0/go.mod h1:jdoeiBIVrJe9gQjwd759ecLJbxCDED4A6p+mqoqDvTg= +cloud.google.com/go/recommender v1.6.0/go.mod h1:+yETpm25mcoiECKh9DEScGzIRyDKpZ0cEhWGo+8bo+c= +cloud.google.com/go/redis v1.7.0/go.mod h1:V3x5Jq1jzUcg+UNsRvdmsfuFnit1cfe3Z/PGyq/lm4Y= +cloud.google.com/go/redis v1.8.0/go.mod h1:Fm2szCDavWzBk2cDKxrkmWBqoCiL1+Ctwq7EyqBCA/A= +cloud.google.com/go/retail v1.8.0/go.mod h1:QblKS8waDmNUhghY2TI9O3JLlFk8jybHeV4BF19FrE4= +cloud.google.com/go/retail v1.9.0/go.mod h1:g6jb6mKuCS1QKnH/dpu7isX253absFl6iE92nHwlBUY= +cloud.google.com/go/scheduler v1.4.0/go.mod h1:drcJBmxF3aqZJRhmkHQ9b3uSSpQoltBPGPxGAWROx6s= +cloud.google.com/go/scheduler v1.5.0/go.mod h1:ri073ym49NW3AfT6DZi21vLZrG07GXr5p3H1KxN5QlI= +cloud.google.com/go/secretmanager v1.6.0/go.mod h1:awVa/OXF6IiyaU1wQ34inzQNc4ISIDIrId8qE5QGgKA= +cloud.google.com/go/security v1.5.0/go.mod h1:lgxGdyOKKjHL4YG3/YwIL2zLqMFCKs0UbQwgyZmfJl4= +cloud.google.com/go/security v1.7.0/go.mod h1:mZklORHl6Bg7CNnnjLH//0UlAlaXqiG7Lb9PsPXLfD0= +cloud.google.com/go/security v1.8.0/go.mod h1:hAQOwgmaHhztFhiQ41CjDODdWP0+AE1B3sX4OFlq+GU= +cloud.google.com/go/securitycenter v1.13.0/go.mod h1:cv5qNAqjY84FCN6Y9z28WlkKXyWsgLO832YiWwkCWcU= +cloud.google.com/go/securitycenter v1.14.0/go.mod h1:gZLAhtyKv85n52XYWt6RmeBdydyxfPeTrpToDPw4Auc= +cloud.google.com/go/servicedirectory v1.4.0/go.mod h1:gH1MUaZCgtP7qQiI+F+A+OpeKF/HQWgtAddhTbhL2bs= +cloud.google.com/go/servicedirectory v1.5.0/go.mod h1:QMKFL0NUySbpZJ1UZs3oFAmdvVxhhxB6eJ/Vlp73dfg= +cloud.google.com/go/speech v1.6.0/go.mod h1:79tcr4FHCimOp56lwC01xnt/WPJZc4v3gzyT7FoBkCM= +cloud.google.com/go/speech v1.7.0/go.mod h1:KptqL+BAQIhMsj1kOP2la5DSEEerPDuOP/2mmkhHhZQ= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= +cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq6kuBTW58Y= +cloud.google.com/go/storage v1.23.0/go.mod h1:vOEEDNFnciUMhBeT6hsJIn3ieU5cFRmzeLgDvXzfIXc= +cloud.google.com/go/storage v1.27.0/go.mod h1:x9DOL8TK/ygDUMieqwfhdpQryTeEkhGKMi80i/iqR2s= +cloud.google.com/go/storage v1.30.1 h1:uOdMxAs8HExqBlnLtnQyP0YkvbiDpdGShGKtx6U/oNM= +cloud.google.com/go/storage v1.30.1/go.mod h1:NfxhC0UJE1aXSx7CIIbCf7y9HKT7BiccwkR7+P7gN8E= +cloud.google.com/go/talent v1.1.0/go.mod h1:Vl4pt9jiHKvOgF9KoZo6Kob9oV4lwd/ZD5Cto54zDRw= +cloud.google.com/go/talent v1.2.0/go.mod h1:MoNF9bhFQbiJ6eFD3uSsg0uBALw4n4gaCaEjBw9zo8g= +cloud.google.com/go/videointelligence v1.6.0/go.mod h1:w0DIDlVRKtwPCn/C4iwZIJdvC69yInhW0cfi+p546uU= +cloud.google.com/go/videointelligence v1.7.0/go.mod h1:k8pI/1wAhjznARtVT9U1llUaFNPh7muw8QyOUpavru4= +cloud.google.com/go/vision v1.2.0/go.mod h1:SmNwgObm5DpFBme2xpyOyasvBc1aPdjvMk2bBk0tKD0= +cloud.google.com/go/vision/v2 v2.2.0/go.mod h1:uCdV4PpN1S0jyCyq8sIM42v2Y6zOLkZs+4R9LrGYwFo= +cloud.google.com/go/vision/v2 v2.3.0/go.mod h1:UO61abBx9QRMFkNBbf1D8B1LXdS2cGiiCRx0vSpZoUo= +cloud.google.com/go/webrisk v1.4.0/go.mod h1:Hn8X6Zr+ziE2aNd8SliSDWpEnSS1u4R9+xXZmFiHmGE= +cloud.google.com/go/webrisk v1.5.0/go.mod h1:iPG6fr52Tv7sGk0H6qUFzmL3HHZev1htXuWDEEsqMTg= +cloud.google.com/go/workflows v1.6.0/go.mod h1:6t9F5h/unJz41YqfBmqSASJSXccBLtD1Vwf+KmJENM0= +cloud.google.com/go/workflows v1.7.0/go.mod h1:JhSrZuVZWuiDfKEFxU0/F1PQjmpnpcoISEXH2bcHC3M= +cosmossdk.io/api v0.3.1 h1:NNiOclKRR0AOlO4KIqeaG6PS6kswOMhHD0ir0SscNXE= +cosmossdk.io/api v0.3.1/go.mod h1:DfHfMkiNA2Uhy8fj0JJlOCYOBp4eWUUJ1te5zBGNyIw= +cosmossdk.io/core v0.6.1 h1:OBy7TI2W+/gyn2z40vVvruK3di+cAluinA6cybFbE7s= +cosmossdk.io/core v0.6.1/go.mod h1:g3MMBCBXtxbDWBURDVnJE7XML4BG5qENhs0gzkcpuFA= +cosmossdk.io/depinject v1.0.0-alpha.3 h1:6evFIgj//Y3w09bqOUOzEpFj5tsxBqdc5CfkO7z+zfw= +cosmossdk.io/depinject v1.0.0-alpha.3/go.mod h1:eRbcdQ7MRpIPEM5YUJh8k97nxHpYbc3sMUnEtt8HPWU= +cosmossdk.io/errors v1.0.0 h1:nxF07lmlBbB8NKQhtJ+sJm6ef5uV1XkvPXG2bUntb04= +cosmossdk.io/errors v1.0.0/go.mod h1:+hJZLuhdDE0pYN8HkOrVNwrIOYvUGnn6+4fjnJs/oV0= +cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca h1:msenprh2BLLRwNT7zN56TbBHOGk/7ARQckXHxXyvjoQ= +cosmossdk.io/log v1.1.1-0.20230704160919-88f2c830b0ca/go.mod h1:PkIAKXZvaxrTRc++z53XMRvFk8AcGGWYHcMIPzVYX9c= +cosmossdk.io/math v1.0.1 h1:Qx3ifyOPaMLNH/89WeZFH268yCvU4xEcnPLu3sJqPPg= +cosmossdk.io/math v1.0.1/go.mod h1:Ygz4wBHrgc7g0N+8+MrnTfS9LLn9aaTGa9hKopuym5k= +cosmossdk.io/tools/rosetta v0.2.1 h1:ddOMatOH+pbxWbrGJKRAawdBkPYLfKXutK9IETnjYxw= +cosmossdk.io/tools/rosetta v0.2.1/go.mod h1:Pqdc1FdvkNV3LcNIkYWt2RQY6IP1ge6YWZk8MhhO9Hw= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= +filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= +github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= +github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= +github.com/99designs/keyring v1.2.2 h1:pZd3neh/EmUzWONb35LxQfvuY7kiSXAq3HQd97+XBn0= +github.com/99designs/keyring v1.2.2/go.mod h1:wes/FrByc8j7lFOAGLGSNEg8f/PaI3cgTBqhFkHUrPk= +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= +github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +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= +github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d/go.mod h1:URdX5+vg25ts3aCh8H5IFZybJYKWhJHYMTnf+ULtoC4= +github.com/ChainSafe/go-schnorrkel v1.0.0 h1:3aDA67lAykLaG1y3AOjs88dMxC88PgUuHRrLeDnvGIM= +github.com/ChainSafe/go-schnorrkel v1.0.0/go.mod h1:dpzHYVxLZcp8pjlV+O+UR8K0Hp/z7vcchBSbMBEhCw4= +github.com/ComposableFi/go-subkey/v2 v2.0.0-tm03420 h1:oknQF/iIhf5lVjbwjsVDzDByupRhga8nhA3NAmwyHDA= +github.com/ComposableFi/go-subkey/v2 v2.0.0-tm03420/go.mod h1:KYkiMX5AbOlXXYfxkrYPrRPV6EbVUALTQh5ptUOJzu8= +github.com/CosmWasm/wasmd v0.41.0 h1:fmwxSbwb50zZDcBaayYFRLIaSFca+EFld1WOaQi49jg= +github.com/CosmWasm/wasmd v0.41.0/go.mod h1:0Sds1q2IsPaTN1gHa3BNOYcUFgtGvxH7CXEXPgoihns= +github.com/CosmWasm/wasmvm v1.3.0 h1:x12X4bKlUPS7TT9QQP45+fJo2sp30GEbiSSgb9jsec8= +github.com/CosmWasm/wasmvm v1.3.0/go.mod h1:vW/E3h8j9xBQs9bCoijDuawKo9kCtxOaS8N8J7KFtkc= +github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= +github.com/FactomProject/basen v0.0.0-20150613233007-fe3947df716e h1:ahyvB3q25YnZWly5Gq1ekg6jcmWaGj/vG/MhF4aisoc= +github.com/FactomProject/basen v0.0.0-20150613233007-fe3947df716e/go.mod h1:kGUqhHd//musdITWjFvNTHn90WG9bMLBEPQZ17Cmlpw= +github.com/FactomProject/btcutilecc v0.0.0-20130527213604-d3a63a5752ec h1:1Qb69mGp/UtRPn422BH4/Y4Q3SLUrD9KHuDkm8iodFc= +github.com/FactomProject/btcutilecc v0.0.0-20130527213604-d3a63a5752ec/go.mod h1:CD8UlnlLDiqb36L110uqiP2iSflVjx9g/3U9hCI4q2U= +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.0/go.mod h1:cTAf44im0RAYeL23bpB+fzCyDH2MJiz2BO69KH/soAE= +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= +github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= +github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= +github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6 h1:fLjPD/aNc3UIOA6tDi6QXUemppXK3P9BI7mr2hd6gx8= +github.com/StirlingMarketingGroup/go-namecase v1.0.0 h1:2CzaNtCzc4iNHirR+5ru9OzGg8rQp860gqLBFqRI02Y= +github.com/StirlingMarketingGroup/go-namecase v1.0.0/go.mod h1:ZsoSKcafcAzuBx+sndbxHu/RjDcDTrEdT4UvhniHfio= +github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= +github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= +github.com/adlio/schema v1.3.3 h1:oBJn8I02PyTB466pZO1UZEn1TV5XLlifBSyMrmHl/1I= +github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= +github.com/alecthomas/participle/v2 v2.0.0-alpha7 h1:cK4vjj0VSgb3lN1nuKA5F7dw+1s1pWBe5bx7nNCnN+c= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= +github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA= +github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4= +github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= +github.com/avast/retry-go/v4 v4.3.4 h1:pHLkL7jvCvP317I8Ge+Km2Yhntv3SdkJm7uekkqbKhM= +github.com/avast/retry-go/v4 v4.3.4/go.mod h1:rv+Nla6Vk3/ilU0H51VHddWHiwimzX66yZ0JT6T+UvE= +github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= +github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go v1.44.122/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= +github.com/aws/aws-sdk-go v1.44.203 h1:pcsP805b9acL3wUqa4JR2vg1k2wnItkDYNvfmcy6F+U= +github.com/aws/aws-sdk-go v1.44.203/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= +github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= +github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A= +github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= +github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= +github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 h1:41iFGWnSlI2gVpmOtVTJZNodLdLQLn/KsJqFvXwnd/s= +github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/btcsuite/btcd/btcec/v2 v2.3.2 h1:5n0X6hX0Zk+6omWcihdYvdAlGf2DfasC0GMf7DClJ3U= +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/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce h1:YtWJF7RHm2pYCvA5t0RPmAaLUhREsKuKd+SLhxFbFeQ= +github.com/bufbuild/protocompile v0.4.0 h1:LbFKd2XowZvQ/kajzguUp2DC9UEIQhIq77fZZlaQsNA= +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= +github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= +github.com/cenkalti/backoff/v4 v4.1.3 h1:cFAlzYUlVYDysBEH2T5hyJZMh3+5+WCBvSnK6Q8UtC4= +github.com/cenkalti/backoff/v4 v4.1.3/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM= +github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= +github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= +github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= +github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= +github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= +github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cmars/basen v0.0.0-20150613233007-fe3947df716e h1:0XBUw73chJ1VYSsfvcPvVT7auykAJce9FpRr10L6Qhw= +github.com/cmars/basen v0.0.0-20150613233007-fe3947df716e/go.mod h1:P13beTBKr5Q18lJe1rIoLUqjM+CB1zYrRg44ZqGuQSA= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cockroachdb/apd/v2 v2.0.2 h1:weh8u7Cneje73dDh+2tEVLUvyBc89iwepWCD8b8034E= +github.com/cockroachdb/apd/v3 v3.1.0 h1:MK3Ow7LH0W8zkd5GMKA1PvS9qG3bWFI95WaVNfyZJ/w= +github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= +github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= +github.com/coinbase/rosetta-sdk-go/types v1.0.0 h1:jpVIwLcPoOeCR6o1tU+Xv7r5bMONNbHU7MuEHboiFuA= +github.com/coinbase/rosetta-sdk-go/types v1.0.0/go.mod h1:eq7W2TMRH22GTW0N0beDnN931DW0/WOI1R2sdHNHG4c= +github.com/cometbft/cometbft v0.37.2 h1:XB0yyHGT0lwmJlFmM4+rsRnczPlHoAKFX6K8Zgc2/Jc= +github.com/cometbft/cometbft v0.37.2/go.mod h1:Y2MMMN//O5K4YKd8ze4r9jmk4Y7h0ajqILXbH5JQFVs= +github.com/cometbft/cometbft-db v0.8.0 h1:vUMDaH3ApkX8m0KZvOFFy9b5DZHBAjsnEuo9AKVZpjo= +github.com/cometbft/cometbft-db v0.8.0/go.mod h1:6ASCP4pfhmrCBpfk01/9E1SI29nD3HfVHrY4PG8x5c0= +github.com/confio/ics23/go v0.9.0 h1:cWs+wdbS2KRPZezoaaj+qBleXgUk5WOQFMP3CQFGTr4= +github.com/confio/ics23/go v0.9.0/go.mod h1:4LPZ2NYqnYIVRklaozjNR1FScgDJ2s5Xrp+e/mYVRak= +github.com/containerd/continuity v0.3.0 h1:nisirsYROK15TAMVukJOUyGJjz4BNQJBVsNvAXZJ/eg= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/cosmos/btcutil v1.0.5 h1:t+ZFcX77LpKtDBhjucvnOH8C2l2ioGsBNEQ3jef8xFk= +github.com/cosmos/btcutil v1.0.5/go.mod h1:IyB7iuqZMJlthe2tkIFL33xPyzbFYP0XVdS8P5lUPis= +github.com/cosmos/cosmos-proto v1.0.0-beta.3 h1:VitvZ1lPORTVxkmF2fAp3IiA61xVwArQYKXTdEcpW6o= +github.com/cosmos/cosmos-proto v1.0.0-beta.3/go.mod h1:t8IASdLaAq+bbHbjq4p960BvcTqtwuAxid3b/2rOD6I= +github.com/cosmos/cosmos-sdk v0.47.4 h1:FVUpEprm58nMmBX4xkRdMDaIG5Nr4yy92HZAfGAw9bg= +github.com/cosmos/cosmos-sdk v0.47.4/go.mod h1:R5n+uM7vguVPFap4pgkdvQCT1nVo/OtPwrlAU40rvok= +github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= +github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY= +github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw= +github.com/cosmos/gogogateway v1.2.0 h1:Ae/OivNhp8DqBi/sh2A8a1D0y638GpL3tkmLQAiKxTE= +github.com/cosmos/gogogateway v1.2.0/go.mod h1:iQpLkGWxYcnCdz5iAdLcRBSw3h7NXeOkZ4GUkT+tbFI= +github.com/cosmos/gogoproto v1.4.2/go.mod h1:cLxOsn1ljAHSV527CHOtaIP91kK6cCrZETRBrkzItWU= +github.com/cosmos/gogoproto v1.4.10 h1:QH/yT8X+c0F4ZDacDv3z+xE3WU1P1Z3wQoLMBRJoKuI= +github.com/cosmos/gogoproto v1.4.10/go.mod h1:3aAZzeRWpAwr+SS/LLkICX2/kDFyaYVzckBDzygIxek= +github.com/cosmos/iavl v0.20.0 h1:fTVznVlepH0KK8NyKq8w+U7c2L6jofa27aFX6YGlm38= +github.com/cosmos/iavl v0.20.0/go.mod h1:WO7FyvaZJoH65+HFOsDir7xU9FWk2w9cHXNW1XHcl7A= +github.com/cosmos/ibc-go/v7 v7.2.0 h1:dx0DLUl7rxdyZ8NiT6UsrbzKOJx/w7s+BOaewFRH6cg= +github.com/cosmos/ibc-go/v7 v7.2.0/go.mod h1:OOcjKIRku/j1Xs1RgKK0yvKRrJ5iFuZYMetR1n3yMlc= +github.com/cosmos/ics23/go v0.10.0 h1:iXqLLgp2Lp+EdpIuwXTYIQU+AiHj9mOC2X9ab++bZDM= +github.com/cosmos/ics23/go v0.10.0/go.mod h1:ZfJSmng/TBNTBkFemHHHj5YY7VAU/MBU980F4VU1NG0= +github.com/cosmos/ledger-cosmos-go v0.12.2 h1:/XYaBlE2BJxtvpkHiBm97gFGSGmYGKunKyF3nNqAXZA= +github.com/cosmos/ledger-cosmos-go v0.12.2/go.mod h1:ZcqYgnfNJ6lAXe4HPtWgarNEY+B74i+2/8MhZw4ziiI= +github.com/cosmos/rosetta-sdk-go v0.10.0 h1:E5RhTruuoA7KTIXUcMicL76cffyeoyvNybzUGSKFTcM= +github.com/cosmos/rosetta-sdk-go v0.10.0/go.mod h1:SImAZkb96YbwvoRkzSMQB6noNJXFgWl/ENIznEoYQI4= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/creachadair/taskgroup v0.4.2 h1:jsBLdAJE42asreGss2xZGZ8fJra7WtwnHWeJFxv2Li8= +github.com/creachadair/taskgroup v0.4.2/go.mod h1:qiXUOSrbwAY3u0JPGTzObbE3yf9hcXHDKBZ2ZjpCbgM= +github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= +github.com/cucumber/common/gherkin/go/v22 v22.0.0 h1:4K8NqptbvdOrjL9DEea6HFjSpbdT9+Q5kgLpmmsHYl0= +github.com/cucumber/common/messages/go/v17 v17.1.1 h1:RNqopvIFyLWnKv0LfATh34SWBhXeoFTJnSrgm9cT/Ts= +github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= +github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/deckarep/golang-set v1.8.0 h1:sk9/l/KqpunDwP7pSjUg0keiOOLEnOBHzykLrsPppp4= +github.com/deckarep/golang-set v1.8.0/go.mod h1:5nI87KwE7wgsBU1F4GKAw2Qod7p5kyS383rP6+o6qqo= +github.com/deckarep/golang-set/v2 v2.1.0 h1:g47V4Or+DUdzbs8FxCCmgb6VYd+ptPAngjM6dtGktsI= +github.com/decred/base58 v1.0.4 h1:QJC6B0E0rXOPA8U/kw2rP+qiRJsUaE2Er+pYb3siUeA= +github.com/decred/base58 v1.0.4/go.mod h1:jJswKPEdvpFpvf7dsDvFZyLT22xZ9lWqEByX38oGd9E= +github.com/decred/dcrd/chaincfg/chainhash v1.0.2 h1:rt5Vlq/jM3ZawwiacWjPa+smINyLRN07EO0cNBV6DGU= +github.com/decred/dcrd/chaincfg/chainhash v1.0.2/go.mod h1:BpbrGgrPTr3YJYRN3Bm+D9NuaFd+zGyNeIKgrhCXK60= +github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= +github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= +github.com/decred/dcrd/dcrec/secp256k1/v2 v2.0.1 h1:18HurQ6DfHeNvwIjvOmrgr44bPdtVaQAe/WWwHg9goM= +github.com/decred/dcrd/dcrec/secp256k1/v2 v2.0.1/go.mod h1:XmyzkaXBy7ZvHdrTAlXAjpog8qKSAWa3ze7yqzWmgmc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f h1:U5y3Y5UE0w7amNe7Z5G/twsBW0KEalRQXZzf8ufSh9I= +github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f/go.mod h1:xH/i4TFMt8koVQZ6WFms69WAsDWr2XsYL3Hkl7jkoLE= +github.com/dgraph-io/badger/v2 v2.2007.4 h1:TRWBQg8UrlUhaFdco01nO2uXwzKS7zd+HVdwV/GHc4o= +github.com/dgraph-io/badger/v2 v2.2007.4/go.mod h1:vSw/ax2qojzbN6eXHIx6KPKtCSHJN/Uz0X0VPruTIhk= +github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= +github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= +github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/docker/distribution v2.8.2+incompatible h1:T3de5rq0dB1j30rp0sA2rER+m322EBzniBPB6ZIzuh8= +github.com/docker/distribution v2.8.2+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v24.0.4+incompatible h1:s/LVDftw9hjblvqIeTiGYXBCD95nOEEl7qRsRrIOuQI= +github.com/docker/docker v24.0.4+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/dvsekhvalnov/jose2go v1.5.0 h1:3j8ya4Z4kMCwT5nXIKFSV84YS+HdqSSO0VsTQxaLAeM= +github.com/dvsekhvalnov/jose2go v1.5.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU= +github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= +github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= +github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= +github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/ethereum/go-ethereum v1.11.6 h1:2VF8Mf7XiSUfmoNOy3D+ocfl9Qu8baQBrCNbo2CXQ8E= +github.com/ethereum/go-ethereum v1.11.6/go.mod h1:+a8pUj1tOyJ2RinsNQD4326YS+leSoKGiG/uVVb0x6Y= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/felixge/httpsnoop v1.0.2 h1:+nS9g82KMXccJ/wp0zyRW9ZBHFETmMGtkk+2CTTrW4o= +github.com/felixge/httpsnoop v1.0.2/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= +github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= +github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= +github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= +github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= +github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14= +github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= +github.com/go-kit/kit v0.12.0 h1:e4o3o3IsBfAKQh5Qbbiqyfu97Ku7jrO/JbohvztANh4= +github.com/go-kit/kit v0.12.0/go.mod h1:lHd+EkCZPIwYItmGDDRdhinkzX2A1sj+M9biaEaizzs= +github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU= +github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= +github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= +github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho= +github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= +github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= +github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw= +github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= +github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8= +github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo= +github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0= +github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gofrs/uuid v4.3.0+incompatible h1:CaSVZxm5B+7o45rtab4jC2G37WGYX1zQfuU2i6DSvnc= +github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= +github.com/gogo/googleapis v1.4.1-0.20201022092350-68b0159b7869/go.mod h1:5YRNX2z1oM5gXdAkurHa942MDgEJyk02w4OecKY87+c= +github.com/gogo/googleapis v1.4.1 h1:1Yx4Myt7BxzvUr5ldGSbwYiZG6t9wGBZ+8/fX3Wvtq0= +github.com/gogo/googleapis v1.4.1/go.mod h1:2lpHqI5OcWCtVElxXnPt+s8oJvMpySlOyM6xDCrzib4= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/glog v1.1.0 h1:/d3pCKDPWNnvIWe0vVUpNP32qc8U3PDVxySP/y360qE= +github.com/golang/glog v1.1.0/go.mod h1:pfYeQZ3JWZoXTV5sFc986z3HTpwQs9At6P4ImfuP3NQ= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= +github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk= +github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= +github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.2.1/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= +github.com/google/martian/v3 v3.3.2 h1:IqNFLAmvJOgVlpdEBiQbDc2EwKW77amAycfTuWKdfvw= +github.com/google/orderedcode v0.0.1 h1:UzfcAexk9Vhv8+9pNOgRu41f16lHq725vPwnSeiG/Us= +github.com/google/orderedcode v0.0.1/go.mod h1:iVyU4/qPKHY5h/wSd6rZZCDcLJNxiWO6dvsYES2Sb20= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/s2a-go v0.1.4 h1:1kZ/sQM3srePvKs3tXAvQzo66XfcReoqFpIpIccE7Oc= +github.com/google/s2a-go v0.1.4/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= +github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.0.0-20220520183353-fd19c99a87aa/go.mod h1:17drOmN3MwGY7t0e+Ei9b45FFGA3fBs3x36SsCg1hq8= +github.com/googleapis/enterprise-certificate-proxy v0.1.0/go.mod h1:17drOmN3MwGY7t0e+Ei9b45FFGA3fBs3x36SsCg1hq8= +github.com/googleapis/enterprise-certificate-proxy v0.2.0/go.mod h1:8C0jb7/mgJe/9KK8Lm7X9ctZC2t60YyIpYEI16jx0Qg= +github.com/googleapis/enterprise-certificate-proxy v0.2.3 h1:yk9/cqRKtT9wXZSsRH9aurXEpJX+U6FLtpYTdC3R06k= +github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= +github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM= +github.com/googleapis/gax-go/v2 v2.2.0/go.mod h1:as02EH8zWkzwUoLbBaFeQ+arQaj/OthfcblKl4IGNaM= +github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99EXz9pXxye9YM= +github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK9wbMD5+iXC6c= +github.com/googleapis/gax-go/v2 v2.5.1/go.mod h1:h6B0KMMFNtI2ddbGJn3T3ZbwkeT6yqEF02fYlzkUCyo= +github.com/googleapis/gax-go/v2 v2.6.0/go.mod h1:1mjbznJAPHFpesgE5ucqfYEscaz5kMdcIDwU/6+DDoY= +github.com/googleapis/gax-go/v2 v2.11.0 h1:9V9PWXEsWnPpQhu/PeQIkS4eGzMlTLGgt80cUUI8Ki4= +github.com/googleapis/gax-go/v2 v2.11.0/go.mod h1:DxmR61SGKkGLa2xigwuZIQpkCI2S5iydzRfb3peWZJI= +github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= +github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= +github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= +github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= +github.com/grpc-ecosystem/go-grpc-middleware v1.3.0 h1:+9834+KizmvFV7pXQGSXQTsaWhq2GjuNUt0aUU0YBYw= +github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= +github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= +github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= +github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= +github.com/gtank/merlin v0.1.1 h1:eQ90iG7K9pOhtereWsmyRJ6RAwcP4tHTDBHXNg+u5is= +github.com/gtank/merlin v0.1.1/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= +github.com/gtank/ristretto255 v0.1.2 h1:JEqUCPA1NvLq5DwYtuzigd7ss8fwbYay9fi4/5uMzcc= +github.com/gtank/ristretto255 v0.1.2/go.mod h1:Ph5OpO6c7xKUGROZfWVLiJf9icMDwUeIvY4OmlYW69o= +github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= +github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-getter v1.7.1 h1:SWiSWN/42qdpR0MdhaOc/bLR48PLuP1ZQtYLRlM69uY= +github.com/hashicorp/go-getter v1.7.1/go.mod h1:W7TalhMmbPmsSMdNjD0ZskARur/9GJ17cfHTRtXV744= +github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc= +github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= +github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= +github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= +github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= +github.com/hashicorp/go-safetemp v1.0.0/go.mod h1:oaerMy3BhqiTbVye6QuFhFtIceqFoDHxNAB65b+Rj1I= +github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= +github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= +github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= +github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go-version v1.6.0 h1:feTTfFNnjP967rlCxM/I9g701jU+RN74YKx2mOkIeek= +github.com/hashicorp/go-version v1.6.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d h1:dg1dEPuWpEqDnvIw251EVy4zlP8gWbsGj4BsUKCRpYs= +github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= +github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= +github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/hdevalence/ed25519consensus v0.1.0 h1:jtBwzzcHuTmFrQN6xQZn6CQEO/V9f7HsjsjeEZ6auqU= +github.com/hdevalence/ed25519consensus v0.1.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo= +github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c h1:DZfsyhDK1hnSS5lH8l+JggqzEleHteTYfutAiVlSUM8= +github.com/holiman/uint256 v1.2.2-0.20230321075855-87b91420868c/go.mod h1:SC8Ryt4n+UBbPbIBKaG9zbbDlp4jOru9xFZmPzLUTxw= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/huandu/go-assert v1.1.5 h1:fjemmA7sSfYHJD7CUqs9qTwwfdNAx7/j2/ZlHXzNB3c= +github.com/huandu/go-assert v1.1.5/go.mod h1:yOLvuqZwmcHIC5rIzrBhT7D3Q9c3GFnd0JrPVhn/06U= +github.com/huandu/skiplist v1.2.0 h1:gox56QD77HzSC0w+Ws3MH3iie755GBJU1OER3h5VsYw= +github.com/huandu/skiplist v1.2.0/go.mod h1:7v3iFjLcSAzO4fN5B8dvebvo/qsfumiLiDXMrPiHF9w= +github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/icza/dyno v0.0.0-20220812133438-f0b6f8a18845 h1:H+uM0Bv88eur3ZSsd2NGKg3YIiuXxwxtlN7HjE66UTU= +github.com/icza/dyno v0.0.0-20220812133438-f0b6f8a18845/go.mod h1:c1tRKs5Tx7E2+uHGSyyncziFjvGpgv4H2HrqXeUQ/Uk= +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.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= +github.com/ipfs/go-cid v0.2.0 h1:01JTiihFq9en9Vz0lc0VDWvZe/uBonGpzo4THP0vcQ0= +github.com/ipfs/go-cid v0.2.0/go.mod h1:P+HXFDF4CVhaVayiEb4wkAy7zBHxBwsJyt0Y5U6MLro= +github.com/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= +github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= +github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +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/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU= +github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +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= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= +github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= +github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8= +github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= +github.com/libp2p/go-libp2p v0.22.0 h1:2Tce0kHOp5zASFKJbNzRElvh0iZwdtG5uZheNW8chIw= +github.com/libp2p/go-libp2p v0.22.0/go.mod h1:UDolmweypBSjQb2f7xutPnwZ/fxioLbMBxSjRksxxU4= +github.com/libp2p/go-openssl v0.1.0 h1:LBkKEcUv6vtZIQLVTegAil8jbNpJErQ9AnT+bWV+Ooo= +github.com/libp2p/go-openssl v0.1.0/go.mod h1:OiOxwPpL3n4xlenjx2h7AwSGaFSC/KZvf6gNdOBQMtc= +github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= +github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= +github.com/linxGnu/grocksdb v1.7.16 h1:Q2co1xrpdkr5Hx3Fp+f+f7fRGhQFQhvi/+226dtLmA8= +github.com/linxGnu/grocksdb v1.7.16/go.mod h1:JkS7pl5qWpGpuVb3bPqTz8nC12X3YtPZT+Xq7+QfQo4= +github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= +github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA= +github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg= +github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-pointer v0.0.1 h1:n+XhsuGeVO6MEAp7xyEukFINEa+Quek5psIR/ylA6o0= +github.com/mattn/go-pointer v0.0.1/go.mod h1:2zXcozF6qYGgmsG+SeTZz3oAbFLdD3OWqnUbNvJZAlc= +github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= +github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= +github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= +github.com/mimoo/StrobeGo v0.0.0-20220103164710-9a04d6ca976b h1:QrHweqAtyJ9EwCaGHBu1fghwxIPiopAHV06JlXrMHjk= +github.com/mimoo/StrobeGo v0.0.0-20220103164710-9a04d6ca976b/go.mod h1:xxLb2ip6sSUts3g1irPVHyk/DGslwQsNOo9I7smJfNU= +github.com/minio/highwayhash v1.0.2 h1:Aak5U0nElisjDCfPSG79Tgzkn2gl66NxOMspRrKnA/g= +github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= +github.com/minio/sha256-simd v1.0.0 h1:v1ta+49hkWZyvaKwrQB8elexRqm6Y0aMLjCNsrYxo6g= +github.com/minio/sha256-simd v1.0.0/go.mod h1:OuYzVNI5vcoYIAmbIvHPl3N3jUzVedXbKy5RFepssQM= +github.com/misko9/go-substrate-rpc-client/v4 v4.0.0-20230413215336-5bd2aea337ae h1:ZYbJh4TLwfSuSQe6DT/1982SfNNBcmvzrX5FycfSrmo= +github.com/misko9/go-substrate-rpc-client/v4 v4.0.0-20230413215336-5bd2aea337ae/go.mod h1:XexEkZgpnQ3sqUYz84DFoVUcDake6G/tYHrwdbdERhM= +github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= +github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= +github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= +github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= +github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= +github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= +github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/moby/term v0.0.0-20220808134915-39b0c02b01ae h1:O4SWKdcHVCvYqyDV+9CJA1fcDN2L11Bule0iFy3YlAI= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o= +github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc= +github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs= +github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns= +github.com/multiformats/go-base32 v0.0.4 h1:+qMh4a2f37b4xTNs6mqitDinryCI+tfO2dRVMN9mjSE= +github.com/multiformats/go-base32 v0.0.4/go.mod h1:jNLFzjPZtp3aIARHbJRZIaPuspdH0J6q39uUM5pnABM= +github.com/multiformats/go-base36 v0.1.0 h1:JR6TyF7JjGd3m6FbLU2cOxhC0Li8z8dLNGQ89tUg4F4= +github.com/multiformats/go-base36 v0.1.0/go.mod h1:kFGE83c6s80PklsHO9sRn2NCoffoRdUUOENyW/Vv6sM= +github.com/multiformats/go-multiaddr v0.6.0 h1:qMnoOPj2s8xxPU5kZ57Cqdr0hHhARz7mFsPMIiYNqzg= +github.com/multiformats/go-multiaddr v0.6.0/go.mod h1:F4IpaKZuPP360tOMn2Tpyu0At8w23aRyVqeK0DbFeGM= +github.com/multiformats/go-multibase v0.1.1 h1:3ASCDsuLX8+j4kx58qnJ4YFq/JWTJpCyDW27ztsVTOI= +github.com/multiformats/go-multibase v0.1.1/go.mod h1:ZEjHE+IsUrgp5mhlEAYjMtZwK1k4haNkcaPg9aoe1a8= +github.com/multiformats/go-multicodec v0.5.0 h1:EgU6cBe/D7WRwQb1KmnBvU7lrcFGMggZVTPtOW9dDHs= +github.com/multiformats/go-multicodec v0.5.0/go.mod h1:DiY2HFaEp5EhEXb/iYzVAunmyX/aSFMxq2KMKfWEues= +github.com/multiformats/go-multihash v0.2.1 h1:aem8ZT0VA2nCHHk7bPJ1BjUbHNciqZC/d16Vve9l108= +github.com/multiformats/go-multihash v0.2.1/go.mod h1:WxoMcYG85AZVQUyRyo9s4wULvW5qrI9vb2Lt6evduFc= +github.com/multiformats/go-varint v0.0.6 h1:gk85QWKxh3TazbLxED/NlDVv8+q+ReFJk7Y2W/KhfNY= +github.com/multiformats/go-varint v0.0.6/go.mod h1:3Ls8CIEsrijN6+B7PbrXRPxHRPuXSrVKRY101jdMZYE= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/grpc-proxy v0.0.0-20181017164139-0f1106ef9c76/go.mod h1:x5OoJHDHqxHS801UIuhqGl6QdSAEJvtausosHSdazIo= +github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= +github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU= +github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k= +github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzEE/Zbp4w= +github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= +github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= +github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= +github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= +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-rc2/go.mod h1:3OVijpioIKYWTqjiG0zfF6wvoJ4fAXGbjdZuI2NgsRQ= +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= +github.com/opentracing/opentracing-go v1.0.2/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxSfWAKL3wpBW7V8scJMt8N8gnaMCS9E/cA= +github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= +github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= +github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= +github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4Emza6EbVUUGA= +github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= +github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= +github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= +github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pelletier/go-toml/v2 v2.0.9 h1:uH2qQXheeefCCkuBBSLi7jCiSmj3VRh2+Goq2N7Xxu0= +github.com/pelletier/go-toml/v2 v2.0.9/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= +github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= +github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08 h1:hDSdbBuw3Lefr6R18ax0tZ2BJeNB3NehB3trOwYBsdU= +github.com/petermattis/goid v0.0.0-20230317030725-371a4b8eda08/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= +github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= +github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pierrec/xxHash v0.1.5 h1:n/jBpwTHiER4xYvK3/CdPVnLDPchj8eTJFFLUb4QHBo= +github.com/pierrec/xxHash v0.1.5/go.mod h1:w2waW5Zoa/Wc4Yqe0wgrIYAGKqRMf7czn2HNKXmuL+I= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= +github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= +github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= +github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8= +github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= +github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= +github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= +github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/common v0.15.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= +github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM= +github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.3.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+PymziUAg= +github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM= +github.com/rakyll/statik v0.1.7 h1:OF3QCZUuyPxuGEP7B4ypUa7sB/iHtqOTDYZXGM8KOdQ= +github.com/rakyll/statik v0.1.7/go.mod h1:AlZONWzMtEnMs7W4e/1LURLiI49pIMmp6V9Unghqrcc= +github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 h1:N/ElC8H3+5XpJzTSTfLsJV/mx9Q9g7kxmchpfZyxgzM= +github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/regen-network/gocuke v0.6.2 h1:pHviZ0kKAq2U2hN2q3smKNxct6hS0mGByFMHGnWA97M= +github.com/regen-network/protobuf v1.3.3-alpha.regen.1 h1:OHEc+q5iIAXpqiqFKeLpu5NwTIkVXUs48vFMwzqpqY4= +github.com/regen-network/protobuf v1.3.3-alpha.regen.1/go.mod h1:2DjTFR1HhMQhiWC5sZ4OhQ3+NtdbZ6oBDKQwq5Ou+FI= +github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +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/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/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= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= +github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= +github.com/sasha-s/go-deadlock v0.3.1 h1:sqv7fDNShgjcaxkO0JNcOAlr8B9+cV5Ey/OB71efZx0= +github.com/sasha-s/go-deadlock v0.3.1/go.mod h1:F73l+cr82YSh10GxyRI6qZiCgK64VaZjwesgfQ1/iLM= +github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible h1:Bn1aCHHRnjv4Bl16T8rcaFjYSrGrIZvpiGO6P3Q4GpU= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +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/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= +github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= +github.com/spacemonkeygo/spacelog v0.0.0-20180420211403-2296661a0572 h1:RC6RW7j+1+HkWaX/Yh71Ee5ZHaHYt7ZP4sQgUrm6cDU= +github.com/spacemonkeygo/spacelog v0.0.0-20180420211403-2296661a0572/go.mod h1:w0SWMsp6j9O/dk4/ZpIhL+3CkG8ofA2vuv7k+ltqUMc= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= +github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/afero v1.9.5 h1:stMpOSZFs//0Lv29HduCmli3GUfpFoF3Y1Q/aXj/wVM= +github.com/spf13/afero v1.9.5/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ= +github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +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.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= +github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/spf13/viper v1.16.0 h1:rGGH0XDZhdUOryiDWjmIvUSWpbNqisK8Wk0Vyefw8hc= +github.com/spf13/viper v1.16.0/go.mod h1:yg78JgCJcbrQOvV9YLXgkLaZqUidkY9K+Dd1FofRzQg= +github.com/strangelove-ventures/interchaintest/v7 v7.0.0-20230721183422-fb937bb0e165 h1:uVCHoklBlbAy77RT6iQBaK7oo8rTn5uI0hrRn1LL5Sw= +github.com/strangelove-ventures/interchaintest/v7 v7.0.0-20230721183422-fb937bb0e165/go.mod h1:WUglvTs5dOXiI7z+VRiVibkFcd2pvTfoDEcXnjYONrw= +github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= +github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.1.5-0.20170601210322-f6abca593680/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= +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.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +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.20220721030215-126854af5e6d h1:vfofYNRScrDdvS342BElfbETmL1Aiz3i2t0zfRj16Hs= +github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d/go.mod h1:RRCYJbIwD5jmqPI9XoAFR0OcDxqUctll6zUj/+B4S48= +github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= +github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= +github.com/tidwall/btree v1.6.0 h1:LDZfKfQIBHGHWSwckhXI0RPSXzlo+KYdjK7FWSqOzzg= +github.com/tidwall/btree v1.6.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= +github.com/tklauser/go-sysconf v0.3.10 h1:IJ1AZGZRWbY8T5Vfk04D9WOA5WSejdflXxP03OUqALw= +github.com/tklauser/numcpus v0.4.0 h1:E53Dm1HjH1/R2/aoCtXtPgzmElmn51aOkhCFSuZq//o= +github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= +github.com/tyler-smith/go-bip32 v1.0.0 h1:sDR9juArbUgX+bO/iblgZnMPeWY1KZMUC2AFUJdv5KE= +github.com/tyler-smith/go-bip32 v1.0.0/go.mod h1:onot+eHknzV4BVPwrzqY5OoVpyCvnwD7lMawL5aQupE= +github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= +github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= +github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0= +github.com/ulikunitz/xz v0.5.10/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= +github.com/ulikunitz/xz v0.5.11 h1:kpFauv27b6ynzBNT/Xy+1k+fK4WswhN/6PN5WhFAGw8= +github.com/ulikunitz/xz v0.5.11/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= +github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/zondax/hid v0.9.1 h1:gQe66rtmyZ8VeGFcOpbuH3r7erYtNEAezCAYu8LdkJo= +github.com/zondax/hid v0.9.1/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= +github.com/zondax/ledger-go v0.14.1 h1:Pip65OOl4iJ84WTpA4BKChvOufMhhbxED3BaihoZN4c= +github.com/zondax/ledger-go v0.14.1/go.mod h1:fZ3Dqg6qcdXWSOJFKMG8GCTnD7slO/RL2feOQv8K320= +go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/bbolt v1.3.7 h1:j+zJOnnEjF/kyHlDDgGnVL/AIqIJPq8UoB2GSNfkUfQ= +go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw= +go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= +go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= +go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= +go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= +go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= +go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= +golang.org/x/crypto v0.0.0-20170613210332-850760c427c5/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +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-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= +golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= +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= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +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/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= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +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.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +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= +golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= +golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220412020605-290c469a71a5/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220617184016-355a448f1bc9/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +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.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50= +golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= +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= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220608161450-d0670ef3b1eb/go.mod h1:jaDAt6Dkxork7LmZnYtzbRWj0W47D86a3TGe0YHBvmE= +golang.org/x/oauth2 v0.0.0-20220622183110-fd043fe589d2/go.mod h1:jaDAt6Dkxork7LmZnYtzbRWj0W47D86a3TGe0YHBvmE= +golang.org/x/oauth2 v0.0.0-20220822191816-0ebed06d0094/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= +golang.org/x/oauth2 v0.0.0-20220909003341-f21342109be1/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= +golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri7E0u6Gs4e9Ri2zaLxzw5DI5XGrYg= +golang.org/x/oauth2 v0.1.0/go.mod h1:G9FE4dLTsbXUu90h/Pf85g4w1D+SSAgR+q46nJZ8M4A= +golang.org/x/oauth2 v0.8.0 h1:6dkIjl3j3LtZ/O3sTgZTMsLKSftL/B8Zgq4huOIIUu8= +golang.org/x/oauth2 v0.8.0/go.mod h1:yr7u4HXZRm1R1kBWqr/xKNqewf0plRYoB7sla+BCIXE= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210819135213-f52c844e1c1c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220315194320-039c03cc5b86/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220502124256-b6088ccd6cba/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +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-20220704084225-05e143d24a9e/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= +golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +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.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= +golang.org/x/sys v0.10.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.10.0 h1:3R7pNqamzBraeqj/Tj8qt1aQ2HpmlC+Cx/qL/7hn4/c= +golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= +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= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +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.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= +golang.org/x/text v0.11.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= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.1.0 h1:xYY+Bajn2a7VBmTM5GikTmnK8ZuX8YgnQCqZpbBNtmA= +golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= +golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +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.11.0 h1:EMCa6U9S2LtZXLAMoWiR/R8dAQFRqbAitmbJ2UKhoi8= +golang.org/x/tools v0.11.0/go.mod h1:anzJrxPjNtfgiYQYirP2CPGzGLxrH2u2QBhn6Bf3qY8= +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= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= +golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= +google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= +google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= +google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= +google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= +google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4= +google.golang.org/api v0.50.0/go.mod h1:4bNT5pAuq5ji4SRZm+5QIkjny9JAyVD/3gaSihNefaw= +google.golang.org/api v0.51.0/go.mod h1:t4HdrdoNgyN5cbEfm7Lum0lcLDLiise1F8qDKX00sOU= +google.golang.org/api v0.54.0/go.mod h1:7C4bFFOvVDGXjfDTAsgGwDgAxRDeQ4X8NvUedIt6z3k= +google.golang.org/api v0.55.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= +google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= +google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdrMgI= +google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I= +google.golang.org/api v0.63.0/go.mod h1:gs4ij2ffTRXwuzzgJl/56BdwJaA194ijkfn++9tDuPo= +google.golang.org/api v0.67.0/go.mod h1:ShHKP8E60yPsKNw/w8w+VYaj9H6buA5UqDp8dhbQZ6g= +google.golang.org/api v0.70.0/go.mod h1:Bs4ZM2HGifEvXwd50TtW70ovgJffJYw2oRCOFU/SkfA= +google.golang.org/api v0.71.0/go.mod h1:4PyU6e6JogV1f9eA4voyrTY2batOLdgZ5qZ5HOCc4j8= +google.golang.org/api v0.74.0/go.mod h1:ZpfMZOVRMywNyvJFeqL9HRWBgAuRfSjJFpe9QtRRyDs= +google.golang.org/api v0.75.0/go.mod h1:pU9QmyHLnzlpar1Mjt4IbapUCy8J+6HD6GeELN69ljA= +google.golang.org/api v0.77.0/go.mod h1:pU9QmyHLnzlpar1Mjt4IbapUCy8J+6HD6GeELN69ljA= +google.golang.org/api v0.78.0/go.mod h1:1Sg78yoMLOhlQTeF+ARBoytAcH1NNyyl390YMy6rKmw= +google.golang.org/api v0.80.0/go.mod h1:xY3nI94gbvBrE0J6NHXhxOmW97HG7Khjkku6AFB3Hyg= +google.golang.org/api v0.84.0/go.mod h1:NTsGnUFJMYROtiquksZHBWtHfeMC7iYthki7Eq3pa8o= +google.golang.org/api v0.85.0/go.mod h1:AqZf8Ep9uZ2pyTvgL+x0D3Zt0eoT9b5E8fmzfu6FO2g= +google.golang.org/api v0.90.0/go.mod h1:+Sem1dnrKlrXMR/X0bPnMWyluQe4RsNoYfmNLhOIkzw= +google.golang.org/api v0.93.0/go.mod h1:+Sem1dnrKlrXMR/X0bPnMWyluQe4RsNoYfmNLhOIkzw= +google.golang.org/api v0.95.0/go.mod h1:eADj+UBuxkh5zlrSntJghuNeg8HwQ1w5lTKkuqaETEI= +google.golang.org/api v0.96.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= +google.golang.org/api v0.97.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= +google.golang.org/api v0.98.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ13s= +google.golang.org/api v0.100.0/go.mod h1:ZE3Z2+ZOr87Rx7dqFsdRQkRBk36kDtp/h+QpHbB7a70= +google.golang.org/api v0.126.0 h1:q4GJq+cAdMAC7XP7njvQ4tvohGLiSlytuL4BQxbIZ+o= +google.golang.org/api v0.126.0/go.mod h1:mBwVAtz+87bEN6CbA1GtZPDOqY2R5ONPqJeIlvyo4Aw= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200324203455-a04cca1dde73/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210126160654-44e461bb6506/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210329143202-679c6ae281ee/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210604141403-392c879c8b08/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210608205507-b6d2f5bf0d7d/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= +google.golang.org/genproto v0.0.0-20210713002101-d411969a0d9a/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210728212813-7823e685a01f/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210813162853-db860fec028c/go.mod h1:cFeNkxwySK631ADgubI+/XFU/xp8FD5KIVV4rj8UC5w= +google.golang.org/genproto v0.0.0-20210821163610-241b8fcbd6c8/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210831024726-fe130286e0e2/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210903162649-d08c68adba83/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210909211513-a8c4777a87af/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210924002016-3dee208752a0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211221195035-429b39de9b1c/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220126215142-9970aeb2e350/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220207164111-0872dc986b00/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220218161850-94dd64e39d7c/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220222213610-43724f9ea8cf/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220304144024-325a89244dc8/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220310185008-1973136f34c6/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220314164441-57ef72a4c106/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= +google.golang.org/genproto v0.0.0-20220324131243-acbaeb5b85eb/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= +google.golang.org/genproto v0.0.0-20220407144326-9054f6ed7bac/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220413183235-5e96e2839df9/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220414192740-2d67ff6cf2b4/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220421151946-72621c1f0bd3/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220429170224-98d788798c3e/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20220502173005-c8bf987b8c21/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220505152158-f39f71e6c8f3/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220518221133-4f43b3371335/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220523171625-347a074981d8/go.mod h1:RAyBrSAP7Fh3Nc84ghnVLDPuV51xc9agzmm4Ph6i0Q4= +google.golang.org/genproto v0.0.0-20220608133413-ed9918b62aac/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220616135557-88e70c0c3a90/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220617124728-180714bec0ad/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220624142145-8cd45d7dbd1f/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220628213854-d9e0b6570c03/go.mod h1:KEWEmljWE5zPzLBa/oHl6DaEt9LmfH6WtH1OHIvleBA= +google.golang.org/genproto v0.0.0-20220722212130-b98a9ff5e252/go.mod h1:GkXuJDJ6aQ7lnJcRF+SJVgFdQhypqgl3LB1C9vabdRE= +google.golang.org/genproto v0.0.0-20220801145646-83ce21fca29f/go.mod h1:iHe1svFLAZg9VWz891+QbRMwUv9O/1Ww+/mngYeThbc= +google.golang.org/genproto v0.0.0-20220815135757-37a418bb8959/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220817144833-d7fd3f11b9b1/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220822174746-9e6da59bd2fc/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220829144015-23454907ede3/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220829175752-36a9c930ecbf/go.mod h1:dbqgFATTzChvnt+ujMdZwITVAJHFtfyN1qUhDqEiIlk= +google.golang.org/genproto v0.0.0-20220913154956-18f8339a66a5/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220914142337-ca0e39ece12f/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220915135415-7fd63a7952de/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220916172020-2692e8806bfa/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220919141832-68c03719ef51/go.mod h1:0Nb8Qy+Sk5eDzHnzlStwW3itdNaWoZA5XeSG+R3JHSo= +google.golang.org/genproto v0.0.0-20220920201722-2b89144ce006/go.mod h1:ht8XFiar2npT/g4vkk7O0WYS1sHOHbdujxbEp7CJWbw= +google.golang.org/genproto v0.0.0-20220926165614-551eb538f295/go.mod h1:woMGP53BroOrRY3xTxlbr8Y3eB/nzAvvFM83q7kG2OI= +google.golang.org/genproto v0.0.0-20220926220553-6981cbe3cfce/go.mod h1:woMGP53BroOrRY3xTxlbr8Y3eB/nzAvvFM83q7kG2OI= +google.golang.org/genproto v0.0.0-20221010155953-15ba04fc1c0e/go.mod h1:3526vdqwhZAwq4wsRUaVG555sVgsNmIjRtO7t/JH29U= +google.golang.org/genproto v0.0.0-20221014173430-6e2ab493f96b/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= +google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a/go.mod h1:1vXfmgAz9N9Jx0QA82PqRVauvCz1SGSz739p0f183jM= +google.golang.org/genproto v0.0.0-20221025140454-527a21cfbd71/go.mod h1:9qHF0xnpdSfF6knlcsnpzUu5y+rpwgbvsyGAZPBMg4s= +google.golang.org/genproto v0.0.0-20230706204954-ccb25ca9f130 h1:Au6te5hbKUV8pIYWHqOUZ1pva5qK/rwbIhoXEUB9Lu8= +google.golang.org/genproto v0.0.0-20230706204954-ccb25ca9f130/go.mod h1:O9kGHb51iE/nOGvQaDUuadVYqovW56s5emA88lQnj6Y= +google.golang.org/genproto/googleapis/api v0.0.0-20230629202037-9506855d4529 h1:s5YSX+ZH5b5vS9rnpGymvIyMpLRJizowqDlOuyjXnTk= +google.golang.org/genproto/googleapis/api v0.0.0-20230629202037-9506855d4529/go.mod h1:vHYtlOoi6TsQ3Uk2yxR7NI5z8uoV+3pZtR4jmHIkRig= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 h1:bVf09lpb+OJbByTj913DRJioFFAjf/ZGxEz7MajTp2U= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM= +google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= +google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc v1.40.1/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc v1.44.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= +google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.46.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.46.2/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.47.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.48.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.49.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= +google.golang.org/grpc v1.50.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= +google.golang.org/grpc v1.50.1/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= +google.golang.org/grpc v1.56.2 h1:fVRFRnXvU+x6C4IlHZewvJOVHoOv1TUuQyoRsYnB4bI= +google.golang.org/grpc v1.56.2/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +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.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= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= +gopkg.in/cheggaaa/pb.v1 v1.0.27/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce h1:+JknDZhAj8YMt7GC73Ei8pv4MzjDUNPHgQWJdtMAaDU= +gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= +gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= +gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= +gotest.tools/v3 v3.5.0 h1:Ljk6PdHdOhAb5aDMWXjDLMMhph+BpztA4v1QdqEW2eY= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +launchpad.net/gocheck v0.0.0-20140225173054-000000000087 h1:Izowp2XBH6Ya6rv+hqbceQyw/gSGoXfH/UPoTGduL54= +launchpad.net/gocheck v0.0.0-20140225173054-000000000087/go.mod h1:hj7XX3B/0A+80Vse0e+BUHsHMTEhd0O4cpUHr/e/BUM= +lukechampine.com/blake3 v1.1.7 h1:GgRMhmdsuK8+ii6UZFDL8Nb+VyMwadAgcJyfYHxG6n0= +lukechampine.com/blake3 v1.1.7/go.mod h1:tkKEOtDkNtklkXtLNEOGNq5tcV90tJiA1vAA12R78LA= +lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI= +lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= +modernc.org/cc/v3 v3.40.0 h1:P3g79IUS/93SYhtoeaHW+kRCIrYaxJ27MFPv+7kaTOw= +modernc.org/cc/v3 v3.40.0/go.mod h1:/bTg4dnWkSXowUO6ssQKnOV0yMVxDYNIsIrzqTFDGH0= +modernc.org/ccgo/v3 v3.16.13 h1:Mkgdzl46i5F/CNR/Kj80Ri59hC8TKAhZrYSaqvkwzUw= +modernc.org/ccgo/v3 v3.16.13/go.mod h1:2Quk+5YgpImhPjv2Qsob1DnZ/4som1lJTodubIcoUkY= +modernc.org/ccorpus v1.11.6 h1:J16RXiiqiCgua6+ZvQot4yUuUy8zxgqbqEEUuGPlISk= +modernc.org/httpfs v1.0.6 h1:AAgIpFZRXuYnkjftxTAZwMIiwEqAfk8aVB2/oA6nAeM= +modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE= +modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY= +modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= +modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds= +modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sqlite v1.24.0 h1:EsClRIWHGhLTCX44p+Ri/JLD+vFGo0QGjasg2/F9TlI= +modernc.org/sqlite v1.24.0/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk= +modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY= +modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw= +modernc.org/tcl v1.15.2 h1:C4ybAYCGJw968e+Me18oW55kD/FexcHbqH2xak1ROSY= +modernc.org/token v1.0.1 h1:A3qvTqOwexpfZZeyI0FeGPDlSWX5pjZu9hF4lU+EKWg= +modernc.org/token v1.0.1/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +modernc.org/z v1.7.3 h1:zDJf6iHjrnB+WRD88stbXokugjyc0/pB91ri1gO6LZY= +nhooyr.io/websocket v1.8.6/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= +nhooyr.io/websocket v1.8.7 h1:usjR2uOr/zjjkVMy0lW+PPohFok7PCow5sDjLgX4P4g= +nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= +pgregory.net/rapid v0.5.5 h1:jkgx1TjbQPD/feRoK+S/mXw9e1uj6WilpHrXJowi6oA= +pgregory.net/rapid v0.5.5/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= +sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= +sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= +sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= +sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= diff --git a/interchaintest/helpers/cosmwasm.go b/interchaintest/helpers/cosmwasm.go new file mode 100644 index 0000000..206bdf3 --- /dev/null +++ b/interchaintest/helpers/cosmwasm.go @@ -0,0 +1,83 @@ +package helpers + +import ( + "context" + "testing" + + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" +) + +func SetupContract(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, keyname string, fileLoc string, message string) (codeId, contract string) { + codeId, err := chain.StoreContract(ctx, keyname, fileLoc) + if err != nil { + t.Fatal(err) + } + + contractAddr, err := chain.InstantiateContract(ctx, keyname, codeId, message, true) + if err != nil { + t.Fatal(err) + } + + return codeId, contractAddr +} + +func ExecuteMsgWithAmount(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, user ibc.Wallet, contractAddr, amount, message string) { + // amount is #utoken + + // There has to be a way to do this in ictest? + cmd := []string{ + "terpd", "tx", "wasm", "execute", contractAddr, message, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", user.KeyName(), + "--gas", "500000", + "--amount", amount, + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + if err := testutil.WaitForBlocks(ctx, 2, chain); err != nil { + t.Fatal(err) + } +} + +func ExecuteMsgWithFee(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, user ibc.Wallet, contractAddr, amount, feeCoin, message string) { + // amount is #utoken + + // There has to be a way to do this in ictest? + cmd := []string{ + "terpd", "tx", "wasm", "execute", contractAddr, message, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", user.KeyName(), + "--gas", "500000", + "--fees", feeCoin, + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + + if amount != "" { + cmd = append(cmd, "--amount", amount) + } + + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + if err := testutil.WaitForBlocks(ctx, 2, chain); err != nil { + t.Fatal(err) + } +} diff --git a/interchaintest/helpers/feeshare.go b/interchaintest/helpers/feeshare.go new file mode 100644 index 0000000..879a4a5 --- /dev/null +++ b/interchaintest/helpers/feeshare.go @@ -0,0 +1,34 @@ +package helpers + +import ( + "context" + "testing" + + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" +) + +func RegisterFeeShare(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, user ibc.Wallet, contract, withdrawAddr string) { + // TF gas to create cost 2mil, so we set to 2.5 to be safe + cmd := []string{ + "terpd", "tx", "feeshare", "register", contract, withdrawAddr, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", user.KeyName(), + // "--gas", "500000", + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + err = testutil.WaitForBlocks(ctx, 2, chain) + require.NoError(t, err) +} diff --git a/interchaintest/helpers/ibchooks.go b/interchaintest/helpers/ibchooks.go new file mode 100644 index 0000000..4e7fb43 --- /dev/null +++ b/interchaintest/helpers/ibchooks.go @@ -0,0 +1,41 @@ +package helpers + +import ( + "context" + "strings" + "testing" + + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/stretchr/testify/require" +) + +func GetIBCHooksUserAddress(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, channel, uaddr string) string { + // terpd q ibchooks wasm-sender channel-0 "terp1hj5fveer5cjtn4wd6wstzugjfdxzl0xppxm7xs" --node http://localhost:26657 + cmd := []string{ + "terpd", "query", "ibchooks", "wasm-sender", channel, uaddr, + "--node", chain.GetRPCAddress(), + "--chain-id", chain.Config().ChainID, + "--output", "json", + } + + // This query does not return a type, just prints the string. + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + address := strings.Replace(string(stdout), "\n", "", -1) + return address +} + +func GetIBCHookTotalFunds(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, contract string, uaddr string) GetTotalFundsResponse { + var res GetTotalFundsResponse + err := chain.QueryContract(ctx, contract, QueryMsg{GetTotalFunds: &GetTotalFundsQuery{Addr: uaddr}}, &res) + require.NoError(t, err) + return res +} + +func GetIBCHookCount(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, contract string, uaddr string) GetCountResponse { + var res GetCountResponse + err := chain.QueryContract(ctx, contract, QueryMsg{GetCount: &GetCountQuery{Addr: uaddr}}, &res) + require.NoError(t, err) + return res +} diff --git a/interchaintest/helpers/query_helpers.go b/interchaintest/helpers/query_helpers.go new file mode 100644 index 0000000..511cd7e --- /dev/null +++ b/interchaintest/helpers/query_helpers.go @@ -0,0 +1,24 @@ +package helpers + +import ( + "context" + "testing" + + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/stretchr/testify/require" +) + +func GetUserTokenFactoryBalances(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, contract string, uaddr string) GetAllBalancesResponse { + var res GetAllBalancesResponse + err := chain.QueryContract(ctx, contract, QueryMsg{GetAllBalances: &GetAllBalancesQuery{Address: uaddr}}, &res) + require.NoError(t, err) + return res +} + +func GetUnityContractWithdrawalReadyTime(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, contract string) WithdrawalTimestampResponse { + // terpd query wasm contract-state smart '{"get_withdrawal_ready_time":{}}' --output json + var res WithdrawalTimestampResponse + err := chain.QueryContract(ctx, contract, QueryMsg{GetWithdrawalReadyTime: &struct{}{}}, &res) + require.NoError(t, err) + return res +} diff --git a/interchaintest/helpers/tokenfactory.go b/interchaintest/helpers/tokenfactory.go new file mode 100644 index 0000000..a7723e8 --- /dev/null +++ b/interchaintest/helpers/tokenfactory.go @@ -0,0 +1,187 @@ +package helpers + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "testing" + + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + tokenfactorytypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" + + "github.com/cosmos/cosmos-sdk/crypto/keyring" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" +) + +func debugOutput(t *testing.T, stdout string) { + if true { + t.Log(stdout) + } +} + +func CreateTokenFactoryDenom(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, user ibc.Wallet, subDenomName, feeCoin string) (fullDenom string) { + // TF gas to create cost 2mil, so we set to 2.5 to be safe + cmd := []string{ + "terpd", "tx", "tokenfactory", "create-denom", subDenomName, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", user.KeyName(), + "--gas", "2500000", + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + + if feeCoin != "" { + cmd = append(cmd, "--fees", feeCoin) + } + + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + err = testutil.WaitForBlocks(ctx, 2, chain) + require.NoError(t, err) + + return "factory/" + user.FormattedAddress() + "/" + subDenomName +} + +func MintTokenFactoryDenom(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, admin ibc.Wallet, amount uint64, fullDenom string) { + denom := strconv.FormatUint(amount, 10) + fullDenom + + // mint new tokens to the account + cmd := []string{ + "terpd", "tx", "tokenfactory", "mint", denom, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", admin.KeyName(), + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + err = testutil.WaitForBlocks(ctx, 2, chain) + require.NoError(t, err) +} + +func MintToTokenFactoryDenom(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, admin ibc.Wallet, toWallet ibc.Wallet, amount uint64, fullDenom string) { + denom := strconv.FormatUint(amount, 10) + fullDenom + + receiver := toWallet.FormattedAddress() + + t.Log("minting", denom, "to", receiver) + + // mint new tokens to the account + cmd := []string{ + "terpd", "tx", "tokenfactory", "mint-to", receiver, denom, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", admin.KeyName(), + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + err = testutil.WaitForBlocks(ctx, 2, chain) + require.NoError(t, err) +} + +func UpdateTokenFactoryMetadata(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, admin ibc.Wallet, fullDenom, ticker, desc, exponent string) { + // terpd tx tokenfactory modify-metadata [denom] [ticker-symbol] [description] [exponent] + cmd := []string{ + "terpd", "tx", "tokenfactory", "modify-metadata", fullDenom, ticker, fmt.Sprintf("'%s'", desc), exponent, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", admin.KeyName(), + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + err = testutil.WaitForBlocks(ctx, 2, chain) + require.NoError(t, err) +} + +func TransferTokenFactoryAdmin(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, currentAdmin ibc.Wallet, newAdminBech32 string, fullDenom string) { + cmd := []string{ + "terpd", "tx", "tokenfactory", "change-admin", fullDenom, newAdminBech32, + "--node", chain.GetRPCAddress(), + "--home", chain.HomeDir(), + "--chain-id", chain.Config().ChainID, + "--from", currentAdmin.KeyName(), + "--keyring-dir", chain.HomeDir(), + "--keyring-backend", keyring.BackendTest, + "-y", + } + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + err = testutil.WaitForBlocks(ctx, 2, chain) + require.NoError(t, err) +} + +// Getters +func GetTokenFactoryAdmin(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, fullDenom string) string { + // $BINARY q tokenfactory denom-authority-metadata $FULL_DENOM + cmd := []string{ + "terpd", "query", "tokenfactory", "denom-authority-metadata", fullDenom, + "--node", chain.GetRPCAddress(), + "--chain-id", chain.Config().ChainID, + "--output", "json", + } + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + debugOutput(t, string(stdout)) + + results := &tokenfactorytypes.QueryDenomAuthorityMetadataResponse{} + err = json.Unmarshal(stdout, results) + require.NoError(t, err) + + t.Log(results) + + return results.AuthorityMetadata.Admin +} + +func GetTokenFactoryDenomMetadata(t *testing.T, ctx context.Context, chain *cosmos.CosmosChain, fullDenom string) banktypes.Metadata { + cmd := []string{ + "terpd", "query", "bank", "denom-metadata", "--denom", fullDenom, + "--node", chain.GetRPCAddress(), + "--chain-id", chain.Config().ChainID, + "--output", "json", + } + stdout, _, err := chain.Exec(ctx, cmd, nil) + require.NoError(t, err) + + results := &banktypes.QueryDenomMetadataResponse{} + err = json.Unmarshal(stdout, results) + require.NoError(t, err) + + t.Log(results) + + return results.Metadata +} diff --git a/interchaintest/helpers/types.go b/interchaintest/helpers/types.go new file mode 100644 index 0000000..d3d49d7 --- /dev/null +++ b/interchaintest/helpers/types.go @@ -0,0 +1,78 @@ +package helpers + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// Go based data types for querying on the contract. +// Execute types are not needed here. We just use strings. Could add though in the future and to_string it + +// EntryPoint +type QueryMsg struct { + // Tokenfactory Core + GetConfig *struct{} `json:"get_config,omitempty"` + GetBalance *GetBalanceQuery `json:"get_balance,omitempty"` + GetAllBalances *GetAllBalancesQuery `json:"get_all_balances,omitempty"` + + // Unity Contract + GetWithdrawalReadyTime *struct{} `json:"get_withdrawal_ready_time,omitempty"` + + // IBCHooks + GetCount *GetCountQuery `json:"get_count,omitempty"` + GetTotalFunds *GetTotalFundsQuery `json:"get_total_funds,omitempty"` +} + +type GetAllBalancesQuery struct { + Address string `json:"address"` +} +type GetAllBalancesResponse struct { + // or is it wasm Coin type? + Data []sdk.Coin `json:"data"` +} + +type GetBalanceQuery struct { + // {"get_balance":{"address":"terp1...","denom":"factory/terp1.../RcqfWz"}} + Address string `json:"address"` + Denom string `json:"denom"` +} +type GetBalanceResponse struct { + // or is it wasm Coin type? + Data sdk.Coin `json:"data"` +} + +type WithdrawalTimestampResponse struct { + // {"data":{"withdrawal_ready_timestamp":"1686146048614053435"}} + Data *WithdrawalTimestampObj `json:"data"` +} +type WithdrawalTimestampObj struct { + WithdrawalReadyTimestamp string `json:"withdrawal_ready_timestamp"` +} + +type GetTotalFundsQuery struct { + // {"get_total_funds":{"addr":"terp1..."}} + Addr string `json:"addr"` +} +type GetTotalFundsResponse struct { + // {"data":{"total_funds":[{"denom":"ibc/04F5F501207C3626A2C14BFEF654D51C2E0B8F7CA578AB8ED272A66FE4E48097","amount":"1"}]}} + Data *GetTotalFundsObj `json:"data"` +} +type GetTotalFundsObj struct { + TotalFunds []WasmCoin `json:"total_funds"` +} + +type WasmCoin struct { + Denom string `json:"denom"` + Amount string `json:"amount"` +} + +type GetCountQuery struct { + // {"get_total_funds":{"addr":"terp1..."}} + Addr string `json:"addr"` +} +type GetCountResponse struct { + // {"data":{"count":0}} + Data *GetCountObj `json:"data"` +} +type GetCountObj struct { + Count int64 `json:"count"` +} diff --git a/interchaintest/ibc_transfer_test.go b/interchaintest/ibc_transfer_test.go new file mode 100644 index 0000000..390bca9 --- /dev/null +++ b/interchaintest/ibc_transfer_test.go @@ -0,0 +1,195 @@ +package interchaintest + +import ( + "context" + "testing" + + transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + interchaintestrelayer "github.com/strangelove-ventures/interchaintest/v7/relayer" + "github.com/strangelove-ventures/interchaintest/v7/testreporter" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" +) + +// TestTerpGaiaIBCTransfer spins up a Terp and Gaia network, initializes an IBC connection between them, +// and sends an ICS20 token transfer from Terp->Gaia and then back from Gaia->Terp. +func TestTerpGaiaIBCTransfer(t *testing.T) { + if testing.Short() { + t.Skip() + } + + t.Parallel() + + // Create chain factory with Terp and Gaia + numVals := 1 + numFullNodes := 1 + + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ + { + Name: "terp", + ChainConfig: terpConfig, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "gaia", + Version: "v9.1.0", + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + }) + + const ( + path = "ibc-path" + ) + + // Get chains from the chain factory + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + + client, network := interchaintest.DockerSetup(t) + + terp, gaia := chains[0].(*cosmos.CosmosChain), chains[1].(*cosmos.CosmosChain) + + relayerType, relayerName := ibc.CosmosRly, "relay" + + // Get a relayer instance + rf := interchaintest.NewBuiltinRelayerFactory( + relayerType, + zaptest.NewLogger(t), + interchaintestrelayer.CustomDockerImage(IBCRelayerImage, IBCRelayerVersion, "100:1000"), + interchaintestrelayer.StartupFlags("--processor", "events", "--block-history", "100"), + ) + + r := rf.Build(t, client, network) + + ic := interchaintest.NewInterchain(). + AddChain(terp). + AddChain(gaia). + AddRelayer(r, relayerName). + AddLink(interchaintest.InterchainLink{ + Chain1: terp, + Chain2: gaia, + Relayer: r, + Path: path, + }) + + ctx := context.Background() + + rep := testreporter.NewNopReporter() + eRep := rep.RelayerExecReporter(t) + + require.NoError(t, ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + BlockDatabaseFile: interchaintest.DefaultBlockDatabaseFilepath(), + SkipPathCreation: false, + })) + t.Cleanup(func() { + _ = ic.Close() + }) + + // Create some user accounts on both chains + users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), genesisWalletAmount, terp, gaia) + + // Wait a few blocks for relayer to start and for user accounts to be created + err = testutil.WaitForBlocks(ctx, 5, terp, gaia) + require.NoError(t, err) + + // Get our Bech32 encoded user addresses + terpUser, gaiaUser := users[0], users[1] + + terpUserAddr := terpUser.FormattedAddress() + gaiaUserAddr := gaiaUser.FormattedAddress() + + // Get original account balances + terpOrigBal, err := terp.GetBalance(ctx, terpUserAddr, terp.Config().Denom) + require.NoError(t, err) + require.Equal(t, genesisWalletAmount, terpOrigBal) + + gaiaOrigBal, err := gaia.GetBalance(ctx, gaiaUserAddr, gaia.Config().Denom) + require.NoError(t, err) + require.Equal(t, genesisWalletAmount, gaiaOrigBal) + + // Compose an IBC transfer and send from Terp -> Gaia + const transferAmount = int64(1_000) + transfer := ibc.WalletAmount{ + Address: gaiaUserAddr, + Denom: terp.Config().Denom, + Amount: transferAmount, + } + + channel, err := ibc.GetTransferChannel(ctx, r, eRep, terp.Config().ChainID, gaia.Config().ChainID) + require.NoError(t, err) + + terpHeight, err := terp.Height(ctx) + require.NoError(t, err) + + transferTx, err := terp.SendIBCTransfer(ctx, channel.ChannelID, terpUserAddr, transfer, ibc.TransferOptions{}) + require.NoError(t, err) + + err = r.StartRelayer(ctx, eRep, path) + require.NoError(t, err) + + t.Cleanup( + func() { + err := r.StopRelayer(ctx, eRep) + if err != nil { + t.Logf("an error occured while stopping the relayer: %s", err) + } + }, + ) + + // Poll for the ack to know the transfer was successful + // TODO: Remove after auto transfer is fixed in the relayer + r.Flush(ctx, eRep, path, channel.ChannelID) + _, err = testutil.PollForAck(ctx, terp, terpHeight-5, terpHeight+50, transferTx.Packet) + require.NoError(t, err) + + err = testutil.WaitForBlocks(ctx, 10, terp) + require.NoError(t, err) + + // Get the IBC denom for uterp on Gaia + terpTokenDenom := transfertypes.GetPrefixedDenom(channel.Counterparty.PortID, channel.Counterparty.ChannelID, terp.Config().Denom) + terpIBCDenom := transfertypes.ParseDenomTrace(terpTokenDenom).IBCDenom() + + // Assert that the funds are no longer present in user acc on Terp and are in the user acc on Gaia + terpUpdateBal, err := terp.GetBalance(ctx, terpUserAddr, terp.Config().Denom) + require.NoError(t, err) + require.Equal(t, terpOrigBal-transferAmount, terpUpdateBal) + + gaiaUpdateBal, err := gaia.GetBalance(ctx, gaiaUserAddr, terpIBCDenom) + require.NoError(t, err) + require.Equal(t, transferAmount, gaiaUpdateBal) + + // Compose an IBC transfer and send from Gaia -> Terp + transfer = ibc.WalletAmount{ + Address: terpUserAddr, + Denom: terpIBCDenom, + Amount: transferAmount, + } + + gaiaHeight, err := gaia.Height(ctx) + require.NoError(t, err) + + transferTx, err = gaia.SendIBCTransfer(ctx, channel.Counterparty.ChannelID, gaiaUserAddr, transfer, ibc.TransferOptions{}) + require.NoError(t, err) + + // Poll for the ack to know the transfer was successful + _, err = testutil.PollForAck(ctx, gaia, gaiaHeight, gaiaHeight+25, transferTx.Packet) + require.NoError(t, err) + + // Assert that the funds are now back on Terp and not on Gaia + terpUpdateBal, err = terp.GetBalance(ctx, terpUserAddr, terp.Config().Denom) + require.NoError(t, err) + require.Equal(t, terpOrigBal, terpUpdateBal) + + gaiaUpdateBal, err = gaia.GetBalance(ctx, gaiaUserAddr, terpIBCDenom) + require.NoError(t, err) + require.Equal(t, int64(0), gaiaUpdateBal) +} diff --git a/interchaintest/module_feeshare_test.go b/interchaintest/module_feeshare_test.go new file mode 100644 index 0000000..4b19851 --- /dev/null +++ b/interchaintest/module_feeshare_test.go @@ -0,0 +1,55 @@ +package interchaintest + +import ( + "testing" + + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + + helpers "github.com/terpnetwork/terp-core/tests/interchaintest/helpers" +) + +// TestTerpFeeShare ensures the feeshare module register and execute sharing functions work properly on smart contracts. +func TestTerpFeeShare(t *testing.T) { + t.Parallel() + + // Base setup + chains := CreateThisBranchChain(t, 1, 0) + ic, ctx, _, _ := BuildInitialChain(t, chains) + + // Chains + terp := chains[0].(*cosmos.CosmosChain) + t.Log("terp.GetHostRPCAddress()", terp.GetHostRPCAddress()) + + nativeDenom := terp.Config().Denom + + // Users + users := interchaintest.GetAndFundTestUsers(t, ctx, "default", int64(10_000_000), terp, terp) + user := users[0] + feeRcvAddr := "terp1v75wlkccpv7le3560zw32v2zjes5n0e7fgfzdc" + + // Upload & init contract payment to another address + _, contractAddr := helpers.SetupContract(t, ctx, terp, user.KeyName(), "contracts/cw_template.wasm", `{"count":0}`) + + // register contract to a random address (since we are the creator, though not the admin) + helpers.RegisterFeeShare(t, ctx, terp, user, contractAddr, feeRcvAddr) + if balance, err := terp.GetBalance(ctx, feeRcvAddr, nativeDenom); err != nil { + t.Fatal(err) + } else if balance != 0 { + t.Fatal("balance not 0") + } + + // execute with a 10000 fee (so 5000 denom should be in the contract now with 50% feeshare default) + helpers.ExecuteMsgWithFee(t, ctx, terp, user, contractAddr, "", "10000"+nativeDenom, `{"increment":{}}`) + + // check balance of nativeDenom now + if balance, err := terp.GetBalance(ctx, feeRcvAddr, nativeDenom); err != nil { + t.Fatal(err) + } else if balance != 5000 { + t.Fatal("balance not 5,000. it is ", balance, nativeDenom) + } + + t.Cleanup(func() { + _ = ic.Close() + }) +} diff --git a/interchaintest/module_ibchooks_test.go b/interchaintest/module_ibchooks_test.go new file mode 100644 index 0000000..52ff372 --- /dev/null +++ b/interchaintest/module_ibchooks_test.go @@ -0,0 +1,186 @@ +package interchaintest + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + interchaintestrelayer "github.com/strangelove-ventures/interchaintest/v7/relayer" + "github.com/strangelove-ventures/interchaintest/v7/testreporter" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" + + helpers "github.com/terpnetwork/terp-core/tests/interchaintest/helpers" +) + +// TestTerpIBCHooks ensures the ibc-hooks middleware from osmosis works. +func TestTerpIBCHooks(t *testing.T) { + if testing.Short() { + t.Skip() + } + + t.Parallel() + + // Create chain factory with Terp and terp2 + numVals := 1 + numFullNodes := 0 + + cfg2 := terpConfig.Clone() + cfg2.Name = "terp-counterparty" + cfg2.ChainID = "counterparty-2" + + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ + { + Name: "terp", + ChainConfig: terpConfig, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "terp", + ChainConfig: cfg2, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + }) + + const ( + path = "ibc-path" + ) + + // Get chains from the chain factory + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + + client, network := interchaintest.DockerSetup(t) + + terp, terp2 := chains[0].(*cosmos.CosmosChain), chains[1].(*cosmos.CosmosChain) + + relayerType, relayerName := ibc.CosmosRly, "relay" + + // Get a relayer instance + rf := interchaintest.NewBuiltinRelayerFactory( + relayerType, + zaptest.NewLogger(t), + interchaintestrelayer.CustomDockerImage(IBCRelayerImage, IBCRelayerVersion, "100:1000"), + interchaintestrelayer.StartupFlags("--processor", "events", "--block-history", "100"), + ) + + r := rf.Build(t, client, network) + + ic := interchaintest.NewInterchain(). + AddChain(terp). + AddChain(terp2). + AddRelayer(r, relayerName). + AddLink(interchaintest.InterchainLink{ + Chain1: terp, + Chain2: terp2, + Relayer: r, + Path: path, + }) + + ctx := context.Background() + + rep := testreporter.NewNopReporter() + eRep := rep.RelayerExecReporter(t) + + require.NoError(t, ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + BlockDatabaseFile: interchaintest.DefaultBlockDatabaseFilepath(), + SkipPathCreation: false, + })) + t.Cleanup(func() { + _ = ic.Close() + }) + + // Create some user accounts on both chains + users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), genesisWalletAmount, terp, terp2) + + // Wait a few blocks for relayer to start and for user accounts to be created + err = testutil.WaitForBlocks(ctx, 5, terp, terp2) + require.NoError(t, err) + + // Get our Bech32 encoded user addresses + terpUser, terp2User := users[0], users[1] + + terpUserAddr := terpUser.FormattedAddress() + // terp2UserAddr := terp2User.FormattedAddress() + + channel, err := ibc.GetTransferChannel(ctx, r, eRep, terp.Config().ChainID, terp2.Config().ChainID) + require.NoError(t, err) + + err = r.StartRelayer(ctx, eRep, path) + require.NoError(t, err) + + t.Cleanup( + func() { + err := r.StopRelayer(ctx, eRep) + if err != nil { + t.Logf("an error occured while stopping the relayer: %s", err) + } + }, + ) + + _, contractAddr := helpers.SetupContract(t, ctx, terp2, terp2User.KeyName(), "contracts/ibchooks_counter.wasm", `{"count":0}`) + + // do an ibc transfer through the memo to the other chain. + transfer := ibc.WalletAmount{ + Address: contractAddr, + Denom: terp.Config().Denom, + Amount: int64(1), + } + + memo := ibc.TransferOptions{ + Memo: fmt.Sprintf(`{"wasm":{"contract":"%s","msg":%s}}`, contractAddr, `{"increment":{}}`), + } + + // Initial transfer. Account is created by the wasm execute is not so we must do this twice to properly set up + transferTx, err := terp.SendIBCTransfer(ctx, channel.ChannelID, terpUser.KeyName(), transfer, memo) + require.NoError(t, err) + terpHeight, err := terp.Height(ctx) + require.NoError(t, err) + + // TODO: Remove when the relayer is fixed + r.Flush(ctx, eRep, path, channel.ChannelID) + _, err = testutil.PollForAck(ctx, terp, terpHeight-5, terpHeight+25, transferTx.Packet) + require.NoError(t, err) + + // Second time, this will make the counter == 1 since the account is now created. + transferTx, err = terp.SendIBCTransfer(ctx, channel.ChannelID, terpUser.KeyName(), transfer, memo) + require.NoError(t, err) + terpHeight, err = terp.Height(ctx) + require.NoError(t, err) + + // TODO: Remove when the relayer is fixed + r.Flush(ctx, eRep, path, channel.ChannelID) + _, err = testutil.PollForAck(ctx, terp, terpHeight-5, terpHeight+25, transferTx.Packet) + require.NoError(t, err) + + // Get the address on the other chain's side + addr := helpers.GetIBCHooksUserAddress(t, ctx, terp, channel.ChannelID, terpUserAddr) + require.NotEmpty(t, addr) + + // Get funds on the receiving chain + funds := helpers.GetIBCHookTotalFunds(t, ctx, terp2, contractAddr, addr) + require.Equal(t, int(1), len(funds.Data.TotalFunds)) + + var ibcDenom string + for _, coin := range funds.Data.TotalFunds { + if strings.HasPrefix(coin.Denom, "ibc/") { + ibcDenom = coin.Denom + break + } + } + require.NotEmpty(t, ibcDenom) + + // ensure the count also increased to 1 as expected. + count := helpers.GetIBCHookCount(t, ctx, terp2, contractAddr, addr) + require.Equal(t, int64(1), count.Data.Count) +} diff --git a/interchaintest/module_pfm_test.go b/interchaintest/module_pfm_test.go new file mode 100644 index 0000000..73b5f7d --- /dev/null +++ b/interchaintest/module_pfm_test.go @@ -0,0 +1,293 @@ +package interchaintest + +import ( + "context" + "encoding/json" + "testing" + "time" + + sdk "github.com/cosmos/cosmos-sdk/types" + transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + interchaintestrelayer "github.com/strangelove-ventures/interchaintest/v7/relayer" + "github.com/strangelove-ventures/interchaintest/v7/testreporter" + "github.com/strangelove-ventures/interchaintest/v7/testutil" + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" +) + +type PacketMetadata struct { + Forward *ForwardMetadata `json:"forward"` +} + +type ForwardMetadata struct { + Receiver string `json:"receiver"` + Port string `json:"port"` + Channel string `json:"channel"` + Timeout time.Duration `json:"timeout"` + Retries *uint8 `json:"retries,omitempty"` + Next *string `json:"next,omitempty"` + RefundSequence *uint64 `json:"refund_sequence,omitempty"` +} + +// TestPacketForwardMiddlewareRouter ensures the PFM module is set up properly and works as expected. +func TestPacketForwardMiddlewareRouter(t *testing.T) { + if testing.Short() { + t.Skip() + } + + var ( + ctx = context.Background() + client, network = interchaintest.DockerSetup(t) + rep = testreporter.NewNopReporter() + eRep = rep.RelayerExecReporter(t) + chainID_A, chainID_B, chainID_C, chainID_D = "chain-a", "chain-b", "chain-c", "chain-d" + chainA, chainB, chainC, chainD *cosmos.CosmosChain + ) + + // base config which all networks will use as defaults. + baseCfg := ibc.ChainConfig{ + Type: "cosmos", + Name: "terp", + ChainID: "", // change this for each + Images: []ibc.DockerImage{TerpImage}, + Bin: "terpd", + Bech32Prefix: "terp", + Denom: Denom, + CoinType: "118", + GasPrices: "0uterpx", + GasAdjustment: 2.0, + TrustingPeriod: "112h", + NoHostMount: false, + ConfigFileOverrides: nil, + EncodingConfig: terpEncoding(), + UsingNewGenesisCommand: true, + ModifyGenesis: cosmos.ModifyGenesis(defaultGenesisKV), + } + + // Set specific chain ids for each so they are their own unique networks + baseCfg.ChainID = chainID_A + configA := baseCfg + + baseCfg.ChainID = chainID_B + configB := baseCfg + + baseCfg.ChainID = chainID_C + configC := baseCfg + + baseCfg.ChainID = chainID_D + configD := baseCfg + + // Create chain factory with multiple Terp individual networks. + numVals := 1 + numFullNodes := 0 + + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ + { + Name: "terp", + ChainConfig: configA, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "terp", + ChainConfig: configB, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "terp", + ChainConfig: configC, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + { + Name: "terp", + ChainConfig: configD, + NumValidators: &numVals, + NumFullNodes: &numFullNodes, + }, + }) + + // Get chains from the chain factory + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + + chainA, chainB, chainC, chainD = chains[0].(*cosmos.CosmosChain), chains[1].(*cosmos.CosmosChain), chains[2].(*cosmos.CosmosChain), chains[3].(*cosmos.CosmosChain) + + r := interchaintest.NewBuiltinRelayerFactory( + ibc.CosmosRly, + zaptest.NewLogger(t), + interchaintestrelayer.CustomDockerImage(IBCRelayerImage, IBCRelayerVersion, "100:1000"), + interchaintestrelayer.StartupFlags("--processor", "events", "--block-history", "100"), + ).Build(t, client, network) + + const pathAB = "ab" + const pathBC = "bc" + const pathCD = "cd" + + ic := interchaintest.NewInterchain(). + AddChain(chainA). + AddChain(chainB). + AddChain(chainC). + AddChain(chainD). + AddRelayer(r, "relayer"). + AddLink(interchaintest.InterchainLink{ + Chain1: chainA, + Chain2: chainB, + Relayer: r, + Path: pathAB, + }). + AddLink(interchaintest.InterchainLink{ + Chain1: chainB, + Chain2: chainC, + Relayer: r, + Path: pathBC, + }). + AddLink(interchaintest.InterchainLink{ + Chain1: chainC, + Chain2: chainD, + Relayer: r, + Path: pathCD, + }) + + require.NoError(t, ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + BlockDatabaseFile: interchaintest.DefaultBlockDatabaseFilepath(), + + SkipPathCreation: false, + })) + t.Cleanup(func() { + _ = ic.Close() + }) + + const userFunds = int64(10_000_000_000) + users := interchaintest.GetAndFundTestUsers(t, ctx, t.Name(), userFunds, chainA, chainB, chainC, chainD) + + abChan, err := ibc.GetTransferChannel(ctx, r, eRep, chainID_A, chainID_B) + require.NoError(t, err) + + baChan := abChan.Counterparty + + cbChan, err := ibc.GetTransferChannel(ctx, r, eRep, chainID_C, chainID_B) + require.NoError(t, err) + + bcChan := cbChan.Counterparty + + dcChan, err := ibc.GetTransferChannel(ctx, r, eRep, chainID_D, chainID_C) + require.NoError(t, err) + + cdChan := dcChan.Counterparty + + // Start the relayer on all paths + err = r.StartRelayer(ctx, eRep, pathAB, pathBC, pathCD) + require.NoError(t, err) + + t.Cleanup( + func() { + err := r.StopRelayer(ctx, eRep) + if err != nil { + t.Logf("an error occured while stopping the relayer: %s", err) + } + }, + ) + + // Get original account balances + userA, userB, userC, userD := users[0], users[1], users[2], users[3] + + const transferAmount int64 = 100000 + + // Compose the prefixed denoms and ibc denom for asserting balances + firstHopDenom := transfertypes.GetPrefixedDenom(baChan.PortID, baChan.ChannelID, chainA.Config().Denom) + secondHopDenom := transfertypes.GetPrefixedDenom(cbChan.PortID, cbChan.ChannelID, firstHopDenom) + thirdHopDenom := transfertypes.GetPrefixedDenom(dcChan.PortID, dcChan.ChannelID, secondHopDenom) + + firstHopDenomTrace := transfertypes.ParseDenomTrace(firstHopDenom) + secondHopDenomTrace := transfertypes.ParseDenomTrace(secondHopDenom) + thirdHopDenomTrace := transfertypes.ParseDenomTrace(thirdHopDenom) + + firstHopIBCDenom := firstHopDenomTrace.IBCDenom() + secondHopIBCDenom := secondHopDenomTrace.IBCDenom() + thirdHopIBCDenom := thirdHopDenomTrace.IBCDenom() + + firstHopEscrowAccount := sdk.MustBech32ifyAddressBytes(chainA.Config().Bech32Prefix, transfertypes.GetEscrowAddress(abChan.PortID, abChan.ChannelID)) + secondHopEscrowAccount := sdk.MustBech32ifyAddressBytes(chainB.Config().Bech32Prefix, transfertypes.GetEscrowAddress(bcChan.PortID, bcChan.ChannelID)) + thirdHopEscrowAccount := sdk.MustBech32ifyAddressBytes(chainC.Config().Bech32Prefix, transfertypes.GetEscrowAddress(cdChan.PortID, abChan.ChannelID)) + + t.Run("multi-hop a->b->c->d", func(t *testing.T) { + // Send packet from Chain A->Chain B->Chain C->Chain D + + transfer := ibc.WalletAmount{ + Address: userB.FormattedAddress(), + Denom: chainA.Config().Denom, + Amount: transferAmount, + } + + secondHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: userD.FormattedAddress(), + Channel: cdChan.ChannelID, + Port: cdChan.PortID, + }, + } + nextBz, err := json.Marshal(secondHopMetadata) + require.NoError(t, err) + next := string(nextBz) + + firstHopMetadata := &PacketMetadata{ + Forward: &ForwardMetadata{ + Receiver: userC.FormattedAddress(), + Channel: bcChan.ChannelID, + Port: bcChan.PortID, + Next: &next, + }, + } + + memo, err := json.Marshal(firstHopMetadata) + require.NoError(t, err) + + chainAHeight, err := chainA.Height(ctx) + require.NoError(t, err) + + transferTx, err := chainA.SendIBCTransfer(ctx, abChan.ChannelID, userA.KeyName(), transfer, ibc.TransferOptions{Memo: string(memo)}) + require.NoError(t, err) + _, err = testutil.PollForAck(ctx, chainA, chainAHeight, chainAHeight+30, transferTx.Packet) + require.NoError(t, err) + err = testutil.WaitForBlocks(ctx, 1, chainA) + require.NoError(t, err) + + chainABalance, err := chainA.GetBalance(ctx, userA.FormattedAddress(), chainA.Config().Denom) + require.NoError(t, err) + + chainBBalance, err := chainB.GetBalance(ctx, userB.FormattedAddress(), firstHopIBCDenom) + require.NoError(t, err) + + chainCBalance, err := chainC.GetBalance(ctx, userC.FormattedAddress(), secondHopIBCDenom) + require.NoError(t, err) + + chainDBalance, err := chainD.GetBalance(ctx, userD.FormattedAddress(), thirdHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, userFunds-transferAmount, chainABalance) + require.Equal(t, int64(0), chainBBalance) + require.Equal(t, int64(0), chainCBalance) + require.Equal(t, transferAmount, chainDBalance) + + firstHopEscrowBalance, err := chainA.GetBalance(ctx, firstHopEscrowAccount, chainA.Config().Denom) + require.NoError(t, err) + + secondHopEscrowBalance, err := chainB.GetBalance(ctx, secondHopEscrowAccount, firstHopIBCDenom) + require.NoError(t, err) + + thirdHopEscrowBalance, err := chainC.GetBalance(ctx, thirdHopEscrowAccount, secondHopIBCDenom) + require.NoError(t, err) + + require.Equal(t, transferAmount, firstHopEscrowBalance) + require.Equal(t, transferAmount, secondHopEscrowBalance) + require.Equal(t, transferAmount, thirdHopEscrowBalance) + }) +} diff --git a/interchaintest/module_tokenfactory_test.go b/interchaintest/module_tokenfactory_test.go new file mode 100644 index 0000000..c885028 --- /dev/null +++ b/interchaintest/module_tokenfactory_test.go @@ -0,0 +1,84 @@ +package interchaintest + +import ( + "fmt" + "testing" + + "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + + helpers "github.com/terpnetwork/terp-core/tests/interchaintest/helpers" +) + +// TestTerpTokenFactory ensures the tokenfactory module & bindings work properly. +func TestTerpTokenFactory(t *testing.T) { + t.Parallel() + + // Base setup + chains := CreateThisBranchChain(t, 1, 0) + ic, ctx, _, _ := BuildInitialChain(t, chains) + + // Chains + terp := chains[0].(*cosmos.CosmosChain) + t.Log("terp.GetHostRPCAddress()", terp.GetHostRPCAddress()) + + users := interchaintest.GetAndFundTestUsers(t, ctx, "default", int64(10_000_000), terp, terp) + user := users[0] + uaddr := user.FormattedAddress() + + user2 := users[1] + uaddr2 := user2.FormattedAddress() + + tfDenom := helpers.CreateTokenFactoryDenom(t, ctx, terp, user, "ictestdenom", fmt.Sprintf("0%s", Denom)) + t.Log("tfDenom", tfDenom) + + // mint + helpers.MintTokenFactoryDenom(t, ctx, terp, user, 100, tfDenom) + t.Log("minted tfDenom to user") + if balance, err := terp.GetBalance(ctx, uaddr, tfDenom); err != nil { + t.Fatal(err) + } else if balance != 100 { + t.Fatal("balance not 100") + } + + // mint-to + helpers.MintToTokenFactoryDenom(t, ctx, terp, user, user2, 70, tfDenom) + t.Log("minted tfDenom to user") + if balance, err := terp.GetBalance(ctx, uaddr2, tfDenom); err != nil { + t.Fatal(err) + } else if balance != 70 { + t.Fatal("balance not 70") + } + + // This allows the uaddr here to mint tokens on behalf of the contract. Typically you only allow a contract here, but this is testing. + coreInitMsg := fmt.Sprintf(`{"allowed_mint_addresses":["%s"],"denoms":["%s"]}`, uaddr, tfDenom) + _, coreTFContract := helpers.SetupContract(t, ctx, terp, user.KeyName(), "contracts/tokenfactory_core.wasm", coreInitMsg) + t.Log("coreContract", coreTFContract) + + // change admin to the contract + helpers.TransferTokenFactoryAdmin(t, ctx, terp, user, coreTFContract, tfDenom) + + // ensure the admin is the contract + admin := helpers.GetTokenFactoryAdmin(t, ctx, terp, tfDenom) + t.Log("admin", admin) + if admin != coreTFContract { + t.Fatal("admin not coreTFContract. Did not properly transfer.") + } + + // Mint on the contract for the user to ensure mint bindings work. + mintMsg := fmt.Sprintf(`{"mint":{"address":"%s","denom":[{"denom":"%s","amount":"31"}]}}`, uaddr2, tfDenom) + if _, err := terp.ExecuteContract(ctx, user.KeyName(), coreTFContract, mintMsg); err != nil { + t.Fatal(err) + } + + // ensure uaddr2 has 31+70 = 101 + if balance, err := terp.GetBalance(ctx, uaddr2, tfDenom); err != nil { + t.Fatal(err) + } else if balance != 101 { + t.Fatal("balance not 101") + } + + t.Cleanup(func() { + _ = ic.Close() + }) +} diff --git a/interchaintest/setup.go b/interchaintest/setup.go new file mode 100644 index 0000000..016b865 --- /dev/null +++ b/interchaintest/setup.go @@ -0,0 +1,147 @@ +package interchaintest + +import ( + "context" + "fmt" + "testing" + + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + ibclocalhost "github.com/cosmos/ibc-go/v7/modules/light-clients/09-localhost" + + "github.com/docker/docker/client" + + interchaintest "github.com/strangelove-ventures/interchaintest/v7" + "github.com/strangelove-ventures/interchaintest/v7/chain/cosmos" + "github.com/strangelove-ventures/interchaintest/v7/ibc" + "github.com/strangelove-ventures/interchaintest/v7/testreporter" + + "github.com/stretchr/testify/require" + "go.uber.org/zap/zaptest" + + testutil "github.com/cosmos/cosmos-sdk/types/module/testutil" +) + +var ( + VotingPeriod = "15s" + MaxDepositPeriod = "10s" + Denom = "uterp" + + TerpE2ERepo = "ghcr.io/terpnetwork/terp-core-e2e" + TerpMainRepo = "ghcr.io/terpnetwork/terp-core" + + IBCRelayerImage = "ghcr.io/cosmos/relayer" + IBCRelayerVersion = "justin-localhost-ibc" + + terpRepo, terpVersion = GetDockerImageInfo() + + TerpImage = ibc.DockerImage{ + Repository: terpRepo, + Version: terpVersion, + UidGid: "1025:1025", + } + + // SDK v47 Genesis + defaultGenesisKV = []cosmos.GenesisKV{ + { + Key: "app_state.gov.params.voting_period", + Value: VotingPeriod, + }, + { + Key: "app_state.gov.params.max_deposit_period", + Value: MaxDepositPeriod, + }, + { + Key: "app_state.gov.params.min_deposit.0.denom", + Value: Denom, + }, + } + + terpConfig = ibc.ChainConfig{ + Type: "cosmos", + Name: "terpnetwork", + ChainID: "120u-1", + Images: []ibc.DockerImage{TerpImage}, + Bin: "terpd", + Bech32Prefix: "terp", + Denom: Denom, + CoinType: "118", + GasPrices: fmt.Sprintf("0%s", Denom), + GasAdjustment: 2.0, + TrustingPeriod: "112h", + NoHostMount: false, + ConfigFileOverrides: nil, + EncodingConfig: terpEncoding(), + UsingNewGenesisCommand: true, + ModifyGenesis: cosmos.ModifyGenesis(defaultGenesisKV), + } + + genesisWalletAmount = int64(10_000_000) +) + +// terpEncoding registers the Terp specific module codecs so that the associated types and msgs +// will be supported when writing to the blocksdb sqlite database. +func terpEncoding() *testutil.TestEncodingConfig { + cfg := cosmos.DefaultEncoding() + + // register custom types + ibclocalhost.RegisterInterfaces(cfg.InterfaceRegistry) + wasmtypes.RegisterInterfaces(cfg.InterfaceRegistry) + + // github.com/cosmos/cosmos-sdk/types/module/testutil + + return &cfg +} + +// This allows for us to test +func FundSpecificUsers() { +} + +// Base chain, no relaying off this branch (or terpnetwork/terp-core:local if no branch is provided.) +func CreateThisBranchChain(t *testing.T, numVals, numFull int) []ibc.Chain { + // Create chain factory with Terp on this current branch + + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), []*interchaintest.ChainSpec{ + { + Name: "terp", + ChainName: "terpnetwork", + Version: terpVersion, + ChainConfig: terpConfig, + NumValidators: &numVals, + NumFullNodes: &numFull, + }, + }) + + // Get chains from the chain factory + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + + // chain := chains[0].(*cosmos.CosmosChain) + return chains +} + +func BuildInitialChain(t *testing.T, chains []ibc.Chain) (*interchaintest.Interchain, context.Context, *client.Client, string) { + // Create a new Interchain object which describes the chains, relayers, and IBC connections we want to use + ic := interchaintest.NewInterchain() + + for _, chain := range chains { + ic = ic.AddChain(chain) + } + + rep := testreporter.NewNopReporter() + eRep := rep.RelayerExecReporter(t) + + ctx := context.Background() + client, network := interchaintest.DockerSetup(t) + + err := ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + SkipPathCreation: true, + // This can be used to write to the block database which will index all block data e.g. txs, msgs, events, etc. + // BlockDatabaseFile: interchaintest.DefaultBlockDatabaseFilepath(), + }) + require.NoError(t, err) + + return ic, ctx, client, network +} diff --git a/osmoutils/ibc.go b/osmoutils/ibc.go new file mode 100644 index 0000000..56e97ef --- /dev/null +++ b/osmoutils/ibc.go @@ -0,0 +1,72 @@ +package osmoutils + +import ( + "encoding/json" + + transfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" + ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// NewEmitErrorAcknowledgement creates a new error acknowledgement after having emitted an event with the +// details of the error. +func NewEmitErrorAcknowledgement(ctx sdk.Context, err error, errorContexts ...string) channeltypes.Acknowledgement { + attributes := make([]sdk.Attribute, len(errorContexts)+1) + attributes[0] = sdk.NewAttribute("error", err.Error()) + for i, s := range errorContexts { + attributes[i+1] = sdk.NewAttribute("error-context", s) + } + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + "ibc-acknowledgement-error", + attributes..., + ), + }) + + return channeltypes.NewErrorAcknowledgement(err) +} + +// MustExtractDenomFromPacketOnRecv takes a packet with a valid ICS20 token data in the Data field and returns the +// denom as represented in the local chain. +// If the data cannot be unmarshalled this function will panic +func MustExtractDenomFromPacketOnRecv(packet ibcexported.PacketI) string { + var data transfertypes.FungibleTokenPacketData + if err := json.Unmarshal(packet.GetData(), &data); err != nil { + panic("unable to unmarshal ICS20 packet data") + } + + var denom string + if transfertypes.ReceiverChainIsSource(packet.GetSourcePort(), packet.GetSourceChannel(), data.Denom) { + // remove prefix added by sender chain + voucherPrefix := transfertypes.GetDenomPrefix(packet.GetSourcePort(), packet.GetSourceChannel()) + + unprefixedDenom := data.Denom[len(voucherPrefix):] + + // coin denomination used in sending from the escrow address + denom = unprefixedDenom + + // The denomination used to send the coins is either the native denom or the hash of the path + // if the denomination is not native. + denomTrace := transfertypes.ParseDenomTrace(unprefixedDenom) + if denomTrace.Path != "" { + denom = denomTrace.IBCDenom() + } + } else { + prefixedDenom := transfertypes.GetDenomPrefix(packet.GetDestPort(), packet.GetDestChannel()) + data.Denom + denom = transfertypes.ParseDenomTrace(prefixedDenom).IBCDenom() + } + return denom +} + +// IsAckError checks an IBC acknowledgement to see if it's an error. +// This is a replacement for ack.Success() which is currently not working on some circumstances +func IsAckError(acknowledgement []byte) bool { + var ackErr channeltypes.Acknowledgement_Error + if err := json.Unmarshal(acknowledgement, &ackErr); err == nil && len(ackErr.Error) > 0 { + return true + } + return false +} diff --git a/proto/Dockerfile b/proto/Dockerfile deleted file mode 100644 index f5e6f16..0000000 --- a/proto/Dockerfile +++ /dev/null @@ -1,39 +0,0 @@ -# This Dockerfile is used for proto generation -# To build, run `make proto-image-build` - -FROM bufbuild/buf:1.7.0 as BUILDER - -FROM golang:1.19-alpine - - -RUN apk add --no-cache \ - nodejs \ - npm \ - git \ - make - -ENV GOLANG_PROTOBUF_VERSION=1.28.0 \ - GOGO_PROTOBUF_VERSION=1.3.2 \ - GRPC_GATEWAY_VERSION=1.16.0 - - -RUN go install github.com/cosmos/cosmos-proto/cmd/protoc-gen-go-pulsar@latest -RUN go install google.golang.org/protobuf/cmd/protoc-gen-go@v${GOLANG_PROTOBUF_VERSION} -RUN go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v${GRPC_GATEWAY_VERSION} \ - github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@v${GRPC_GATEWAY_VERSION} - -# install all gogo protobuf binaries -RUN git clone https://github.com/regen-network/protobuf.git; \ - cd protobuf; \ - go mod download; \ - make install - -# we need to use git clone because we use 'replace' directive in go.mod -# protoc-gen-gocosmos was moved to to in cosmos/gogoproto but pending a migration there. -RUN git clone https://github.com/regen-network/cosmos-proto.git; \ - cd cosmos-proto/protoc-gen-gocosmos; \ - go install . - -RUN npm install -g swagger-combine - -COPY --from=BUILDER /usr/local/bin /usr/local/bin diff --git a/proto/buf.gen.gogo.yml b/proto/buf.gen.gogo.yml deleted file mode 100644 index 855ea25..0000000 --- a/proto/buf.gen.gogo.yml +++ /dev/null @@ -1,8 +0,0 @@ -version: v1 -plugins: - - name: gocosmos - out: .. - opt: plugins=grpc,Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types - - name: grpc-gateway - out: .. - opt: logtostderr=true,allow_colon_final_segments=true \ No newline at end of file diff --git a/proto/buf.lock b/proto/buf.lock index 9de2779..f802501 100644 --- a/proto/buf.lock +++ b/proto/buf.lock @@ -5,15 +5,19 @@ deps: owner: cosmos repository: cosmos-proto commit: 1935555c206d4afb9e94615dfd0fad31 + digest: shake256:c74d91a3ac7ae07d579e90eee33abf9b29664047ac8816500cf22c081fec0d72d62c89ce0bebafc1f6fec7aa5315be72606717740ca95007248425102c365377 - remote: buf.build owner: cosmos repository: cosmos-sdk commit: 954f7b05f38440fc8250134b15adec47 + digest: shake256:2ab4404fd04a7d1d52df0e2d0f2d477a3d83ffd88d876957bf3fedfd702c8e52833d65b3ce1d89a3c5adf2aab512616b0e4f51d8463f07eda9a8a3317ee3ac54 - remote: buf.build owner: cosmos repository: gogo-proto - commit: 34d970b699f84aa382f3c29773a60836 + commit: 5e5b9fdd01804356895f8f79a6f1ddc1 + digest: shake256:0b85da49e2e5f9ebc4806eae058e2f56096ff3b1c59d1fb7c190413dd15f45dd456f0b69ced9059341c80795d2b6c943de15b120a9e0308b499e43e4b5fc2952 - remote: buf.build owner: googleapis repository: googleapis - commit: 75b4300737fb4efca0831636be94e517 + commit: 28151c0d0a1641bf938a7672c500e01d + digest: shake256:49215edf8ef57f7863004539deff8834cfb2195113f0b890dd1f67815d9353e28e668019165b9d872395871eeafcbab3ccfdb2b5f11734d3cca95be9e8d139de diff --git a/proto/buf.md b/proto/buf.md deleted file mode 100644 index d81eb01..0000000 --- a/proto/buf.md +++ /dev/null @@ -1,18 +0,0 @@ -# Protobufs - -This is the public protocol buffers API for [Terpd](https://github.com/terpnetwork/terp-core). -## Download - -The `buf` CLI comes with an export command. Use `buf export -h` for details - -#### Examples: - -Download cosmwasm protos for a commit: -```bash -buf export buf.build/terpnetwork/terpd:${commit} --output ./tmp -``` - -Download all project protos: -```bash -buf export . --output ./tmp -``` \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/authz.proto b/proto/cosmwasm/wasm/v1/authz.proto deleted file mode 100644 index ce10a3d..0000000 --- a/proto/cosmwasm/wasm/v1/authz.proto +++ /dev/null @@ -1,131 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "google/protobuf/any.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; - -// ContractExecutionAuthorization defines authorization for wasm execute. -// Since: wasmd 0.30 -message ContractExecutionAuthorization { - option (amino.name) = "wasm/ContractExecutionAuthorization"; - option (cosmos_proto.implements_interface) = - "cosmos.authz.v1beta1.Authorization"; - - // Grants for contract executions - repeated ContractGrant grants = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// ContractMigrationAuthorization defines authorization for wasm contract -// migration. Since: wasmd 0.30 -message ContractMigrationAuthorization { - option (amino.name) = "wasm/ContractMigrationAuthorization"; - option (cosmos_proto.implements_interface) = - "cosmos.authz.v1beta1.Authorization"; - - // Grants for contract migrations - repeated ContractGrant grants = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// ContractGrant a granted permission for a single contract -// Since: wasmd 0.30 -message ContractGrant { - // Contract is the bech32 address of the smart contract - string contract = 1; - - // Limit defines execution limits that are enforced and updated when the grant - // is applied. When the limit lapsed the grant is removed. - google.protobuf.Any limit = 2 [ (cosmos_proto.accepts_interface) = - "cosmwasm.wasm.v1.ContractAuthzLimitX" ]; - - // Filter define more fine-grained control on the message payload passed - // to the contract in the operation. When no filter applies on execution, the - // operation is prohibited. - google.protobuf.Any filter = 3 - [ (cosmos_proto.accepts_interface) = - "cosmwasm.wasm.v1.ContractAuthzFilterX" ]; -} - -// MaxCallsLimit limited number of calls to the contract. No funds transferable. -// Since: wasmd 0.30 -message MaxCallsLimit { - option (amino.name) = "wasm/MaxCallsLimit"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzLimitX"; - - // Remaining number that is decremented on each execution - uint64 remaining = 1; -} - -// MaxFundsLimit defines the maximal amounts that can be sent to the contract. -// Since: wasmd 0.30 -message MaxFundsLimit { - option (amino.name) = "wasm/MaxFundsLimit"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzLimitX"; - - // Amounts is the maximal amount of tokens transferable to the contract. - repeated cosmos.base.v1beta1.Coin amounts = 1 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// CombinedLimit defines the maximal amounts that can be sent to a contract and -// the maximal number of calls executable. Both need to remain >0 to be valid. -// Since: wasmd 0.30 -message CombinedLimit { - option (amino.name) = "wasm/CombinedLimit"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzLimitX"; - - // Remaining number that is decremented on each execution - uint64 calls_remaining = 1; - // Amounts is the maximal amount of tokens transferable to the contract. - repeated cosmos.base.v1beta1.Coin amounts = 2 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// AllowAllMessagesFilter is a wildcard to allow any type of contract payload -// message. -// Since: wasmd 0.30 -message AllowAllMessagesFilter { - option (amino.name) = "wasm/AllowAllMessagesFilter"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzFilterX"; -} - -// AcceptedMessageKeysFilter accept only the specific contract message keys in -// the json object to be executed. -// Since: wasmd 0.30 -message AcceptedMessageKeysFilter { - option (amino.name) = "wasm/AcceptedMessageKeysFilter"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzFilterX"; - - // Messages is the list of unique keys - repeated string keys = 1; -} - -// AcceptedMessagesFilter accept only the specific raw contract messages to be -// executed. -// Since: wasmd 0.30 -message AcceptedMessagesFilter { - option (amino.name) = "wasm/AcceptedMessagesFilter"; - option (cosmos_proto.implements_interface) = - "cosmwasm.wasm.v1.ContractAuthzFilterX"; - - // Messages is the list of raw contract messages - repeated bytes messages = 1 [ (gogoproto.casttype) = "RawContractMessage" ]; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/genesis.proto b/proto/cosmwasm/wasm/v1/genesis.proto deleted file mode 100644 index 898ccee..0000000 --- a/proto/cosmwasm/wasm/v1/genesis.proto +++ /dev/null @@ -1,56 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; -import "cosmwasm/wasm/v1/types.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; - -// GenesisState - genesis state of x/wasm -message GenesisState { - Params params = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - repeated Code codes = 2 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.jsontag) = "codes,omitempty" - ]; - repeated Contract contracts = 3 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.jsontag) = "contracts,omitempty" - ]; - repeated Sequence sequences = 4 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.jsontag) = "sequences,omitempty" - ]; -} - -// Code struct encompasses CodeInfo and CodeBytes -message Code { - uint64 code_id = 1 [ (gogoproto.customname) = "CodeID" ]; - CodeInfo code_info = 2 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - bytes code_bytes = 3; - // Pinned to wasmvm cache - bool pinned = 4; -} - -// Contract struct encompasses ContractAddress, ContractInfo, and ContractState -message Contract { - string contract_address = 1; - ContractInfo contract_info = 2 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - repeated Model contract_state = 3 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - repeated ContractCodeHistoryEntry contract_code_history = 4 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// Sequence key and value of an id generation counter -message Sequence { - bytes id_key = 1 [ (gogoproto.customname) = "IDKey" ]; - uint64 value = 2; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/ibc.proto b/proto/cosmwasm/wasm/v1/ibc.proto deleted file mode 100644 index 196387b..0000000 --- a/proto/cosmwasm/wasm/v1/ibc.proto +++ /dev/null @@ -1,37 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; - -// MsgIBCSend -message MsgIBCSend { - // the channel by which the packet will be sent - string channel = 2 [ (gogoproto.moretags) = "yaml:\"source_channel\"" ]; - - // Timeout height relative to the current block height. - // The timeout is disabled when set to 0. - uint64 timeout_height = 4 - [ (gogoproto.moretags) = "yaml:\"timeout_height\"" ]; - // Timeout timestamp (in nanoseconds) relative to the current block timestamp. - // The timeout is disabled when set to 0. - uint64 timeout_timestamp = 5 - [ (gogoproto.moretags) = "yaml:\"timeout_timestamp\"" ]; - - // Data is the payload to transfer. We must not make assumption what format or - // content is in here. - bytes data = 6; -} - -// MsgIBCSendResponse -message MsgIBCSendResponse { - // Sequence number of the IBC packet sent - uint64 sequence = 1; -} - -// MsgIBCCloseChannel port and channel need to be owned by the contract -message MsgIBCCloseChannel { - string channel = 2 [ (gogoproto.moretags) = "yaml:\"source_channel\"" ]; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/proposal.proto b/proto/cosmwasm/wasm/v1/proposal.proto deleted file mode 100644 index f411345..0000000 --- a/proto/cosmwasm/wasm/v1/proposal.proto +++ /dev/null @@ -1,329 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; -import "cosmos/base/v1beta1/coin.proto"; -import "cosmwasm/wasm/v1/types.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_stringer_all) = false; -option (gogoproto.goproto_getters_all) = false; -option (gogoproto.equal_all) = true; - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit StoreCodeProposal. To submit WASM code to the system, -// a simple MsgStoreCode can be invoked from the x/gov module via -// a v1 governance proposal. -message StoreCodeProposal { - option deprecated = true; - option (amino.name) = "wasm/StoreCodeProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's environment as sender - string run_as = 3; - // WASMByteCode can be raw or gzip compressed - bytes wasm_byte_code = 4 [ (gogoproto.customname) = "WASMByteCode" ]; - // Used in v1beta1 - reserved 5, 6; - // InstantiatePermission to apply on contract creation, optional - AccessConfig instantiate_permission = 7; - // UnpinCode code on upload, optional - bool unpin_code = 8; - // Source is the URL where the code is hosted - string source = 9; - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - string builder = 10; - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - bytes code_hash = 11; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit InstantiateContractProposal. To instantiate a contract, -// a simple MsgInstantiateContract can be invoked from the x/gov module via -// a v1 governance proposal. -message InstantiateContractProposal { - option deprecated = true; - option (amino.name) = "wasm/InstantiateContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's environment as sender - string run_as = 3; - // Admin is an optional address that can execute migrations - string admin = 4; - // CodeID is the reference to the stored WASM code - uint64 code_id = 5 [ (gogoproto.customname) = "CodeID" ]; - // Label is optional metadata to be stored with a constract instance. - string label = 6; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 7 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 8 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit InstantiateContract2Proposal. To instantiate contract 2, -// a simple MsgInstantiateContract2 can be invoked from the x/gov module via -// a v1 governance proposal. -message InstantiateContract2Proposal { - option deprecated = true; - option (amino.name) = "wasm/InstantiateContract2Proposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's enviroment as sender - string run_as = 3; - // Admin is an optional address that can execute migrations - string admin = 4; - // CodeID is the reference to the stored WASM code - uint64 code_id = 5 [ (gogoproto.customname) = "CodeID" ]; - // Label is optional metadata to be stored with a constract instance. - string label = 6; - // Msg json encode message to be passed to the contract on instantiation - bytes msg = 7 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 8 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - // Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - bytes salt = 9; - // FixMsg include the msg value into the hash for the predictable address. - // Default is false - bool fix_msg = 10; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit MigrateContractProposal. To migrate a contract, -// a simple MsgMigrateContract can be invoked from the x/gov module via -// a v1 governance proposal. -message MigrateContractProposal { - option deprecated = true; - option (amino.name) = "wasm/MigrateContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // Note: skipping 3 as this was previously used for unneeded run_as - - // Contract is the address of the smart contract - string contract = 4; - // CodeID references the new WASM code - uint64 code_id = 5 [ (gogoproto.customname) = "CodeID" ]; - // Msg json encoded message to be passed to the contract on migration - bytes msg = 6 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit SudoContractProposal. To call sudo on a contract, -// a simple MsgSudoContract can be invoked from the x/gov module via -// a v1 governance proposal. -message SudoContractProposal { - option deprecated = true; - option (amino.name) = "wasm/SudoContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // Contract is the address of the smart contract - string contract = 3; - // Msg json encoded message to be passed to the contract as sudo - bytes msg = 4 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit ExecuteContractProposal. To call execute on a contract, -// a simple MsgExecuteContract can be invoked from the x/gov module via -// a v1 governance proposal. -message ExecuteContractProposal { - option deprecated = true; - option (amino.name) = "wasm/ExecuteContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's environment as sender - string run_as = 3; - // Contract is the address of the smart contract - string contract = 4; - // Msg json encoded message to be passed to the contract as execute - bytes msg = 5 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 6 [ - (gogoproto.nullable) = false, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UpdateAdminProposal. To set an admin for a contract, -// a simple MsgUpdateAdmin can be invoked from the x/gov module via -// a v1 governance proposal. -message UpdateAdminProposal { - option deprecated = true; - option (amino.name) = "wasm/UpdateAdminProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // NewAdmin address to be set - string new_admin = 3 [ (gogoproto.moretags) = "yaml:\"new_admin\"" ]; - // Contract is the address of the smart contract - string contract = 4; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit ClearAdminProposal. To clear the admin of a contract, -// a simple MsgClearAdmin can be invoked from the x/gov module via -// a v1 governance proposal. -message ClearAdminProposal { - option deprecated = true; - option (amino.name) = "wasm/ClearAdminProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // Contract is the address of the smart contract - string contract = 3; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit PinCodesProposal. To pin a set of code ids in the wasmvm -// cache, a simple MsgPinCodes can be invoked from the x/gov module via -// a v1 governance proposal. -message PinCodesProposal { - option deprecated = true; - option (amino.name) = "wasm/PinCodesProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1 [ (gogoproto.moretags) = "yaml:\"title\"" ]; - // Description is a human readable text - string description = 2 [ (gogoproto.moretags) = "yaml:\"description\"" ]; - // CodeIDs references the new WASM codes - repeated uint64 code_ids = 3 [ - (gogoproto.customname) = "CodeIDs", - (gogoproto.moretags) = "yaml:\"code_ids\"" - ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UnpinCodesProposal. To unpin a set of code ids in the wasmvm -// cache, a simple MsgUnpinCodes can be invoked from the x/gov module via -// a v1 governance proposal. -message UnpinCodesProposal { - option deprecated = true; - option (amino.name) = "wasm/UnpinCodesProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1 [ (gogoproto.moretags) = "yaml:\"title\"" ]; - // Description is a human readable text - string description = 2 [ (gogoproto.moretags) = "yaml:\"description\"" ]; - // CodeIDs references the WASM codes - repeated uint64 code_ids = 3 [ - (gogoproto.customname) = "CodeIDs", - (gogoproto.moretags) = "yaml:\"code_ids\"" - ]; -} - -// AccessConfigUpdate contains the code id and the access config to be -// applied. -message AccessConfigUpdate { - // CodeID is the reference to the stored WASM code to be updated - uint64 code_id = 1 [ (gogoproto.customname) = "CodeID" ]; - // InstantiatePermission to apply to the set of code ids - AccessConfig instantiate_permission = 2 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UpdateInstantiateConfigProposal. To update instantiate config -// to a set of code ids, a simple MsgUpdateInstantiateConfig can be invoked from -// the x/gov module via a v1 governance proposal. -message UpdateInstantiateConfigProposal { - option deprecated = true; - option (amino.name) = "wasm/UpdateInstantiateConfigProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1 [ (gogoproto.moretags) = "yaml:\"title\"" ]; - // Description is a human readable text - string description = 2 [ (gogoproto.moretags) = "yaml:\"description\"" ]; - // AccessConfigUpdate contains the list of code ids and the access config - // to be applied. - repeated AccessConfigUpdate access_config_updates = 3 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit StoreAndInstantiateContractProposal. To store and instantiate -// the contract, a simple MsgStoreAndInstantiateContract can be invoked from -// the x/gov module via a v1 governance proposal. -message StoreAndInstantiateContractProposal { - option deprecated = true; - option (amino.name) = "wasm/StoreAndInstantiateContractProposal"; - option (cosmos_proto.implements_interface) = "cosmos.gov.v1beta1.Content"; - - // Title is a short summary - string title = 1; - // Description is a human readable text - string description = 2; - // RunAs is the address that is passed to the contract's environment as sender - string run_as = 3; - // WASMByteCode can be raw or gzip compressed - bytes wasm_byte_code = 4 [ (gogoproto.customname) = "WASMByteCode" ]; - // InstantiatePermission to apply on contract creation, optional - AccessConfig instantiate_permission = 5; - // UnpinCode code on upload, optional - bool unpin_code = 6; - // Admin is an optional address that can execute migrations - string admin = 7; - // Label is optional metadata to be stored with a constract instance. - string label = 8; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 9 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 10 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - // Source is the URL where the code is hosted - string source = 11; - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - string builder = 12; - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - bytes code_hash = 13; -} diff --git a/proto/cosmwasm/wasm/v1/query.proto b/proto/cosmwasm/wasm/v1/query.proto deleted file mode 100644 index 5a2039b..0000000 --- a/proto/cosmwasm/wasm/v1/query.proto +++ /dev/null @@ -1,268 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "gogoproto/gogo.proto"; -import "cosmwasm/wasm/v1/types.proto"; -import "google/api/annotations.proto"; -import "cosmos/base/query/v1beta1/pagination.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; -option (gogoproto.equal_all) = false; - -// Query provides defines the gRPC querier service -service Query { - // ContractInfo gets the contract meta data - rpc ContractInfo(QueryContractInfoRequest) - returns (QueryContractInfoResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/contract/{address}"; - } - // ContractHistory gets the contract code history - rpc ContractHistory(QueryContractHistoryRequest) - returns (QueryContractHistoryResponse) { - option (google.api.http).get = - "/cosmwasm/wasm/v1/contract/{address}/history"; - } - // ContractsByCode lists all smart contracts for a code id - rpc ContractsByCode(QueryContractsByCodeRequest) - returns (QueryContractsByCodeResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/code/{code_id}/contracts"; - } - // AllContractState gets all raw store data for a single contract - rpc AllContractState(QueryAllContractStateRequest) - returns (QueryAllContractStateResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/contract/{address}/state"; - } - // RawContractState gets single key from the raw store data of a contract - rpc RawContractState(QueryRawContractStateRequest) - returns (QueryRawContractStateResponse) { - option (google.api.http).get = - "/cosmwasm/wasm/v1/contract/{address}/raw/{query_data}"; - } - // SmartContractState get smart query result from the contract - rpc SmartContractState(QuerySmartContractStateRequest) - returns (QuerySmartContractStateResponse) { - option (google.api.http).get = - "/cosmwasm/wasm/v1/contract/{address}/smart/{query_data}"; - } - // Code gets the binary code and metadata for a singe wasm code - rpc Code(QueryCodeRequest) returns (QueryCodeResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/code/{code_id}"; - } - // Codes gets the metadata for all stored wasm codes - rpc Codes(QueryCodesRequest) returns (QueryCodesResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/code"; - } - - // PinnedCodes gets the pinned code ids - rpc PinnedCodes(QueryPinnedCodesRequest) returns (QueryPinnedCodesResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/codes/pinned"; - } - - // Params gets the module params - rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/cosmwasm/wasm/v1/codes/params"; - } - - // ContractsByCreator gets the contracts by creator - rpc ContractsByCreator(QueryContractsByCreatorRequest) - returns (QueryContractsByCreatorResponse) { - option (google.api.http).get = - "/cosmwasm/wasm/v1/contracts/creator/{creator_address}"; - } -} - -// QueryContractInfoRequest is the request type for the Query/ContractInfo RPC -// method -message QueryContractInfoRequest { - // address is the address of the contract to query - string address = 1; -} -// QueryContractInfoResponse is the response type for the Query/ContractInfo RPC -// method -message QueryContractInfoResponse { - option (gogoproto.equal) = true; - - // address is the address of the contract - string address = 1; - ContractInfo contract_info = 2 [ - (gogoproto.embed) = true, - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.jsontag) = "" - ]; -} - -// QueryContractHistoryRequest is the request type for the Query/ContractHistory -// RPC method -message QueryContractHistoryRequest { - // address is the address of the contract to query - string address = 1; - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryContractHistoryResponse is the response type for the -// Query/ContractHistory RPC method -message QueryContractHistoryResponse { - repeated ContractCodeHistoryEntry entries = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryContractsByCodeRequest is the request type for the Query/ContractsByCode -// RPC method -message QueryContractsByCodeRequest { - uint64 code_id = 1; // grpc-gateway_out does not support Go style CodID - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryContractsByCodeResponse is the response type for the -// Query/ContractsByCode RPC method -message QueryContractsByCodeResponse { - // contracts are a set of contract addresses - repeated string contracts = 1; - - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryAllContractStateRequest is the request type for the -// Query/AllContractState RPC method -message QueryAllContractStateRequest { - // address is the address of the contract - string address = 1; - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryAllContractStateResponse is the response type for the -// Query/AllContractState RPC method -message QueryAllContractStateResponse { - repeated Model models = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryRawContractStateRequest is the request type for the -// Query/RawContractState RPC method -message QueryRawContractStateRequest { - // address is the address of the contract - string address = 1; - bytes query_data = 2; -} - -// QueryRawContractStateResponse is the response type for the -// Query/RawContractState RPC method -message QueryRawContractStateResponse { - // Data contains the raw store data - bytes data = 1; -} - -// QuerySmartContractStateRequest is the request type for the -// Query/SmartContractState RPC method -message QuerySmartContractStateRequest { - // address is the address of the contract - string address = 1; - // QueryData contains the query data passed to the contract - bytes query_data = 2 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// QuerySmartContractStateResponse is the response type for the -// Query/SmartContractState RPC method -message QuerySmartContractStateResponse { - // Data contains the json data returned from the smart contract - bytes data = 1 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// QueryCodeRequest is the request type for the Query/Code RPC method -message QueryCodeRequest { - uint64 code_id = 1; // grpc-gateway_out does not support Go style CodID -} - -// CodeInfoResponse contains code meta data from CodeInfo -message CodeInfoResponse { - option (gogoproto.equal) = true; - - uint64 code_id = 1 [ - (gogoproto.customname) = "CodeID", - (gogoproto.jsontag) = "id" - ]; // id for legacy support - string creator = 2; - bytes data_hash = 3 - [ (gogoproto.casttype) = - "github.com/cometbft/cometbft/libs/bytes.HexBytes" ]; - // Used in v1beta1 - reserved 4, 5; - AccessConfig instantiate_permission = 6 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// QueryCodeResponse is the response type for the Query/Code RPC method -message QueryCodeResponse { - option (gogoproto.equal) = true; - CodeInfoResponse code_info = 1 - [ (gogoproto.embed) = true, (gogoproto.jsontag) = "" ]; - bytes data = 2 [ (gogoproto.jsontag) = "data" ]; -} - -// QueryCodesRequest is the request type for the Query/Codes RPC method -message QueryCodesRequest { - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 1; -} - -// QueryCodesResponse is the response type for the Query/Codes RPC method -message QueryCodesResponse { - repeated CodeInfoResponse code_infos = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryPinnedCodesRequest is the request type for the Query/PinnedCodes -// RPC method -message QueryPinnedCodesRequest { - // pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryPinnedCodesResponse is the response type for the -// Query/PinnedCodes RPC method -message QueryPinnedCodesResponse { - repeated uint64 code_ids = 1 [ (gogoproto.customname) = "CodeIDs" ]; - // pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} - -// QueryParamsRequest is the request type for the Query/Params RPC method. -message QueryParamsRequest {} - -// QueryParamsResponse is the response type for the Query/Params RPC method. -message QueryParamsResponse { - // params defines the parameters of the module. - Params params = 1 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// QueryContractsByCreatorRequest is the request type for the -// Query/ContractsByCreator RPC method. -message QueryContractsByCreatorRequest { - // CreatorAddress is the address of contract creator - string creator_address = 1; - // Pagination defines an optional pagination for the request. - cosmos.base.query.v1beta1.PageRequest pagination = 2; -} - -// QueryContractsByCreatorResponse is the response type for the -// Query/ContractsByCreator RPC method. -message QueryContractsByCreatorResponse { - // ContractAddresses result set - repeated string contract_addresses = 1; - // Pagination defines the pagination in the response. - cosmos.base.query.v1beta1.PageResponse pagination = 2; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/tx.proto b/proto/cosmwasm/wasm/v1/tx.proto deleted file mode 100644 index 79a9930..0000000 --- a/proto/cosmwasm/wasm/v1/tx.proto +++ /dev/null @@ -1,391 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "cosmos/base/v1beta1/coin.proto"; -import "cosmos/msg/v1/msg.proto"; -import "gogoproto/gogo.proto"; -import "cosmwasm/wasm/v1/types.proto"; -import "cosmos_proto/cosmos.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; - -// Msg defines the wasm Msg service. -service Msg { - // StoreCode to submit Wasm code to the system - rpc StoreCode(MsgStoreCode) returns (MsgStoreCodeResponse); - // InstantiateContract creates a new smart contract instance for the given - // code id. - rpc InstantiateContract(MsgInstantiateContract) - returns (MsgInstantiateContractResponse); - // InstantiateContract2 creates a new smart contract instance for the given - // code id with a predictable address - rpc InstantiateContract2(MsgInstantiateContract2) - returns (MsgInstantiateContract2Response); - // Execute submits the given message data to a smart contract - rpc ExecuteContract(MsgExecuteContract) returns (MsgExecuteContractResponse); - // Migrate runs a code upgrade/ downgrade for a smart contract - rpc MigrateContract(MsgMigrateContract) returns (MsgMigrateContractResponse); - // UpdateAdmin sets a new admin for a smart contract - rpc UpdateAdmin(MsgUpdateAdmin) returns (MsgUpdateAdminResponse); - // ClearAdmin removes any admin stored for a smart contract - rpc ClearAdmin(MsgClearAdmin) returns (MsgClearAdminResponse); - // UpdateInstantiateConfig updates instantiate config for a smart contract - rpc UpdateInstantiateConfig(MsgUpdateInstantiateConfig) - returns (MsgUpdateInstantiateConfigResponse); - // UpdateParams defines a governance operation for updating the x/wasm - // module parameters. The authority is defined in the keeper. - // - // Since: 0.40 - rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); - // SudoContract defines a governance operation for calling sudo - // on a contract. The authority is defined in the keeper. - // - // Since: 0.40 - rpc SudoContract(MsgSudoContract) returns (MsgSudoContractResponse); - // PinCodes defines a governance operation for pinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - rpc PinCodes(MsgPinCodes) returns (MsgPinCodesResponse); - // UnpinCodes defines a governance operation for unpinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - rpc UnpinCodes(MsgUnpinCodes) returns (MsgUnpinCodesResponse); - // StoreAndInstantiateContract defines a governance operation for storing - // and instantiating the contract. The authority is defined in the keeper. - // - // Since: 0.40 - rpc StoreAndInstantiateContract(MsgStoreAndInstantiateContract) - returns (MsgStoreAndInstantiateContractResponse); -} - -// MsgStoreCode submit Wasm code to the system -message MsgStoreCode { - option (amino.name) = "wasm/MsgStoreCode"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the actor that signed the messages - string sender = 1; - // WASMByteCode can be raw or gzip compressed - bytes wasm_byte_code = 2 [ (gogoproto.customname) = "WASMByteCode" ]; - // Used in v1beta1 - reserved 3, 4; - // InstantiatePermission access control to apply on contract creation, - // optional - AccessConfig instantiate_permission = 5; -} -// MsgStoreCodeResponse returns store result data. -message MsgStoreCodeResponse { - // CodeID is the reference to the stored WASM code - uint64 code_id = 1 [ (gogoproto.customname) = "CodeID" ]; - // Checksum is the sha256 hash of the stored code - bytes checksum = 2; -} - -// MsgInstantiateContract create a new smart contract instance for the given -// code id. -message MsgInstantiateContract { - option (amino.name) = "wasm/MsgInstantiateContract"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // Admin is an optional address that can execute migrations - string admin = 2; - // CodeID is the reference to the stored WASM code - uint64 code_id = 3 [ (gogoproto.customname) = "CodeID" ]; - // Label is optional metadata to be stored with a contract instance. - string label = 4; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 5 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 6 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// MsgInstantiateContractResponse return instantiation result data -message MsgInstantiateContractResponse { - // Address is the bech32 address of the new contract instance. - string address = 1; - // Data contains bytes to returned from the contract - bytes data = 2; -} - -// MsgInstantiateContract2 create a new smart contract instance for the given -// code id with a predicable address. -message MsgInstantiateContract2 { - option (amino.name) = "wasm/MsgInstantiateContract2"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // Admin is an optional address that can execute migrations - string admin = 2; - // CodeID is the reference to the stored WASM code - uint64 code_id = 3 [ (gogoproto.customname) = "CodeID" ]; - // Label is optional metadata to be stored with a contract instance. - string label = 4; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 5 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on instantiation - repeated cosmos.base.v1beta1.Coin funds = 6 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - // Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - bytes salt = 7; - // FixMsg include the msg value into the hash for the predictable address. - // Default is false - bool fix_msg = 8; -} - -// MsgInstantiateContract2Response return instantiation result data -message MsgInstantiateContract2Response { - // Address is the bech32 address of the new contract instance. - string address = 1; - // Data contains bytes to returned from the contract - bytes data = 2; -} - -// MsgExecuteContract submits the given message data to a smart contract -message MsgExecuteContract { - option (amino.name) = "wasm/MsgExecuteContract"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // Contract is the address of the smart contract - string contract = 2; - // Msg json encoded message to be passed to the contract - bytes msg = 3 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred to the contract on execution - repeated cosmos.base.v1beta1.Coin funds = 5 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; -} - -// MsgExecuteContractResponse returns execution result data. -message MsgExecuteContractResponse { - // Data contains bytes to returned from the contract - bytes data = 1; -} - -// MsgMigrateContract runs a code upgrade/ downgrade for a smart contract -message MsgMigrateContract { - option (amino.name) = "wasm/MsgMigrateContract"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // Contract is the address of the smart contract - string contract = 2; - // CodeID references the new WASM code - uint64 code_id = 3 [ (gogoproto.customname) = "CodeID" ]; - // Msg json encoded message to be passed to the contract on migration - bytes msg = 4 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// MsgMigrateContractResponse returns contract migration result data. -message MsgMigrateContractResponse { - // Data contains same raw bytes returned as data from the wasm contract. - // (May be empty) - bytes data = 1; -} - -// MsgUpdateAdmin sets a new admin for a smart contract -message MsgUpdateAdmin { - option (amino.name) = "wasm/MsgUpdateAdmin"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // NewAdmin address to be set - string new_admin = 2; - // Contract is the address of the smart contract - string contract = 3; -} - -// MsgUpdateAdminResponse returns empty data -message MsgUpdateAdminResponse {} - -// MsgClearAdmin removes any admin stored for a smart contract -message MsgClearAdmin { - option (amino.name) = "wasm/MsgClearAdmin"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the actor that signed the messages - string sender = 1; - // Contract is the address of the smart contract - string contract = 3; -} - -// MsgClearAdminResponse returns empty data -message MsgClearAdminResponse {} - -// MsgUpdateInstantiateConfig updates instantiate config for a smart contract -message MsgUpdateInstantiateConfig { - option (amino.name) = "wasm/MsgUpdateInstantiateConfig"; - option (cosmos.msg.v1.signer) = "sender"; - - // Sender is the that actor that signed the messages - string sender = 1; - // CodeID references the stored WASM code - uint64 code_id = 2 [ (gogoproto.customname) = "CodeID" ]; - // NewInstantiatePermission is the new access control - AccessConfig new_instantiate_permission = 3; -} - -// MsgUpdateInstantiateConfigResponse returns empty data -message MsgUpdateInstantiateConfigResponse {} - -// MsgUpdateParams is the MsgUpdateParams request type. -// -// Since: 0.40 -message MsgUpdateParams { - option (amino.name) = "wasm/MsgUpdateParams"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - - // params defines the x/wasm parameters to update. - // - // NOTE: All parameters must be supplied. - Params params = 2 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. -// -// Since: 0.40 -message MsgUpdateParamsResponse {} - -// MsgSudoContract is the MsgSudoContract request type. -// -// Since: 0.40 -message MsgSudoContract { - option (amino.name) = "wasm/MsgSudoContract"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - - // Contract is the address of the smart contract - string contract = 2; - // Msg json encoded message to be passed to the contract as sudo - bytes msg = 3 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// MsgSudoContractResponse defines the response structure for executing a -// MsgSudoContract message. -// -// Since: 0.40 -message MsgSudoContractResponse { - // Data contains bytes to returned from the contract - bytes data = 1; -} - -// MsgPinCodes is the MsgPinCodes request type. -// -// Since: 0.40 -message MsgPinCodes { - option (amino.name) = "wasm/MsgPinCodes"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - // CodeIDs references the new WASM codes - repeated uint64 code_ids = 2 [ - (gogoproto.customname) = "CodeIDs", - (gogoproto.moretags) = "yaml:\"code_ids\"" - ]; -} - -// MsgPinCodesResponse defines the response structure for executing a -// MsgPinCodes message. -// -// Since: 0.40 -message MsgPinCodesResponse {} - -// MsgUnpinCodes is the MsgUnpinCodes request type. -// -// Since: 0.40 -message MsgUnpinCodes { - option (amino.name) = "wasm/MsgUnpinCodes"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - // CodeIDs references the WASM codes - repeated uint64 code_ids = 2 [ - (gogoproto.customname) = "CodeIDs", - (gogoproto.moretags) = "yaml:\"code_ids\"" - ]; -} - -// MsgUnpinCodesResponse defines the response structure for executing a -// MsgUnpinCodes message. -// -// Since: 0.40 -message MsgUnpinCodesResponse {} - -// MsgStoreAndInstantiateContract is the MsgStoreAndInstantiateContract -// request type. -// -// Since: 0.40 -message MsgStoreAndInstantiateContract { - option (amino.name) = "wasm/MsgStoreAndInstantiateContract"; - option (cosmos.msg.v1.signer) = "authority"; - - // Authority is the address of the governance account. - string authority = 1 [ (cosmos_proto.scalar) = "cosmos.AddressString" ]; - // WASMByteCode can be raw or gzip compressed - bytes wasm_byte_code = 3 [ (gogoproto.customname) = "WASMByteCode" ]; - // InstantiatePermission to apply on contract creation, optional - AccessConfig instantiate_permission = 4; - // UnpinCode code on upload, optional. As default the uploaded contract is - // pinned to cache. - bool unpin_code = 5; - // Admin is an optional address that can execute migrations - string admin = 6; - // Label is optional metadata to be stored with a constract instance. - string label = 7; - // Msg json encoded message to be passed to the contract on instantiation - bytes msg = 8 [ (gogoproto.casttype) = "RawContractMessage" ]; - // Funds coins that are transferred from the authority account to the contract - // on instantiation - repeated cosmos.base.v1beta1.Coin funds = 9 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins" - ]; - // Source is the URL where the code is hosted - string source = 10; - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - string builder = 11; - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - bytes code_hash = 12; -} - -// MsgStoreAndInstantiateContractResponse defines the response structure -// for executing a MsgStoreAndInstantiateContract message. -// -// Since: 0.40 -message MsgStoreAndInstantiateContractResponse { - // Address is the bech32 address of the new contract instance. - string address = 1; - // Data contains bytes to returned from the contract - bytes data = 2; -} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/types.proto b/proto/cosmwasm/wasm/v1/types.proto deleted file mode 100644 index 1572b5a..0000000 --- a/proto/cosmwasm/wasm/v1/types.proto +++ /dev/null @@ -1,148 +0,0 @@ -syntax = "proto3"; -package cosmwasm.wasm.v1; - -import "cosmos_proto/cosmos.proto"; -import "gogoproto/gogo.proto"; -import "google/protobuf/any.proto"; -import "amino/amino.proto"; - -option go_package = "github.com/terpnetwork/terp-core/x/wasm/types"; -option (gogoproto.goproto_getters_all) = false; -option (gogoproto.equal_all) = true; - -// AccessType permission types -enum AccessType { - option (gogoproto.goproto_enum_prefix) = false; - option (gogoproto.goproto_enum_stringer) = false; - // AccessTypeUnspecified placeholder for empty value - ACCESS_TYPE_UNSPECIFIED = 0 - [ (gogoproto.enumvalue_customname) = "AccessTypeUnspecified" ]; - // AccessTypeNobody forbidden - ACCESS_TYPE_NOBODY = 1 - [ (gogoproto.enumvalue_customname) = "AccessTypeNobody" ]; - // AccessTypeOnlyAddress restricted to a single address - // Deprecated: use AccessTypeAnyOfAddresses instead - ACCESS_TYPE_ONLY_ADDRESS = 2 - [ (gogoproto.enumvalue_customname) = "AccessTypeOnlyAddress" ]; - // AccessTypeEverybody unrestricted - ACCESS_TYPE_EVERYBODY = 3 - [ (gogoproto.enumvalue_customname) = "AccessTypeEverybody" ]; - // AccessTypeAnyOfAddresses allow any of the addresses - ACCESS_TYPE_ANY_OF_ADDRESSES = 4 - [ (gogoproto.enumvalue_customname) = "AccessTypeAnyOfAddresses" ]; -} - -// AccessTypeParam -message AccessTypeParam { - option (gogoproto.goproto_stringer) = true; - AccessType value = 1 [ (gogoproto.moretags) = "yaml:\"value\"" ]; -} - -// AccessConfig access control type. -message AccessConfig { - option (gogoproto.goproto_stringer) = true; - AccessType permission = 1 [ (gogoproto.moretags) = "yaml:\"permission\"" ]; - - // Address - // Deprecated: replaced by addresses - string address = 2 [ (gogoproto.moretags) = "yaml:\"address\"" ]; - repeated string addresses = 3 [ (gogoproto.moretags) = "yaml:\"addresses\"" ]; -} - -// Params defines the set of wasm parameters. -message Params { - option (gogoproto.goproto_stringer) = false; - AccessConfig code_upload_access = 1 [ - (gogoproto.nullable) = false, - (amino.dont_omitempty) = true, - (gogoproto.moretags) = "yaml:\"code_upload_access\"" - ]; - AccessType instantiate_default_permission = 2 - [ (gogoproto.moretags) = "yaml:\"instantiate_default_permission\"" ]; -} - -// CodeInfo is data for the uploaded contract WASM code -message CodeInfo { - // CodeHash is the unique identifier created by wasmvm - bytes code_hash = 1; - // Creator address who initially stored the code - string creator = 2; - // Used in v1beta1 - reserved 3, 4; - // InstantiateConfig access control to apply on contract creation, optional - AccessConfig instantiate_config = 5 - [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; -} - -// ContractInfo stores a WASM contract instance -message ContractInfo { - option (gogoproto.equal) = true; - - // CodeID is the reference to the stored Wasm code - uint64 code_id = 1 [ (gogoproto.customname) = "CodeID" ]; - // Creator address who initially instantiated the contract - string creator = 2; - // Admin is an optional address that can execute migrations - string admin = 3; - // Label is optional metadata to be stored with a contract instance. - string label = 4; - // Created Tx position when the contract was instantiated. - AbsoluteTxPosition created = 5; - string ibc_port_id = 6 [ (gogoproto.customname) = "IBCPortID" ]; - - // Extension is an extension point to store custom metadata within the - // persistence model. - google.protobuf.Any extension = 7 - [ (cosmos_proto.accepts_interface) = - "cosmwasm.wasm.v1.ContractInfoExtension" ]; -} - -// ContractCodeHistoryOperationType actions that caused a code change -enum ContractCodeHistoryOperationType { - option (gogoproto.goproto_enum_prefix) = false; - // ContractCodeHistoryOperationTypeUnspecified placeholder for empty value - CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED = 0 - [ (gogoproto.enumvalue_customname) = - "ContractCodeHistoryOperationTypeUnspecified" ]; - // ContractCodeHistoryOperationTypeInit on chain contract instantiation - CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT = 1 - [ (gogoproto.enumvalue_customname) = - "ContractCodeHistoryOperationTypeInit" ]; - // ContractCodeHistoryOperationTypeMigrate code migration - CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE = 2 - [ (gogoproto.enumvalue_customname) = - "ContractCodeHistoryOperationTypeMigrate" ]; - // ContractCodeHistoryOperationTypeGenesis based on genesis data - CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS = 3 - [ (gogoproto.enumvalue_customname) = - "ContractCodeHistoryOperationTypeGenesis" ]; -} - -// ContractCodeHistoryEntry metadata to a contract. -message ContractCodeHistoryEntry { - ContractCodeHistoryOperationType operation = 1; - // CodeID is the reference to the stored WASM code - uint64 code_id = 2 [ (gogoproto.customname) = "CodeID" ]; - // Updated Tx position when the operation was executed. - AbsoluteTxPosition updated = 3; - bytes msg = 4 [ (gogoproto.casttype) = "RawContractMessage" ]; -} - -// AbsoluteTxPosition is a unique transaction position that allows for global -// ordering of transactions. -message AbsoluteTxPosition { - // BlockHeight is the block the contract was created at - uint64 block_height = 1; - // TxIndex is a monotonic counter within the block (actual transaction index, - // or gas consumed) - uint64 tx_index = 2; -} - -// Model is a struct that holds a KV pair -message Model { - // hex-encode key to read it better (this is often ascii) - bytes key = 1 [ (gogoproto.casttype) = - "github.com/cometbft/cometbft/libs/bytes.HexBytes" ]; - // base64-encode raw value - bytes value = 2; -} \ No newline at end of file diff --git a/proto/gaia/globalfee/v1beta1/genesis.proto b/proto/gaia/globalfee/v1beta1/genesis.proto new file mode 100644 index 0000000..39493b0 --- /dev/null +++ b/proto/gaia/globalfee/v1beta1/genesis.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; +package gaia.globalfee.v1beta1; + +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; + +option go_package = "github.com/cosmos/gaia/x/globalfee/types"; + +// GenesisState - initial state of module +message GenesisState { + // Params of this module + Params params = 1 [ + (gogoproto.nullable) = false, + (gogoproto.jsontag) = "params,omitempty" + ]; +} + +// Params defines the set of module parameters. +message Params { + // Minimum stores the minimum gas price(s) for all TX on the chain. + // When multiple coins are defined then they are accepted alternatively. + // The list must be sorted by denoms asc. No duplicate denoms or zero amount + // values allowed. For more information see + // https://docs.cosmos.network/main/modules/auth#concepts + repeated cosmos.base.v1beta1.DecCoin minimum_gas_prices = 1 [ + (gogoproto.nullable) = false, + (gogoproto.jsontag) = "minimum_gas_prices,omitempty", + (gogoproto.moretags) = "yaml:\"minimum_gas_prices\"", + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.DecCoins" + ]; +} diff --git a/proto/gaia/globalfee/v1beta1/query.proto b/proto/gaia/globalfee/v1beta1/query.proto new file mode 100644 index 0000000..6d2cc11 --- /dev/null +++ b/proto/gaia/globalfee/v1beta1/query.proto @@ -0,0 +1,33 @@ +syntax = "proto3"; +package gaia.globalfee.v1beta1; + +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "cosmos/base/v1beta1/coin.proto"; + +option go_package = "github.com/cosmos/gaia/x/globalfee/types"; + +// Query defines the gRPC querier service. +service Query { + // MinimumGasPrices returns the minimum gas prices. + rpc MinimumGasPrices(QueryMinimumGasPricesRequest) + returns (QueryMinimumGasPricesResponse) { + option (google.api.http).get = + "/gaia/globalfee/v1beta1/minimum_gas_prices"; + } +} + +// QueryMinimumGasPricesRequest is the request type for the +// Query/MinimumGasPrices RPC method. +message QueryMinimumGasPricesRequest {} + +// QueryMinimumGasPricesResponse is the response type for the +// Query/MinimumGasPrices RPC method. +message QueryMinimumGasPricesResponse { + repeated cosmos.base.v1beta1.DecCoin minimum_gas_prices = 1 [ + (gogoproto.nullable) = false, + (gogoproto.jsontag) = "minimum_gas_prices,omitempty", + (gogoproto.moretags) = "yaml:\"minimum_gas_prices\"", + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.DecCoins" + ]; +} diff --git a/proto/gaia/globalfee/v1beta1/tx.proto b/proto/gaia/globalfee/v1beta1/tx.proto new file mode 100644 index 0000000..3db2354 --- /dev/null +++ b/proto/gaia/globalfee/v1beta1/tx.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; +package gaia.globalfee.v1beta1; + +option go_package = "github.com/cosmos/gaia/x/globalfee/types"; + +import "cosmos/msg/v1/msg.proto"; +import "gaia/globalfee/v1beta1/genesis.proto"; +import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; + +// Msg defines the x/globalfee Msg service. +service Msg { + // UpdateParams defines a governance operation for updating the x/mint module + // parameters. The authority is hard-coded to the x/gov module account. + // + // Since: cosmos-sdk 0.47 + rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); +} + +// MsgUpdateParams is the Msg/UpdateParams request type. +// +// Since: cosmos-sdk 0.47 +message MsgUpdateParams { + option (cosmos.msg.v1.signer) = "authority"; + + // authority is the address of the governance account. + string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // params defines the x/mint parameters to update. + // + // NOTE: All parameters must be supplied. + Params params = 2 [(gogoproto.nullable) = false]; +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +// +// Since: cosmos-sdk 0.47 +message MsgUpdateParamsResponse {} + \ No newline at end of file diff --git a/proto/cosmwasm/tokenfactory/v1beta1/authority_metadata.proto b/proto/osmosis/tokenfactory/v1beta1/authorityMetadata.proto similarity index 77% rename from proto/cosmwasm/tokenfactory/v1beta1/authority_metadata.proto rename to proto/osmosis/tokenfactory/v1beta1/authorityMetadata.proto index 3d27b3d..347e53c 100644 --- a/proto/cosmwasm/tokenfactory/v1beta1/authority_metadata.proto +++ b/proto/osmosis/tokenfactory/v1beta1/authorityMetadata.proto @@ -1,10 +1,10 @@ syntax = "proto3"; package osmosis.tokenfactory.v1beta1; -import "cosmos/base/v1beta1/coin.proto"; import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; +option go_package = "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types"; // DenomAuthorityMetadata specifies metadata for addresses that have specific // capabilities over a token factory denom. Right now there is only one Admin @@ -12,6 +12,6 @@ option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; message DenomAuthorityMetadata { option (gogoproto.equal) = true; - // Can be empty for no admin, or a valid terp address + // Can be empty for no admin, or a valid osmosis address string admin = 1 [ (gogoproto.moretags) = "yaml:\"admin\"" ]; } \ No newline at end of file diff --git a/proto/cosmwasm/tokenfactory/v1beta1/genesis.proto b/proto/osmosis/tokenfactory/v1beta1/genesis.proto similarity index 81% rename from proto/cosmwasm/tokenfactory/v1beta1/genesis.proto rename to proto/osmosis/tokenfactory/v1beta1/genesis.proto index 8b123c5..39147b1 100644 --- a/proto/cosmwasm/tokenfactory/v1beta1/genesis.proto +++ b/proto/osmosis/tokenfactory/v1beta1/genesis.proto @@ -2,10 +2,10 @@ syntax = "proto3"; package osmosis.tokenfactory.v1beta1; import "gogoproto/gogo.proto"; -import "cosmwasm/tokenfactory/v1beta1/authority_metadata.proto"; -import "cosmwasm/tokenfactory/v1beta1/params.proto"; +import "osmosis/tokenfactory/v1beta1/authorityMetadata.proto"; +import "osmosis/tokenfactory/v1beta1/params.proto"; -option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; +option go_package = "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types"; // GenesisState defines the tokenfactory module's genesis state. message GenesisState { diff --git a/proto/cosmwasm/tokenfactory/v1beta1/params.proto b/proto/osmosis/tokenfactory/v1beta1/params.proto similarity index 50% rename from proto/cosmwasm/tokenfactory/v1beta1/params.proto rename to proto/osmosis/tokenfactory/v1beta1/params.proto index 2871b8b..1eef2b7 100644 --- a/proto/cosmwasm/tokenfactory/v1beta1/params.proto +++ b/proto/osmosis/tokenfactory/v1beta1/params.proto @@ -2,11 +2,11 @@ syntax = "proto3"; package osmosis.tokenfactory.v1beta1; import "gogoproto/gogo.proto"; -import "cosmwasm/tokenfactory/v1beta1/authority_metadata.proto"; +import "osmosis/tokenfactory/v1beta1/authorityMetadata.proto"; import "cosmos_proto/cosmos.proto"; import "cosmos/base/v1beta1/coin.proto"; -option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; +option go_package = "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types"; // Params defines the parameters for the tokenfactory module. message Params { @@ -15,4 +15,12 @@ message Params { (gogoproto.moretags) = "yaml:\"denom_creation_fee\"", (gogoproto.nullable) = false ]; + + // if denom_creation_fee is an empty array, then this field is used to add more gas consumption + // to the base cost. + // https://github.com/CosmWasm/token-factory/issues/11 + uint64 denom_creation_gas_consume = 2 [ + (gogoproto.moretags) = "yaml:\"denom_creation_gas_consume\"", + (gogoproto.nullable) = true + ]; } \ No newline at end of file diff --git a/proto/cosmwasm/tokenfactory/v1beta1/query.proto b/proto/osmosis/tokenfactory/v1beta1/query.proto similarity index 92% rename from proto/cosmwasm/tokenfactory/v1beta1/query.proto rename to proto/osmosis/tokenfactory/v1beta1/query.proto index d7e4c42..d4e93bf 100644 --- a/proto/cosmwasm/tokenfactory/v1beta1/query.proto +++ b/proto/osmosis/tokenfactory/v1beta1/query.proto @@ -4,10 +4,10 @@ package osmosis.tokenfactory.v1beta1; import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; import "cosmos/base/query/v1beta1/pagination.proto"; -import "cosmwasm/tokenfactory/v1beta1/authority_metadata.proto"; -import "cosmwasm/tokenfactory/v1beta1/params.proto"; +import "osmosis/tokenfactory/v1beta1/authorityMetadata.proto"; +import "osmosis/tokenfactory/v1beta1/params.proto"; -option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; +option go_package = "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types"; // Query defines the gRPC querier service. service Query { @@ -68,4 +68,4 @@ message QueryDenomsFromCreatorRequest { // DenomsFromCreator gRPC query. message QueryDenomsFromCreatorResponse { repeated string denoms = 1 [ (gogoproto.moretags) = "yaml:\"denoms\"" ]; -} \ No newline at end of file +} diff --git a/proto/cosmwasm/tokenfactory/v1beta1/tx.proto b/proto/osmosis/tokenfactory/v1beta1/tx.proto similarity index 62% rename from proto/cosmwasm/tokenfactory/v1beta1/tx.proto rename to proto/osmosis/tokenfactory/v1beta1/tx.proto index 365bf5f..7f40114 100644 --- a/proto/cosmwasm/tokenfactory/v1beta1/tx.proto +++ b/proto/osmosis/tokenfactory/v1beta1/tx.proto @@ -4,31 +4,27 @@ package osmosis.tokenfactory.v1beta1; import "gogoproto/gogo.proto"; import "cosmos/base/v1beta1/coin.proto"; import "cosmos/bank/v1beta1/bank.proto"; +import "osmosis/tokenfactory/v1beta1/params.proto"; +import "cosmos/msg/v1/msg.proto"; +import "cosmos_proto/cosmos.proto"; -option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; +option go_package = "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types"; // Msg defines the tokefactory module's gRPC message service. service Msg { - // CreateDenom Creates a denom of factory/{creator address}/{subdenom} given - // the denom creator address and the subdenom. Subdenoms can contain - // [a-zA-Z0-9./]. rpc CreateDenom(MsgCreateDenom) returns (MsgCreateDenomResponse); - // Mint is message type that represents a request to mint a new denom. rpc Mint(MsgMint) returns (MsgMintResponse); - // Burn message type that represents a request to burn (i.e., destroy) a - // denom. rpc Burn(MsgBurn) returns (MsgBurnResponse); - // A message type that represents a request to change the administrator of the - // denom. rpc ChangeAdmin(MsgChangeAdmin) returns (MsgChangeAdminResponse); - // A message type that represents a request to set metadata for a - // denomination. rpc SetDenomMetadata(MsgSetDenomMetadata) returns (MsgSetDenomMetadataResponse); + rpc ForceTransfer(MsgForceTransfer) returns (MsgForceTransferResponse); - // ForceTransfer is deactivated for now because we need to think through edge - // cases rpc ForceTransfer(MsgForceTransfer) returns - // (MsgForceTransferResponse); + // UpdateParams defines a governance operation for updating the x/mint module + // parameters. The authority is hard-coded to the x/gov module account. + // + // Since: cosmos-sdk 0.47 + rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); } // MsgCreateDenom defines the message structure for the CreateDenom gRPC service @@ -47,7 +43,7 @@ message MsgCreateDenom { } // MsgCreateDenomResponse is the return value of MsgCreateDenom -// It returns the full string of the newly created denom. +// It returns the full string of the newly created denom message MsgCreateDenomResponse { string new_token_denom = 1 [ (gogoproto.moretags) = "yaml:\"new_token_denom\"" ]; @@ -61,9 +57,10 @@ message MsgMint { (gogoproto.moretags) = "yaml:\"amount\"", (gogoproto.nullable) = false ]; + string mintToAddress = 3 + [ (gogoproto.moretags) = "yaml:\"mint_to_address\"" ]; } -// MsgMintResponse defines the response structure for an executed -// MsgMint message. + message MsgMintResponse {} // MsgBurn is the sdk.Msg type for allowing an admin account to burn @@ -74,9 +71,10 @@ message MsgBurn { (gogoproto.moretags) = "yaml:\"amount\"", (gogoproto.nullable) = false ]; + string burnFromAddress = 3 + [ (gogoproto.moretags) = "yaml:\"burn_from_address\"" ]; } -// MsgBurnResponse defines the response structure for an executed -// MsgBurn message. + message MsgBurnResponse {} // MsgChangeAdmin is the sdk.Msg type for allowing an admin account to reassign @@ -91,22 +89,8 @@ message MsgChangeAdmin { // MsgChangeAdmin message. message MsgChangeAdminResponse {} -// message MsgForceTransfer { -// string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; -// cosmos.base.v1beta1.Coin amount = 2 [ -// (gogoproto.moretags) = "yaml:\"amount\"", -// (gogoproto.nullable) = false -// ]; -// string transferFromAddress = 3 -// [ (gogoproto.moretags) = "yaml:\"transfer_from_address\"" ]; -// string transferToAddress = 4 -// [ (gogoproto.moretags) = "yaml:\"transfer_to_address\"" ]; -// } - -// message MsgForceTransferResponse {} - // MsgSetDenomMetadata is the sdk.Msg type for allowing an admin account to set -// the denom's bank metadata. +// the denom's bank metadata message MsgSetDenomMetadata { string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; cosmos.bank.v1beta1.Metadata metadata = 2 [ @@ -117,4 +101,39 @@ message MsgSetDenomMetadata { // MsgSetDenomMetadataResponse defines the response structure for an executed // MsgSetDenomMetadata message. -message MsgSetDenomMetadataResponse {} \ No newline at end of file +message MsgSetDenomMetadataResponse {} + +message MsgForceTransfer { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + cosmos.base.v1beta1.Coin amount = 2 [ + (gogoproto.moretags) = "yaml:\"amount\"", + (gogoproto.nullable) = false + ]; + string transferFromAddress = 3 + [ (gogoproto.moretags) = "yaml:\"transfer_from_address\"" ]; + string transferToAddress = 4 + [ (gogoproto.moretags) = "yaml:\"transfer_to_address\"" ]; +} + +message MsgForceTransferResponse {} + +// MsgUpdateParams is the Msg/UpdateParams request type. +// +// Since: cosmos-sdk 0.47 +message MsgUpdateParams { + option (cosmos.msg.v1.signer) = "authority"; + + // authority is the address of the governance account. + string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // params defines the x/mint parameters to update. + // + // NOTE: All parameters must be supplied. + Params params = 2 [(gogoproto.nullable) = false]; +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +// +// Since: cosmos-sdk 0.47 +message MsgUpdateParamsResponse {} diff --git a/proto/terp/feeshare/v1/feeshare.proto b/proto/terp/feeshare/v1/feeshare.proto new file mode 100644 index 0000000..1d7f9a8 --- /dev/null +++ b/proto/terp/feeshare/v1/feeshare.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; +package terp.feeshare.v1; + +option go_package = "github.com/terpnetwork/terp-core/v2/x/feeshare/types"; + +// FeeShare defines an instance that organizes fee distribution conditions for +// the owner of a given smart contract +message FeeShare { + // contract_address is the bech32 address of a registered contract in string + // form + string contract_address = 1; + // deployer_address is the bech32 address of message sender. It must be the + // same as the contracts admin address. + string deployer_address = 2; + // withdrawer_address is the bech32 address of account receiving the + // transaction fees. + string withdrawer_address = 3; +} diff --git a/proto/terp/feeshare/v1/genesis.proto b/proto/terp/feeshare/v1/genesis.proto new file mode 100644 index 0000000..da635c4 --- /dev/null +++ b/proto/terp/feeshare/v1/genesis.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; +package terp.feeshare.v1; + +import "terp/feeshare/v1/feeshare.proto"; +import "gogoproto/gogo.proto"; +option go_package = "github.com/terpnetwork/terp-core/v2/x/feeshare/types"; + +// GenesisState defines the module's genesis state. +message GenesisState { + // params are the feeshare module parameters + Params params = 1 [ (gogoproto.nullable) = false ]; + // FeeShare is a slice of active registered contracts for fee distribution + repeated FeeShare fee_share = 2 [ (gogoproto.nullable) = false ]; +} + +// Params defines the feeshare module params +message Params { + // enable_feeshare defines a parameter to enable the feeshare module + bool enable_fee_share = 1; + // developer_shares defines the proportion of the transaction fees to be + // distributed to the registered contract owner + string developer_shares = 2 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + // allowed_denoms defines the list of denoms that are allowed to be paid to + // the contract withdraw addresses. If said denom is not in the list, the fees + // will ONLY be sent to the community pool. + // If this list is empty, all denoms are allowed. + repeated string allowed_denoms = 3; +} diff --git a/proto/terp/feeshare/v1/query.proto b/proto/terp/feeshare/v1/query.proto new file mode 100644 index 0000000..7200378 --- /dev/null +++ b/proto/terp/feeshare/v1/query.proto @@ -0,0 +1,119 @@ +syntax = "proto3"; +package terp.feeshare.v1; + +import "cosmos/base/query/v1beta1/pagination.proto"; +import "terp/feeshare/v1/genesis.proto"; +import "terp/feeshare/v1/feeshare.proto"; +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; + +option go_package = "github.com/terpnetwork/terp-core/v2/x/feeshare/types"; + +// Query defines the gRPC querier service. +service Query { + // FeeShares retrieves all registered FeeShares + rpc FeeShares(QueryFeeSharesRequest) returns (QueryFeeSharesResponse) { + option (google.api.http).get = "/terp/feeshare/v1/fee_shares"; + } + + // FeeShare retrieves a registered FeeShare for a given contract address + rpc FeeShare(QueryFeeShareRequest) returns (QueryFeeShareResponse) { + option (google.api.http).get = + "/terp/feeshare/v1/fee_shares/{contract_address}"; + } + + // Params retrieves the FeeShare module params + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/terp/feeshare/v1/params"; + } + + // DeployerFeeShares retrieves all FeeShares that a given deployer has + // registered + rpc DeployerFeeShares(QueryDeployerFeeSharesRequest) + returns (QueryDeployerFeeSharesResponse) { + option (google.api.http).get = + "/terp/feeshare/v1/fee_shares/{deployer_address}"; + } + + // WithdrawerFeeShares retrieves all FeeShares with a given withdrawer + // address + rpc WithdrawerFeeShares(QueryWithdrawerFeeSharesRequest) + returns (QueryWithdrawerFeeSharesResponse) { + option (google.api.http).get = + "/terp/feeshare/v1/fee_shares/{withdrawer_address}"; + } +} + +// QueryFeeSharesRequest is the request type for the Query/FeeShares RPC method. +message QueryFeeSharesRequest { + // pagination defines an optional pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 1; +} + +// QueryFeeSharesResponse is the response type for the Query/FeeShares RPC +// method. +message QueryFeeSharesResponse { + // FeeShare is a slice of all stored Reveneue + repeated FeeShare feeshare = 1 [ (gogoproto.nullable) = false ]; + // pagination defines the pagination in the response. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + +// QueryFeeShareRequest is the request type for the Query/FeeShare RPC method. +message QueryFeeShareRequest { + // contract_address of a registered contract in bech32 format + string contract_address = 1; +} + +// QueryFeeShareResponse is the response type for the Query/FeeShare RPC method. +message QueryFeeShareResponse { + // FeeShare is a stored Reveneue for the queried contract + FeeShare feeshare = 1 [ (gogoproto.nullable) = false ]; +} + +// QueryParamsRequest is the request type for the Query/Params RPC method. +message QueryParamsRequest {} + +// QueryParamsResponse is the response type for the Query/Params RPC method. +message QueryParamsResponse { + // params is the returned FeeShare parameter + Params params = 1 [ (gogoproto.nullable) = false ]; +} + +// QueryDeployerFeeSharesRequest is the request type for the +// Query/DeployerFeeShares RPC method. +message QueryDeployerFeeSharesRequest { + // deployer_address in bech32 format + string deployer_address = 1; + // pagination defines an optional pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 2; +} + +// QueryDeployerFeeSharesResponse is the response type for the +// Query/DeployerFeeShares RPC method. +message QueryDeployerFeeSharesResponse { + // contract_addresses is the slice of registered contract addresses for a + // deployer + repeated string contract_addresses = 1; + // pagination defines the pagination in the response. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} + +// QueryWithdrawerFeeSharesRequest is the request type for the +// Query/WithdrawerFeeShares RPC method. +message QueryWithdrawerFeeSharesRequest { + // withdrawer_address in bech32 format + string withdrawer_address = 1; + // pagination defines an optional pagination for the request. + cosmos.base.query.v1beta1.PageRequest pagination = 2; +} + +// QueryWithdrawerFeeSharesResponse is the response type for the +// Query/WithdrawerFeeShares RPC method. +message QueryWithdrawerFeeSharesResponse { + // contract_addresses is the slice of registered contract addresses for a + // withdrawer + repeated string contract_addresses = 1; + // pagination defines the pagination in the response. + cosmos.base.query.v1beta1.PageResponse pagination = 2; +} diff --git a/proto/terp/feeshare/v1/tx.proto b/proto/terp/feeshare/v1/tx.proto new file mode 100644 index 0000000..af279bb --- /dev/null +++ b/proto/terp/feeshare/v1/tx.proto @@ -0,0 +1,97 @@ +syntax = "proto3"; +package terp.feeshare.v1; + +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "cosmos/msg/v1/msg.proto"; +import "cosmos_proto/cosmos.proto"; +import "terp/feeshare/v1/genesis.proto"; + +option go_package = "github.com/terpnetwork/terp-core/v2/x/feeshare/types"; + +// Msg defines the fees Msg service. +service Msg { + // RegisterFeeShare registers a new contract for receiving transaction fees + rpc RegisterFeeShare(MsgRegisterFeeShare) + returns (MsgRegisterFeeShareResponse) { + option (google.api.http).post = "/terp/feeshare/v1/tx/register_FeeShare"; + }; + // UpdateFeeShare updates the withdrawer address of a FeeShare + rpc UpdateFeeShare(MsgUpdateFeeShare) returns (MsgUpdateFeeShareResponse) { + option (google.api.http).post = "/terp/feeshare/v1/tx/update_FeeShare"; + }; + // CancelFeeShare cancels a contract's fee registration and further receival + // of transaction fees + rpc CancelFeeShare(MsgCancelFeeShare) returns (MsgCancelFeeShareResponse) { + option (google.api.http).post = "/terp/feeshare/v1/tx/cancel_FeeShare"; + }; + // Update the params of the module through gov v1 type. + rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse); +} + +// MsgRegisterFeeShare defines a message that registers a FeeShare +message MsgRegisterFeeShare { + option (gogoproto.equal) = false; + // contract_address in bech32 format + string contract_address = 1; + // deployer_address is the bech32 address of message sender. It must be the + // same the contract's admin address + string deployer_address = 2; + // withdrawer_address is the bech32 address of account receiving the + // transaction fees + string withdrawer_address = 3; +} + +// MsgRegisterFeeShareResponse defines the MsgRegisterFeeShare response type +message MsgRegisterFeeShareResponse {} + +// MsgUpdateFeeShare defines a message that updates the withdrawer address for a +// registered FeeShare +message MsgUpdateFeeShare { + option (gogoproto.equal) = false; + // contract_address in bech32 format + string contract_address = 1; + // deployer_address is the bech32 address of message sender. It must be the + // same the contract's admin address + string deployer_address = 2; + // withdrawer_address is the bech32 address of account receiving the + // transaction fees + string withdrawer_address = 3; +} + +// MsgUpdateFeeShareResponse defines the MsgUpdateFeeShare response type +message MsgUpdateFeeShareResponse {} + +// MsgCancelFeeShare defines a message that cancels a registered FeeShare +message MsgCancelFeeShare { + option (gogoproto.equal) = false; + // contract_address in bech32 format + string contract_address = 1; + // deployer_address is the bech32 address of message sender. It must be the + // same the contract's admin address + string deployer_address = 2; +} + +// MsgCancelFeeShareResponse defines the MsgCancelFeeShare response type +message MsgCancelFeeShareResponse {} + +// MsgUpdateParams is the Msg/UpdateParams request type. +// +// Since: cosmos-sdk 0.47 +message MsgUpdateParams { + option (cosmos.msg.v1.signer) = "authority"; + + // authority is the address that controls the module (defaults to x/gov unless overwritten). + string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + + // params defines the x/feeshare parameters to update. + // + // NOTE: All parameters must be supplied. + Params params = 2 [(gogoproto.nullable) = false]; +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +// +// Since: cosmos-sdk 0.47 +message MsgUpdateParamsResponse {} \ No newline at end of file diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100644 index 0000000..6582a24 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +set -e + +GIT_TAG=$(git describe --tags) + +echo "> Building $GIT_TAG..." + +docker build . -t terpnetwork/terp-core:$GIT_TAG \ No newline at end of file diff --git a/scripts/build_and_run.sh b/scripts/build_and_run.sh new file mode 100644 index 0000000..7705232 --- /dev/null +++ b/scripts/build_and_run.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +set -e + +./scripts/build.sh +./scripts/run.sh \ No newline at end of file diff --git a/scripts/build_and_run_blocking.sh b/scripts/build_and_run_blocking.sh new file mode 100644 index 0000000..b10a142 --- /dev/null +++ b/scripts/build_and_run_blocking.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +set -e + +./scripts/build.sh +./scripts/run_blocking.sh \ No newline at end of file diff --git a/scripts/git/linter.sh b/scripts/git/linter.sh new file mode 100644 index 0000000..635e5b7 --- /dev/null +++ b/scripts/git/linter.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +if ! command -v golangci-lint &> /dev/null ; then + echo "golangci-lint not installed or available in the PATH" >&2 + echo "please check https://github.com/golangci/golangci-lint" >&2 + exit 1 +fi + +res="$(golangci-lint run ./... --allow-parallel-runners --concurrency 1 --fix)" +word_count=`echo $res | wc -w` + +if [ $word_count -gt 1 ]; then + echo "golangci-lint failed" + echo -e "$res" + + exit 2 +fi \ No newline at end of file diff --git a/scripts/git/markdown_lint.sh b/scripts/git/markdown_lint.sh new file mode 100644 index 0000000..c3b939e --- /dev/null +++ b/scripts/git/markdown_lint.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +if ! command -v markdownlint &> /dev/null ; then + echo "markdownlint not installed" >&2 + echo "please check https://www.npmjs.com/package/markdownlint" >&2 + exit 1 +fi + +res="$(markdownlint . --disable MD013 MD010 2>&1 echo)" +word_count=`echo $res | wc -w` + +if [ $word_count -gt 0 ]; then + echo "markdownlint failed" + echo -e "$res" + exit 2 +fi \ No newline at end of file diff --git a/scripts/git/tidy.sh b/scripts/git/tidy.sh new file mode 100644 index 0000000..6b71935 --- /dev/null +++ b/scripts/git/tidy.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +function runTidy() { + go mod tidy -v + if [ $? -ne 0 ]; then + echo "go mod tidy failed" + exit 2 + fi + + git diff --exit-code go.* &> /dev/null + if [ $? -ne 0 ]; then + echo "root go.mod or go.sum differs, please re-add it to your commit" + exit 3 + fi +} + +runTidy + +cd interchaintest/ +runTidy diff --git a/scripts/merge_protoc.py b/scripts/merge_protoc.py new file mode 100644 index 0000000..a908fc6 --- /dev/null +++ b/scripts/merge_protoc.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 + +# Call this from the ./scripts/protoc_swagger_openapi_gen.sh script + +# merged protoc definitions together into 1 JSON file without duplicate keys +# this is done AFTER swagger-merger has been run, merging the multiple name-#.json files into 1. + +import json +import os +import random +import string + +current_dir = os.path.dirname(os.path.realpath(__file__)) +project_root = os.path.dirname(current_dir) + +all_dir = os.path.join(project_root, "tmp-swagger-gen", "_all") + +# get the go.mod file Version +version = "" +with open(os.path.join(project_root, "go.mod"), "r") as f: + for line in f.readlines(): + if line.startswith("module"): + version = line.split("/")[-1].strip() + break + +if not version: + print("Could not find version in go.mod") + exit(1) + +# What we will save when all combined +output: dict +output = { + "swagger": "2.0", + "info": {"title": "Terp network", "version": version}, + "consumes": ["application/json"], + "produces": ["application/json"], + "paths": {}, + "definitions": {}, +} + +# Combine all individual files calls into 1 massive file. +for file in os.listdir(all_dir): + if not file.endswith(".json"): + continue + + # read file all_dir / file + with open(os.path.join(all_dir, file), "r") as f: + data = json.load(f) + + for key in data["paths"]: + output["paths"][key] = data["paths"][key] + + for key in data["definitions"]: + output["definitions"][key] = data["definitions"][key] + + +# loop through all paths, then alter any keys which are "operationId" to be a random string of 20 characters +# this is done to avoid duplicate keys in the final output (which opens 2 tabs in swagger-ui) +# current-random +for path in output["paths"]: + for method in output["paths"][path]: + if "operationId" in output["paths"][path][method]: + output["paths"][path][method][ + "operationId" + ] = f'{output["paths"][path][method]["operationId"]}_' + "".join( + random.choices(string.ascii_uppercase + string.digits, k=5) + ) + + +# save output into 1 big json file +with open( + os.path.join(project_root, "tmp-swagger-gen", "_all", "FINAL.json"), "w" +) as f: + json.dump(output, f, indent=2) diff --git a/scripts/protoc-swagger-gen.sh b/scripts/protoc-swagger-gen.sh deleted file mode 100755 index f0a6bc8..0000000 --- a/scripts/protoc-swagger-gen.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env bash - -set -eo pipefail - -mkdir -p ./docs/client -proto_dirs=$(find ./proto -path -prune -o -name '*.proto' -print0 | xargs -0 -n1 dirname | sort | uniq) -for dir in $proto_dirs; do - - # generate swagger files (filter query files) - query_file=$(find "${dir}" -maxdepth 1 \( -name 'query.proto' -o -name 'service.proto' \)) - if [[ ! -z "$query_file" ]]; then - buf protoc \ - -I "proto" \ - -I "third_party/proto" \ - "$query_file" \ - --swagger_out=./docs/client \ - --swagger_opt=logtostderr=true --swagger_opt=fqn_for_swagger_name=true --swagger_opt=simple_operation_ids=true - fi -done diff --git a/scripts/protoc_swagger_openapi_gen.sh b/scripts/protoc_swagger_openapi_gen.sh new file mode 100644 index 0000000..613ad7c --- /dev/null +++ b/scripts/protoc_swagger_openapi_gen.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash + +# Run from the project root directory +# This script generates the swagger & openapi.yaml documentation for the rest API on port 1317 +# +# Install the following:: +# sudo npm install -g swagger2openapi swagger-merger swagger-combine +# go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger@v1.16.0 + +# change to the scripts folder +cd "$(dirname `realpath "$0"`)" +# change to the root folder +cd ../ + +mkdir -p ./tmp-swagger-gen + +# Get the paths used repos from go/pkg/mod +cosmos_sdk_dir=$(go list -f '{{ .Dir }}' -m github.com/cosmos/cosmos-sdk) +wasmd=$(go list -f '{{ .Dir }}' -m github.com/CosmWasm/wasmd) +gaia=$(go list -f '{{ .Dir }}' -m github.com/cosmos/gaia/v9) +ica=$(go list -f '{{ .Dir }}' -m github.com/cosmos/interchain-accounts) +pfm=$(go list -fprot '{{ .Dir }}' -m github.com/strangelove-ventures/packet-forward-middleware/v4) + +proto_dirs=$(find ./proto "$cosmos_sdk_dir"/proto "$wasmd"/proto "$gaia"/proto "$ica"/proto "$pfm"/proto -path -prune -o -name '*.proto' -print0 | xargs -0 -n1 dirname | sort | uniq) +for dir in $proto_dirs; do + + # generate swagger files (filter query files) + query_file=$(find "${dir}" -maxdepth 1 \( -name 'query.proto' -o -name 'service.proto' \)) + if [[ ! -z "$query_file" ]]; then + protoc \ + -I "proto" \ + -I "$cosmos_sdk_dir/third_party/proto" \ + -I "$cosmos_sdk_dir/proto" \ + -I "$wasmd/proto" \ + -I "$gaia/proto" \ + -I "$ica/proto" \ + -I "$pfm/proto" \ + "$query_file" \ + --swagger_out ./tmp-swagger-gen \ + --swagger_opt logtostderr=true \ + --swagger_opt fqn_for_swagger_name=true \ + --swagger_opt simple_operation_ids=true + fi +done + +# delete cosmos/mint path since terp uses its own module +rm -rf ./tmp-swagger-gen/cosmos/mint + +# Fix circular definition in cosmos/tx/v1beta1/service.swagger.json +jq 'del(.definitions["cosmos.tx.v1beta1.ModeInfo.Multi"].properties.mode_infos.items["$ref"])' ./tmp-swagger-gen/cosmos/tx/v1beta1/service.swagger.json > ./tmp-swagger-gen/cosmos/tx/v1beta1/fixed-service.swagger.json + +# Tag everything as "gRPC Gateway API" +perl -i -pe 's/"(Query|Service)"/"gRPC Gateway API"/' $(find ./tmp-swagger-gen -name '*.swagger.json' -print0 | xargs -0) + +# Convert all *.swagger.json files into a single folder _all +files=$(find ./tmp-swagger-gen -name '*.swagger.json' -print0 | xargs -0) +mkdir -p ./tmp-swagger-gen/_all +counter=0 +for f in $files; do + echo "[+] $f" + + # check gaia first before cosmos + if [[ "$f" =~ "gaia" ]]; then + cp $f ./tmp-swagger-gen/_all/gaia-$counter.json + elif [[ "$f" =~ "router" ]]; then + cp $f ./tmp-swagger-gen/_all/pfm-$counter.json + elif [[ "$f" =~ "cosmwasm" ]]; then + cp $f ./tmp-swagger-gen/_all/cosmwasm-$counter.json + elif [[ "$f" =~ "osmosis" ]]; then + cp $f ./tmp-swagger-gen/_all/osmosis-$counter.json + elif [[ "$f" =~ "terp" ]]; then + cp $f ./tmp-swagger-gen/_all/terp-$counter.json + elif [[ "$f" =~ "cosmos" ]]; then + cp $f ./tmp-swagger-gen/_all/cosmos-$counter.json + # elif [[ "$f" =~ "intertx" ]]; then + # cp $f ./tmp-swagger-gen/_all/intertx-$counter.json + else + cp $f ./tmp-swagger-gen/_all/other-$counter.json + fi + ((counter++)) +done + +# merges all the above into FINAL.json +python3 ./scripts/merge_protoc.py + +# Makes a swagger temp file with reference pointers +swagger-combine ./tmp-swagger-gen/_all/FINAL.json -o ./docs/_tmp_swagger.yaml -f yaml --continueOnConflictingPaths --includeDefinitions + +# extends out the *ref instances to their full value +swagger-merger --input ./docs/_tmp_swagger.yaml -o ./docs/swagger.yaml + +# Derive openapi from swagger docs +swagger2openapi --patch ./docs/swagger.yaml --outfile ./docs/static/openapi.yml --yaml + +# clean swagger tmp files +rm ./docs/_tmp_swagger.yaml +rm -rf ./tmp-swagger-gen \ No newline at end of file diff --git a/scripts/protocgen.sh b/scripts/protocgen.sh index b3c03de..ff826ba 100755 --- a/scripts/protocgen.sh +++ b/scripts/protocgen.sh @@ -1,30 +1,37 @@ #!/usr/bin/env bash -set -eo pipefail +#== Legacy Requirements (<= SDK v45) == +# +## make sure your `go env GOPATH` is in the `$PATH` +## Install: +## + latest buf (v1.0.0-rc11 or later) +## + protobuf v3 +# +## All protoc dependencies must be installed not in the module scope +## currently we must use grpc-gateway v1 +# cd ~ +# go install google.golang.org/protobuf/cmd/protoc-gen-go@latest +# go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest +# go install github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway@v1.16.0 +# go install github.com/cosmos/cosmos-proto/cmd/protoc-gen-go-pulsar@latest +# go get github.com/regen-network/cosmos-proto@latest # doesn't work in install mode +# go get github.com/regen-network/cosmos-proto/protoc-gen-gocosmos@v0.3.1 + +# Updated - How to run manually: +# docker build --pull --rm -f "contrib/devtools/Dockerfile" -t cosmossdk-proto:latest "contrib/devtools" +# docker run --rm -v $(pwd):/workspace --workdir /workspace cosmossdk-proto sh ./scripts/protocgen.sh -protoc_install_proto_gen_doc() { - echo "Installing protobuf protoc-gen-doc plugin" - (go install github.com/pseudomuto/protoc-gen-doc/cmd/protoc-gen-doc@latest 2> /dev/null) -} +set -eo pipefail echo "Generating gogo proto code" cd proto -proto_dirs=$(find ./cosmwasm -path -prune -o -name '*.proto' -print0 | xargs -0 -n1 dirname | sort | uniq) -for dir in $proto_dirs; do - for file in $(find "${dir}" -maxdepth 1 -name '*.proto'); do - if grep "option go_package" $file &> /dev/null ; then - buf generate --template buf.gen.gogo.yml $file - fi - done -done - -protoc_install_proto_gen_doc - -echo "Generating proto docs" -buf generate --template buf.gen.doc.yml - +buf mod update cd .. +buf generate # move proto files to the right places -cp -r github.com/terpnetwork/terp-core/* ./ -rm -rf github.com \ No newline at end of file +cp -r ./github.com/terpnetwork/terp-core/x/* x/ +cp -r ./github.com/cosmos/gaia/x/* x/ + + +rm -rf ./github.com \ No newline at end of file diff --git a/scripts/protocgen2.sh b/scripts/protocgen2.sh new file mode 100644 index 0000000..77ad9c7 --- /dev/null +++ b/scripts/protocgen2.sh @@ -0,0 +1,19 @@ +# this script is for generating protobuf files for the new google.golang.org/protobuf API + +set -eo pipefail + +protoc_install_gopulsar() { + go install github.com/cosmos/cosmos-proto/cmd/protoc-gen-go-pulsar@latest + go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest +} + +protoc_install_gopulsar + +echo "Cleaning API directory" +(cd api; find ./ -type f \( -iname \*.pulsar.go -o -iname \*.pb.go -o -iname \*.cosmos_orm.go -o -iname \*.pb.gw.go \) -delete; find . -empty -type d -delete; cd ..) + +echo "Generating API module" +(cd proto; buf generate --template buf.gen.pulsar.yaml) + +echo "Generate Pulsar Test Data" +(cd testutil/testdata; buf generate --template buf.gen.pulsar.yaml) \ No newline at end of file diff --git a/scripts/run.sh b/scripts/run.sh new file mode 100644 index 0000000..97a2d31 --- /dev/null +++ b/scripts/run.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +set -e + +GIT_TAG=$(git describe --tags) + +echo "> Running $GIT_TAG..." + +docker run --rm -it -p 26657:26657 --name terp-local terpnetwork/terp-core:$GIT_TAG /bin/sh \ No newline at end of file diff --git a/scripts/run_blocking.sh b/scripts/run_blocking.sh new file mode 100644 index 0000000..2d22122 --- /dev/null +++ b/scripts/run_blocking.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +set -e + +GIT_TAG=$(git describe --tags) + +echo "> Running $GIT_TAG..." + +docker run --rm -it -p 26657:26657 --name terp-local terpnetwork/terp-core:$GIT_TAG /bin/sh -c "./setup_and_run.sh" \ No newline at end of file diff --git a/scripts/test_node.sh b/scripts/test_node.sh new file mode 100644 index 0000000..cf2fb0c --- /dev/null +++ b/scripts/test_node.sh @@ -0,0 +1,118 @@ +#!/bin/bash +# Run this script to quickly install, setup, and run the current version of terp without docker. +# +# Example: +# CHAIN_ID="local-1" HOME_DIR="~/.terp1" TIMEOUT_COMMIT="500ms" CLEAN=true sh scripts/test_node.sh +# CHAIN_ID="local-2" HOME_DIR="~/.terp2" CLEAN=true RPC=36657 REST=2317 PROFF=6061 P2P=36656 GRPC=8090 GRPC_WEB=8091 ROSETTA=8081 TIMEOUT_COMMIT="500ms" sh scripts/test_node.sh +# +# To use unoptomized wasm files up to ~5mb, add: MAX_WASM_SIZE=5000000 + +export KEY="terp1" +export KEY2="terp2" + +export CHAIN_ID=${CHAIN_ID:-"local-1"} +export MONIKER="localterp" +export KEYALGO="secp256k1" +export KEYRING=${KEYRING:-"test"} +export HOME_DIR=$(eval echo "${HOME_DIR:-"~/.terp"}") +export BINARY=${BINARY:-terpd} + +export CLEAN=${CLEAN:-"false"} +export RPC=${RPC:-"26657"} +export REST=${REST:-"1317"} +export PROFF=${PROFF:-"6060"} +export P2P=${P2P:-"26656"} +export GRPC=${GRPC:-"9090"} +export GRPC_WEB=${GRPC_WEB:-"9091"} +export ROSETTA=${ROSETTA:-"8080"} +export TIMEOUT_COMMIT=${TIMEOUT_COMMIT:-"5s"} + +alias BINARY="$BINARY --home=$HOME_DIR" + +command -v $BINARY > /dev/null 2>&1 || { echo >&2 "$BINARY command not found. Ensure this is setup / properly installed in your GOPATH (make install)."; exit 1; } +command -v jq > /dev/null 2>&1 || { echo >&2 "jq not installed. More info: https://stedolan.github.io/jq/download/"; exit 1; } + +$BINARY config keyring-backend $KEYRING +$BINARY config chain-id $CHAIN_ID + +from_scratch () { + # Fresh install on current branch + make install + + # remove existing daemon. + rm -rf $HOME_DIR && echo "Removed $HOME_DIR" + + # terp1efd63aw40lxf3n4mhf7dzhjkr453axurajg60e + echo "decorate bright ozone fork gallery riot bus exhaust worth way bone indoor calm squirrel merry zero scheme cotton until shop any excess stage laundry" | BINARY keys add $KEY --keyring-backend $KEYRING --algo $KEYALGO --recover + # terp1hj5fveer5cjtn4wd6wstzugjfdxzl0xppxm7xs + echo "wealth flavor believe regret funny network recall kiss grape useless pepper cram hint member few certain unveil rather brick bargain curious require crowd raise" | BINARY keys add $KEY2 --keyring-backend $KEYRING --algo $KEYALGO --recover + + BINARY init $MONIKER --chain-id $CHAIN_ID --default-denom uterpx + + # Function updates the config based on a jq argument as a string + update_test_genesis () { + cat $HOME_DIR/config/genesis.json | jq "$1" > $HOME_DIR/config/tmp_genesis.json && mv $HOME_DIR/config/tmp_genesis.json $HOME_DIR/config/genesis.json + } + + # Block + update_test_genesis '.consensus_params["block"]["max_gas"]="100000000"' + # Gov + update_test_genesis '.app_state["gov"]["params"]["min_deposit"]=[{"denom": "uterpx","amount": "1000000"}]' + update_test_genesis '.app_state["gov"]["voting_params"]["voting_period"]="15s"' + # staking + update_test_genesis '.app_state["staking"]["params"]["bond_denom"]="uterpx"' + update_test_genesis '.app_state["staking"]["params"]["min_commission_rate"]="0.050000000000000000"' + # mint + update_test_genesis '.app_state["mint"]["params"]["mint_denom"]="uterpx"' + # crisis + update_test_genesis '.app_state["crisis"]["constant_fee"]={"denom": "uterpx","amount": "1000"}' + + # Custom Modules + + # Allocate genesis accounts + BINARY genesis add-genesis-account $KEY 10000000uterpx,1000utest --keyring-backend $KEYRING + BINARY genesis add-genesis-account $KEY2 1000000uterpx,1000utest --keyring-backend $KEYRING + + BINARY genesis gentx $KEY 1000000uterpx --keyring-backend $KEYRING --chain-id $CHAIN_ID + + # Collect genesis tx + BINARY genesis collect-gentxs + + # Run this to ensure terprything worked and that the genesis file is setup correctly + BINARY genesis validate-genesis +} + +# check if CLEAN is not set to false +if [ "$CLEAN" != "false" ]; then + echo "Starting from a clean state" + from_scratch +fi + +echo "Starting node..." + +# Opens the RPC endpoint to outside connections +sed -i 's/laddr = "tcp:\/\/127.0.0.1:26657"/c\laddr = "tcp:\/\/0.0.0.0:'$RPC'"/g' $HOME_DIR/config/config.toml +sed -i 's/cors_allowed_origins = \[\]/cors_allowed_origins = \["\*"\]/g' $HOME_DIR/config/config.toml + +# REST endpoint +sed -i 's/address = "tcp:\/\/localhost:1317"/address = "tcp:\/\/0.0.0.0:'$REST'"/g' $HOME_DIR/config/app.toml +sed -i 's/enable = false/enable = true/g' $HOME_DIR/config/app.toml + +# replace pprof_laddr = "localhost:6060" binding +sed -i 's/pprof_laddr = "localhost:6060"/pprof_laddr = "localhost:'$PROFF_LADDER'"/g' $HOME_DIR/config/config.toml + +# change p2p addr laddr = "tcp://0.0.0.0:26656" +sed -i 's/laddr = "tcp:\/\/0.0.0.0:26656"/laddr = "tcp:\/\/0.0.0.0:'$P2P'"/g' $HOME_DIR/config/config.toml + +# GRPC +sed -i 's/address = "localhost:9090"/address = "0.0.0.0:'$GRPC'"/g' $HOME_DIR/config/app.toml +sed -i 's/address = "localhost:9091"/address = "0.0.0.0:'$GRPC_WEB'"/g' $HOME_DIR/config/app.toml + +# Rosetta Api +sed -i 's/address = ":8080"/address = "0.0.0.0:'$ROSETTA'"/g' $HOME_DIR/config/app.toml + +# faster blocks +sed -i 's/timeout_commit = "5s"/timeout_commit = "'$TIMEOUT_COMMIT'"/g' $HOME_DIR/config/config.toml + +# Start the node with 0 gas fees +BINARY start --pruning=nothing --minimum-gas-prices=0uterpx --rpc.laddr="tcp://0.0.0.0:$RPC" \ No newline at end of file diff --git a/tests/e2e/README.md b/tests/e2e/README.md deleted file mode 100644 index dae38fe..0000000 --- a/tests/e2e/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# End To End Testing - e2e - -Scenario tests that run against on or multiple chain instances. diff --git a/tests/e2e/gov_test.go b/tests/e2e/gov_test.go deleted file mode 100644 index 4054637..0000000 --- a/tests/e2e/gov_test.go +++ /dev/null @@ -1,135 +0,0 @@ -package e2e_test - -import ( - "testing" - "time" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - sdk "github.com/cosmos/cosmos-sdk/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/tests/e2e" - "github.com/terpnetwork/terp-core/x/wasm/ibctesting" -) - -func TestGovVoteByContract(t *testing.T) { - // Given a contract with delegation - // And a gov proposal - // When the contract sends a vote for the proposal - // Then the vote is taken into account - - coord := ibctesting.NewCoordinator(t, 1) - chain := coord.GetChain(ibctesting.GetChainID(1)) - contractAddr := e2e.InstantiateReflectContract(t, chain) - chain.Fund(contractAddr, sdk.NewIntFromUint64(1_000_000_000)) - // a contract with a high delegation amount - delegateMsg := wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Delegate: &wasmvmtypes.DelegateMsg{ - Validator: sdk.ValAddress(chain.Vals.Validators[0].Address).String(), - Amount: wasmvmtypes.Coin{ - Denom: sdk.DefaultBondDenom, - Amount: "1000000000", - }, - }, - }, - } - e2e.MustExecViaReflectContract(t, chain, contractAddr, delegateMsg) - - signer := chain.SenderAccount.GetAddress().String() - govKeeper, accountKeeper := chain.App.GovKeeper, chain.App.AccountKeeper - communityPoolBalance := chain.Balance(accountKeeper.GetModuleAccount(chain.GetContext(), distributiontypes.ModuleName).GetAddress(), sdk.DefaultBondDenom) - require.False(t, communityPoolBalance.IsZero()) - - initialDeposit := govKeeper.GetParams(chain.GetContext()).MinDeposit - govAcctAddr := govKeeper.GetGovernanceAccount(chain.GetContext()).GetAddress() - - specs := map[string]struct { - vote *wasmvmtypes.VoteMsg - expPass bool - }{ - "yes": { - vote: &wasmvmtypes.VoteMsg{ - Vote: wasmvmtypes.Yes, - }, - expPass: true, - }, - "no": { - vote: &wasmvmtypes.VoteMsg{ - Vote: wasmvmtypes.No, - }, - expPass: false, - }, - "abstain": { - vote: &wasmvmtypes.VoteMsg{ - Vote: wasmvmtypes.Abstain, - }, - expPass: true, - }, - "no with veto": { - vote: &wasmvmtypes.VoteMsg{ - Vote: wasmvmtypes.NoWithVeto, - }, - expPass: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // given a unique recipient - recipientAddr := sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address().Bytes()) - // and a new proposal - payloadMsg := &distributiontypes.MsgCommunityPoolSpend{ - Authority: govAcctAddr.String(), - Recipient: recipientAddr.String(), - Amount: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - } - msg, err := v1.NewMsgSubmitProposal( - []sdk.Msg{payloadMsg}, - initialDeposit, - signer, - "", - "my proposal", - "testing", - ) - require.NoError(t, err) - rsp, gotErr := chain.SendMsgs(msg) - require.NoError(t, gotErr) - require.Len(t, rsp.MsgResponses, 1) - got, ok := rsp.MsgResponses[0].GetCachedValue().(*v1.MsgSubmitProposalResponse) - require.True(t, ok) - propID := got.ProposalId - - // with other delegators voted yes - _, err = chain.SendMsgs(v1.NewMsgVote(chain.SenderAccount.GetAddress(), propID, v1.VoteOption_VOTE_OPTION_YES, "")) - require.NoError(t, err) - - // when contract votes - spec.vote.ProposalId = propID - voteMsg := wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: spec.vote, - }, - } - e2e.MustExecViaReflectContract(t, chain, contractAddr, voteMsg) - - // then proposal executed after voting period - proposal, ok := govKeeper.GetProposal(chain.GetContext(), propID) - require.True(t, ok) - coord.IncrementTimeBy(proposal.VotingEndTime.Sub(chain.GetContext().BlockTime()) + time.Minute) - coord.CommitBlock(chain) - - // and recipient balance updated - recipientBalance := chain.Balance(recipientAddr, sdk.DefaultBondDenom) - if !spec.expPass { - assert.True(t, recipientBalance.IsZero()) - return - } - expBalanceAmount := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) - assert.Equal(t, expBalanceAmount.String(), recipientBalance.String()) - }) - } -} diff --git a/tests/e2e/grants_test.go b/tests/e2e/grants_test.go deleted file mode 100644 index 0fb4882..0000000 --- a/tests/e2e/grants_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package e2e_test - -import ( - "fmt" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/authz" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/tests/e2e" - "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestGrants(t *testing.T) { - // Given a contract by address A - // And a grant for address B by A created - // When B sends an execute with tokens from A - // Then the grant is executed as defined - // And - // - balance A reduced (on success) - // - balance B not touched - - coord := ibctesting.NewCoordinator(t, 1) - chain := coord.GetChain(ibctesting.GetChainID(1)) - contractAddr := e2e.InstantiateReflectContract(t, chain) - require.NotEmpty(t, contractAddr) - - granterAddr := chain.SenderAccount.GetAddress() - granteePrivKey := secp256k1.GenPrivKey() - granteeAddr := sdk.AccAddress(granteePrivKey.PubKey().Address().Bytes()) - otherPrivKey := secp256k1.GenPrivKey() - otherAddr := sdk.AccAddress(otherPrivKey.PubKey().Address().Bytes()) - - chain.Fund(granteeAddr, sdk.NewInt(1_000_000)) - chain.Fund(otherAddr, sdk.NewInt(1_000_000)) - assert.Equal(t, sdk.NewInt(1_000_000), chain.Balance(granteeAddr, sdk.DefaultBondDenom).Amount) - - myAmount := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2_000_000)) - - specs := map[string]struct { - limit types.ContractAuthzLimitX - filter types.ContractAuthzFilterX - transferAmount sdk.Coin - senderKey cryptotypes.PrivKey - expErr *errorsmod.Error - }{ - "in limits and filter": { - limit: types.NewMaxFundsLimit(myAmount), - filter: types.NewAllowAllMessagesFilter(), - transferAmount: myAmount, - senderKey: granteePrivKey, - }, - "exceed limits": { - limit: types.NewMaxFundsLimit(myAmount), - filter: types.NewAllowAllMessagesFilter(), - transferAmount: myAmount.Add(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - senderKey: granteePrivKey, - expErr: sdkerrors.ErrUnauthorized, - }, - "not match filter": { - limit: types.NewMaxFundsLimit(myAmount), - filter: types.NewAcceptedMessageKeysFilter("foo"), - transferAmount: sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()), - senderKey: granteePrivKey, - expErr: sdkerrors.ErrUnauthorized, - }, - "non authorized sender address": { // sanity check - testing sdk - limit: types.NewMaxFundsLimit(myAmount), - filter: types.NewAllowAllMessagesFilter(), - senderKey: otherPrivKey, - transferAmount: myAmount, - expErr: authz.ErrNoAuthorizationFound, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup grant - grant, err := types.NewContractGrant(contractAddr, spec.limit, spec.filter) - require.NoError(t, err) - authorization := types.NewContractExecutionAuthorization(*grant) - expiry := time.Now().Add(time.Hour) - grantMsg, err := authz.NewMsgGrant(granterAddr, granteeAddr, authorization, &expiry) - require.NoError(t, err) - _, err = chain.SendMsgs(grantMsg) - require.NoError(t, err) - - granterStartBalance := chain.Balance(granterAddr, sdk.DefaultBondDenom).Amount - - // when - anyValidReflectMsg := []byte(fmt.Sprintf(`{"reflect_msg": {"msgs": [{"bank":{"burn":{"amount":[{"denom":%q, "amount": %q}]}}}]}}`, sdk.DefaultBondDenom, myAmount.Amount.String())) - execMsg := authz.NewMsgExec(spec.senderKey.PubKey().Address().Bytes(), []sdk.Msg{&types.MsgExecuteContract{ - Sender: granterAddr.String(), - Contract: contractAddr.String(), - Msg: anyValidReflectMsg, - Funds: sdk.NewCoins(spec.transferAmount), - }}) - _, gotErr := chain.SendNonDefaultSenderMsgs(spec.senderKey, &execMsg) - - // then - if spec.expErr != nil { - require.True(t, spec.expErr.Is(gotErr)) - assert.Equal(t, sdk.NewInt(1_000_000), chain.Balance(granteeAddr, sdk.DefaultBondDenom).Amount) - assert.Equal(t, granterStartBalance, chain.Balance(granterAddr, sdk.DefaultBondDenom).Amount) - return - } - require.NoError(t, gotErr) - assert.Equal(t, sdk.NewInt(1_000_000), chain.Balance(granteeAddr, sdk.DefaultBondDenom).Amount) - assert.Equal(t, granterStartBalance.Sub(spec.transferAmount.Amount), chain.Balance(granterAddr, sdk.DefaultBondDenom).Amount) - }) - } -} diff --git a/tests/e2e/group_test.go b/tests/e2e/group_test.go deleted file mode 100644 index 1b2fc7e..0000000 --- a/tests/e2e/group_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package e2e_test - -import ( - "testing" - "time" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - "github.com/cometbft/cometbft/libs/rand" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/group" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/tests/e2e" - "github.com/terpnetwork/terp-core/x/wasm/ibctesting" -) - -func TestGroupWithContract(t *testing.T) { - // Given a group with a contract as only member - // When contract submits a proposal with try_execute - // Then the payload msg is executed - - coord := ibctesting.NewCoordinator(t, 1) - chain := coord.GetChain(ibctesting.GetChainID(1)) - contractAddr := e2e.InstantiateReflectContract(t, chain) - chain.Fund(contractAddr, sdk.NewIntFromUint64(1_000_000_000)) - - members := []group.MemberRequest{ - { - Address: contractAddr.String(), - Weight: "1", - Metadata: "my contract", - }, - } - msg, err := group.NewMsgCreateGroupWithPolicy( - chain.SenderAccount.GetAddress().String(), - members, - "my group", - "my metadata", - false, - group.NewPercentageDecisionPolicy("1", time.Second, 0), - ) - require.NoError(t, err) - rsp, err := chain.SendMsgs(msg) - require.NoError(t, err) - - createRsp := rsp.MsgResponses[0].GetCachedValue().(*group.MsgCreateGroupWithPolicyResponse) - groupID, policyAddr := createRsp.GroupId, sdk.MustAccAddressFromBech32(createRsp.GroupPolicyAddress) - require.NotEmpty(t, groupID) - chain.Fund(policyAddr, sdk.NewIntFromUint64(1_000_000_000)) - // and a proposal submitted - recipientAddr := sdk.AccAddress(rand.Bytes(address.Len)) - - payload := []sdk.Msg{banktypes.NewMsgSend(policyAddr, recipientAddr, sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())))} - propMsg, err := group.NewMsgSubmitProposal(policyAddr.String(), []string{contractAddr.String()}, payload, "my proposal", group.Exec_EXEC_TRY, "my title", "my description") - require.NoError(t, err) - - rsp = e2e.MustExecViaStargateReflectContract(t, chain, contractAddr, propMsg) - bz := rsp.MsgResponses[0].GetCachedValue().(*types.MsgExecuteContractResponse).Data - var groupRsp group.MsgSubmitProposalResponse - require.NoError(t, chain.Codec.Unmarshal(bz, &groupRsp)) - // require.NotEmpty(t, groupRsp.ProposalId) - - // and coins received - recipientBalance := chain.Balance(recipientAddr, sdk.DefaultBondDenom) - expBalanceAmount := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) - assert.Equal(t, expBalanceAmount.String(), recipientBalance.String()) -} diff --git a/tests/e2e/ibc_fees_test.go b/tests/e2e/ibc_fees_test.go deleted file mode 100644 index 685880f..0000000 --- a/tests/e2e/ibc_fees_test.go +++ /dev/null @@ -1,214 +0,0 @@ -package e2e - -import ( - "bytes" - "encoding/base64" - "fmt" - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - ibcfee "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/types" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestIBCFeesTransfer(t *testing.T) { - // scenario: - // given 2 chains - // with an ics-20 channel established - // when an ics-29 fee is attached to an ibc package - // then the relayer's payee is receiving the fee(s) on success - marshaler := app.MakeEncodingConfig().Marshaler - coord := wasmibctesting.NewCoordinator(t, 2) - chainA := coord.GetChain(wasmibctesting.GetChainID(1)) - chainB := coord.GetChain(wasmibctesting.GetChainID(2)) - - actorChainA := sdk.AccAddress(chainA.SenderPrivKey.PubKey().Address()) - actorChainB := sdk.AccAddress(chainB.SenderPrivKey.PubKey().Address()) - receiver := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - payee := sdk.AccAddress(bytes.Repeat([]byte{2}, address.Len)) - oneToken := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: string(marshaler.MustMarshalJSON(&ibcfee.Metadata{FeeVersion: ibcfee.Version, AppVersion: ibctransfertypes.Version})), - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: string(marshaler.MustMarshalJSON(&ibcfee.Metadata{FeeVersion: ibcfee.Version, AppVersion: ibctransfertypes.Version})), - Order: channeltypes.UNORDERED, - } - // with an ics-20 transfer channel setup between both chains - coord.Setup(path) - require.True(t, chainA.App.IBCFeeKeeper.IsFeeEnabled(chainA.GetContext(), ibctransfertypes.PortID, path.EndpointA.ChannelID)) - // and with a payee registered on both chains - _, err := chainA.SendMsgs(ibcfee.NewMsgRegisterPayee(ibctransfertypes.PortID, path.EndpointA.ChannelID, actorChainA.String(), payee.String())) - require.NoError(t, err) - _, err = chainB.SendMsgs(ibcfee.NewMsgRegisterCounterpartyPayee(ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), payee.String())) - require.NoError(t, err) - - // when a transfer package is sent - transferCoin := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1)) - ibcPayloadMsg := ibctransfertypes.NewMsgTransfer(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, transferCoin, actorChainA.String(), receiver.String(), clienttypes.Height{}, uint64(time.Now().Add(time.Minute).UnixNano()), "testing") - ibcPackageFee := ibcfee.NewFee(oneToken, oneToken, sdk.Coins{}) - feeMsg := ibcfee.NewMsgPayPacketFee(ibcPackageFee, ibctransfertypes.PortID, path.EndpointA.ChannelID, actorChainA.String(), nil) - _, err = chainA.SendMsgs(feeMsg, ibcPayloadMsg) - require.NoError(t, err) - pendingIncentivisedPackages := chainA.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainA.GetContext(), ibctransfertypes.PortID, path.EndpointA.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 1) - - // and packages relayed - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - // then - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, transferCoin.Denom, transferCoin.Amount) - gotBalance := chainB.Balance(receiver, expBalance.Denom) - assert.Equal(t, expBalance.String(), gotBalance.String()) - payeeBalance := chainA.AllBalances(payee) - assert.Equal(t, oneToken.Add(oneToken...).String(), payeeBalance.String()) - - // and with a payee registered for chain B to A - _, err = chainA.SendMsgs(ibcfee.NewMsgRegisterCounterpartyPayee(ibctransfertypes.PortID, path.EndpointA.ChannelID, actorChainA.String(), payee.String())) - require.NoError(t, err) - _, err = chainB.SendMsgs(ibcfee.NewMsgRegisterPayee(ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), payee.String())) - require.NoError(t, err) - - // and transfer from B to A - ibcPayloadMsg = ibctransfertypes.NewMsgTransfer(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, transferCoin, actorChainB.String(), receiver.String(), clienttypes.Height{}, uint64(time.Now().Add(time.Minute).UnixNano()), "more testing") - ibcPackageFee = ibcfee.NewFee(oneToken, oneToken, sdk.Coins{}) - feeMsg = ibcfee.NewMsgPayPacketFee(ibcPackageFee, ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), nil) - _, err = chainB.SendMsgs(feeMsg, ibcPayloadMsg) - require.NoError(t, err) - pendingIncentivisedPackages = chainB.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainB.GetContext(), ibctransfertypes.PortID, path.EndpointB.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 1) - - // when packages relayed - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - // then - expBalance = ibctransfertypes.GetTransferCoin(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, transferCoin.Denom, transferCoin.Amount) - gotBalance = chainA.Balance(receiver, expBalance.Denom) - assert.Equal(t, expBalance.String(), gotBalance.String()) - payeeBalance = chainB.AllBalances(payee) - assert.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2)).String(), payeeBalance.String()) -} - -func TestIBCFeesWasm(t *testing.T) { - // scenario: - // given 2 chains with cw20-ibc on chain A and native ics20 module on B - // and an ibc channel established - // when an ics-29 fee is attached to an ibc package - // then the relayer's payee is receiving the fee(s) on success - marshaler := app.MakeEncodingConfig().Marshaler - coord := wasmibctesting.NewCoordinator(t, 2) - chainA := coord.GetChain(wasmibctesting.GetChainID(1)) - chainB := coord.GetChain(ibctesting.GetChainID(2)) - actorChainA := sdk.AccAddress(chainA.SenderPrivKey.PubKey().Address()) - actorChainB := sdk.AccAddress(chainB.SenderPrivKey.PubKey().Address()) - - // setup chain A - codeID := chainA.StoreCodeFile("./testdata/cw20_base.wasm.gz").CodeID - - initMsg := []byte(fmt.Sprintf(`{"decimals": 6, "name": "test", "symbol":"ALX", "initial_balances": [{"address": %q,"amount":"100000000"}] }`, actorChainA.String())) - cw20ContractAddr := chainA.InstantiateContract(codeID, initMsg) - - initMsg = []byte(fmt.Sprintf(`{"default_timeout": 360, "gov_contract": %q, "allowlist":[{"contract":%q}]}`, actorChainA.String(), cw20ContractAddr.String())) - codeID = chainA.StoreCodeFile("./testdata/cw20_ics20.wasm.gz").CodeID - ibcContractAddr := chainA.InstantiateContract(codeID, initMsg) - ibcContractPortID := chainA.ContractInfo(ibcContractAddr).IBCPortID - - payee := sdk.AccAddress(bytes.Repeat([]byte{2}, address.Len)) - oneToken := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibcContractPortID, - Version: string(marshaler.MustMarshalJSON(&ibcfee.Metadata{FeeVersion: ibcfee.Version, AppVersion: ibctransfertypes.Version})), - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: string(marshaler.MustMarshalJSON(&ibcfee.Metadata{FeeVersion: ibcfee.Version, AppVersion: ibctransfertypes.Version})), - Order: channeltypes.UNORDERED, - } - // with an ics-29 fee enabled channel setup between both chains - coord.Setup(path) - require.True(t, chainA.App.IBCFeeKeeper.IsFeeEnabled(chainA.GetContext(), ibcContractPortID, path.EndpointA.ChannelID)) - require.True(t, chainB.App.IBCFeeKeeper.IsFeeEnabled(chainB.GetContext(), ibctransfertypes.PortID, path.EndpointB.ChannelID)) - // and with a payee registered for A -> B - _, err := chainA.SendMsgs(ibcfee.NewMsgRegisterPayee(ibcContractPortID, path.EndpointA.ChannelID, actorChainA.String(), payee.String())) - require.NoError(t, err) - _, err = chainB.SendMsgs(ibcfee.NewMsgRegisterCounterpartyPayee(ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), payee.String())) - require.NoError(t, err) - - // when a transfer package is sent from ics20 contract on A to B - transfer := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`{"channel": %q, "remote_address": %q}`, path.EndpointA.ChannelID, actorChainB.String()))) - exec := []byte(fmt.Sprintf(`{"send":{"contract": %q, "amount": "100", "msg": %q}}`, ibcContractAddr.String(), transfer)) - execMsg := wasmtypes.MsgExecuteContract{ - Sender: actorChainA.String(), - Contract: cw20ContractAddr.String(), - Msg: exec, - } - ibcPackageFee := ibcfee.NewFee(oneToken, oneToken, sdk.Coins{}) - feeMsg := ibcfee.NewMsgPayPacketFee(ibcPackageFee, ibcContractPortID, path.EndpointA.ChannelID, actorChainA.String(), nil) - _, err = chainA.SendMsgs(feeMsg, &execMsg) - require.NoError(t, err) - pendingIncentivisedPackages := chainA.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainA.GetContext(), ibcContractPortID, path.EndpointA.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 1) - - // and packages relayed - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - // then - // on chain A - gotCW20Balance, err := chainA.App.WasmKeeper.QuerySmart(chainA.GetContext(), cw20ContractAddr, []byte(fmt.Sprintf(`{"balance":{"address": %q}}`, actorChainA.String()))) - require.NoError(t, err) - assert.JSONEq(t, `{"balance":"99999900"}`, string(gotCW20Balance)) - payeeBalance := chainA.AllBalances(payee) - assert.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2)).String(), payeeBalance.String()) - // and on chain B - pendingIncentivisedPackages = chainA.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainA.GetContext(), ibcContractPortID, path.EndpointA.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 0) - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, "cw20:"+cw20ContractAddr.String(), sdk.NewInt(100)) - gotBalance := chainB.Balance(actorChainB, expBalance.Denom) - assert.Equal(t, expBalance.String(), gotBalance.String(), chainB.AllBalances(actorChainB)) - - // and with a payee registered for chain B to A - _, err = chainA.SendMsgs(ibcfee.NewMsgRegisterCounterpartyPayee(ibcContractPortID, path.EndpointA.ChannelID, actorChainA.String(), payee.String())) - require.NoError(t, err) - _, err = chainB.SendMsgs(ibcfee.NewMsgRegisterPayee(ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), payee.String())) - require.NoError(t, err) - - // and when sent back from chain B to A - ibcPayloadMsg := ibctransfertypes.NewMsgTransfer(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, gotBalance, actorChainB.String(), actorChainA.String(), clienttypes.Height{}, uint64(time.Now().Add(time.Minute).UnixNano()), "even more tests") - ibcPackageFee = ibcfee.NewFee(oneToken, oneToken, sdk.Coins{}) - feeMsg = ibcfee.NewMsgPayPacketFee(ibcPackageFee, ibctransfertypes.PortID, path.EndpointB.ChannelID, actorChainB.String(), nil) - _, err = chainB.SendMsgs(feeMsg, ibcPayloadMsg) - require.NoError(t, err) - pendingIncentivisedPackages = chainB.App.IBCFeeKeeper.GetIdentifiedPacketFeesForChannel(chainB.GetContext(), ibctransfertypes.PortID, path.EndpointB.ChannelID) - assert.Len(t, pendingIncentivisedPackages, 1) - - // when packages relayed - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - // then - // on chain A - gotCW20Balance, err = chainA.App.WasmKeeper.QuerySmart(chainA.GetContext(), cw20ContractAddr, []byte(fmt.Sprintf(`{"balance":{"address": %q}}`, actorChainA.String()))) - require.NoError(t, err) - assert.JSONEq(t, `{"balance":"100000000"}`, string(gotCW20Balance)) - // and on chain B - payeeBalance = chainB.AllBalances(payee) - assert.Equal(t, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2)).String(), payeeBalance.String()) -} diff --git a/tests/e2e/ica_test.go b/tests/e2e/ica_test.go deleted file mode 100644 index c77605b..0000000 --- a/tests/e2e/ica_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package e2e - -import ( - "bytes" - "testing" - "time" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/gogoproto/proto" - icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" - hosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" - icatypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" -) - -func TestICA(t *testing.T) { - // scenario: - // given a host and controller chain - // when an ica is registered on the controller chain - // and the channel is established to the host chain - // then the ICA owner can submit a message via IBC - // to control their account on the host chain - coord := wasmibctesting.NewCoordinator(t, 2) - hostChain := coord.GetChain(ibctesting.GetChainID(1)) - hostParams := hosttypes.NewParams(true, []string{sdk.MsgTypeURL(&banktypes.MsgSend{})}) - hostChain.App.ICAHostKeeper.SetParams(hostChain.GetContext(), hostParams) - - controllerChain := coord.GetChain(ibctesting.GetChainID(2)) - - path := wasmibctesting.NewPath(controllerChain, hostChain) - coord.SetupConnections(path) - - ownerAddr := sdk.AccAddress(controllerChain.SenderPrivKey.PubKey().Address()) - msg := icacontrollertypes.NewMsgRegisterInterchainAccount(path.EndpointA.ConnectionID, ownerAddr.String(), "") - res, err := controllerChain.SendMsgs(msg) - require.NoError(t, err) - chanID, portID, version := parseIBCChannelEvents(t, res) - - // next open channels on both sides - path.EndpointA.ChannelID = chanID - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: portID, - Version: version, - Order: channeltypes.ORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: icatypes.HostPortID, - Version: icatypes.Version, - Order: channeltypes.ORDERED, - } - coord.CreateChannels(path) - - // assert ICA exists on controller - icaRsp, err := controllerChain.App.ICAControllerKeeper.InterchainAccount(sdk.WrapSDKContext(controllerChain.GetContext()), &icacontrollertypes.QueryInterchainAccountRequest{ - Owner: ownerAddr.String(), - ConnectionId: path.EndpointA.ConnectionID, - }) - require.NoError(t, err) - icaAddr := sdk.MustAccAddressFromBech32(icaRsp.GetAddress()) - hostChain.Fund(icaAddr, sdk.NewInt(1_000)) - - // submit a tx - targetAddr := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - sendCoin := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - payloadMsg := banktypes.NewMsgSend(icaAddr, targetAddr, sdk.NewCoins(sendCoin)) - rawPayloadData, err := icatypes.SerializeCosmosTx(controllerChain.Codec, []proto.Message{payloadMsg}) - require.NoError(t, err) - payloadPacket := icatypes.InterchainAccountPacketData{ - Type: icatypes.EXECUTE_TX, - Data: rawPayloadData, - Memo: "testing", - } - relativeTimeout := uint64(time.Minute.Nanoseconds()) // note this is in nanoseconds - msgSendTx := icacontrollertypes.NewMsgSendTx(ownerAddr.String(), path.EndpointA.ConnectionID, relativeTimeout, payloadPacket) - _, err = controllerChain.SendMsgs(msgSendTx) - require.NoError(t, err) - - assert.Equal(t, 1, len(controllerChain.PendingSendPackets)) - require.NoError(t, coord.RelayAndAckPendingPackets(path)) - - gotBalance := hostChain.Balance(targetAddr, sdk.DefaultBondDenom) - assert.Equal(t, sendCoin.String(), gotBalance.String()) -} - -func parseIBCChannelEvents(t *testing.T, res *sdk.Result) (string, string, string) { - t.Helper() - chanID, err := ibctesting.ParseChannelIDFromEvents(res.GetEvents()) - require.NoError(t, err) - portID, err := wasmibctesting.ParsePortIDFromEvents(res.GetEvents()) - require.NoError(t, err) - version, err := wasmibctesting.ParseChannelVersionFromEvents(res.GetEvents()) - require.NoError(t, err) - return chanID, portID, version -} diff --git a/tests/e2e/reflect_helper.go b/tests/e2e/reflect_helper.go deleted file mode 100644 index 1977f82..0000000 --- a/tests/e2e/reflect_helper.go +++ /dev/null @@ -1,68 +0,0 @@ -package e2e - -import ( - "encoding/json" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// InstantiateReflectContract store and instantiate a reflect contract instance -func InstantiateReflectContract(t *testing.T, chain *ibctesting.TestChain) sdk.AccAddress { - codeID := chain.StoreCodeFile("../../x/wasm/keeper/testdata/reflect_1_1.wasm").CodeID - contractAddr := chain.InstantiateContract(codeID, []byte(`{}`)) - require.NotEmpty(t, contractAddr) - return contractAddr -} - -// MustExecViaReflectContract submit execute message to send payload to reflect contract -func MustExecViaReflectContract(t *testing.T, chain *ibctesting.TestChain, contractAddr sdk.AccAddress, msgs ...wasmvmtypes.CosmosMsg) *sdk.Result { - rsp, err := ExecViaReflectContract(t, chain, contractAddr, msgs) - require.NoError(t, err) - return rsp -} - -type sdkMessageType interface { - codec.ProtoMarshaler - sdk.Msg -} - -func MustExecViaStargateReflectContract[T sdkMessageType](t *testing.T, chain *ibctesting.TestChain, contractAddr sdk.AccAddress, msgs ...T) *sdk.Result { - vmMsgs := make([]wasmvmtypes.CosmosMsg, len(msgs)) - for i, m := range msgs { - bz, err := chain.Codec.Marshal(m) - require.NoError(t, err) - vmMsgs[i] = wasmvmtypes.CosmosMsg{ - Stargate: &wasmvmtypes.StargateMsg{ - TypeURL: sdk.MsgTypeURL(m), - Value: bz, - }, - } - } - rsp, err := ExecViaReflectContract(t, chain, contractAddr, vmMsgs) - require.NoError(t, err) - return rsp -} - -// ExecViaReflectContract submit execute message to send payload to reflect contract -func ExecViaReflectContract(t *testing.T, chain *ibctesting.TestChain, contractAddr sdk.AccAddress, msgs []wasmvmtypes.CosmosMsg) (*sdk.Result, error) { - require.NotEmpty(t, msgs) - reflectSend := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{Msgs: msgs}, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - execMsg := &types.MsgExecuteContract{ - Sender: chain.SenderAccount.GetAddress().String(), - Contract: contractAddr.String(), - Msg: reflectSendBz, - } - return chain.SendMsgs(execMsg) -} diff --git a/tests/e2e/testdata/cw20_base.wasm.gz b/tests/e2e/testdata/cw20_base.wasm.gz deleted file mode 100644 index 7745e80..0000000 Binary files a/tests/e2e/testdata/cw20_base.wasm.gz and /dev/null differ diff --git a/tests/e2e/testdata/cw20_ics20.wasm.gz b/tests/e2e/testdata/cw20_ics20.wasm.gz deleted file mode 100644 index 07517a2..0000000 Binary files a/tests/e2e/testdata/cw20_ics20.wasm.gz and /dev/null differ diff --git a/testutil/nullify/nullitfy.go b/testutil/nullify/nullitfy.go new file mode 100644 index 0000000..3b968c0 --- /dev/null +++ b/testutil/nullify/nullitfy.go @@ -0,0 +1,57 @@ +// Package nullify provides methods to init nil values structs for test assertion. +package nullify + +import ( + "reflect" + "unsafe" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + coinType = reflect.TypeOf(sdk.Coin{}) + coinsType = reflect.TypeOf(sdk.Coins{}) +) + +// Fill analyze all struct fields and slices with +// reflection and initialize the nil and empty slices, +// structs, and pointers. +func Fill(x interface{}) interface{} { + v := reflect.Indirect(reflect.ValueOf(x)) + switch v.Kind() { + case reflect.Slice: + for i := 0; i < v.Len(); i++ { + obj := v.Index(i) + objPt := reflect.NewAt(obj.Type(), unsafe.Pointer(obj.UnsafeAddr())).Interface() + objPt = Fill(objPt) + obj.Set(reflect.ValueOf(objPt)) + } + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + f := reflect.Indirect(v.Field(i)) + if !f.CanSet() { + continue + } + switch f.Kind() { + case reflect.Slice: + f.Set(reflect.MakeSlice(f.Type(), 0, 0)) + case reflect.Struct: + switch f.Type() { + case coinType: + coin := reflect.New(coinType).Interface() + s := reflect.ValueOf(coin).Elem() + f.Set(s) + case coinsType: + coins := reflect.New(coinsType).Interface() + s := reflect.ValueOf(coins).Elem() + f.Set(s) + default: + objPt := reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Interface() + s := Fill(objPt) + f.Set(reflect.ValueOf(s)) + } + } + } + } + return reflect.Indirect(v).Interface() +} diff --git a/x/feeshare/README.md b/x/feeshare/README.md new file mode 100644 index 0000000..781ed45 --- /dev/null +++ b/x/feeshare/README.md @@ -0,0 +1,13 @@ +# fee-share + +This module shares contract execution fees with the application teams. +This module is a heavily modified fork of [evmos/x/revenue](https://github.com/evmos/evmos/tree/main/x/revenue). +A big thanks go to the original authors. + +[FeeShare Spec](spec/README.md) + +--- + +> [Register a Contract](spec/00_register.md) + +> [Update Conrtact Withdraw Address](spec/00_update.md) diff --git a/x/feeshare/ante/ante.go b/x/feeshare/ante/ante.go new file mode 100644 index 0000000..e871059 --- /dev/null +++ b/x/feeshare/ante/ante.go @@ -0,0 +1,120 @@ +package ante + +import ( + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + + feeshare "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +// FeeSharePayoutDecorator Run his after we already deduct the fee from the account with +// the ante.NewDeductFeeDecorator() decorator. We pull funds from the FeeCollector ModuleAccount +type FeeSharePayoutDecorator struct { + bankKeeper BankKeeper + feesharekeeper FeeShareKeeper +} + +func NewFeeSharePayoutDecorator(bk BankKeeper, fs FeeShareKeeper) FeeSharePayoutDecorator { + return FeeSharePayoutDecorator{ + bankKeeper: bk, + feesharekeeper: fs, + } +} + +func (fsd FeeSharePayoutDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { + feeTx, ok := tx.(sdk.FeeTx) + if !ok { + return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx") + } + + err = FeeSharePayout(ctx, fsd.bankKeeper, feeTx.GetFee(), fsd.feesharekeeper, tx.GetMsgs()) + if err != nil { + return ctx, errorsmod.Wrapf(sdkerrors.ErrInsufficientFunds, err.Error()) + } + + return next(ctx, tx, simulate) +} + +// FeePayLogic takes the total fees and splits them based on the governance params +// and the number of contracts we are executing on. +// This returns the amount of fees each contract developer should get. +// tested in ante_test.go +func FeePayLogic(fees sdk.Coins, govPercent sdk.Dec, numPairs int) sdk.Coins { + var splitFees sdk.Coins + for _, c := range fees.Sort() { + rewardAmount := govPercent.MulInt(c.Amount).QuoInt64(int64(numPairs)).RoundInt() + if !rewardAmount.IsZero() { + splitFees = splitFees.Add(sdk.NewCoin(c.Denom, rewardAmount)) + } + } + return splitFees +} + +// FeeSharePayout takes the total fees and redistributes 50% (or param set) to the contract developers +// provided they opted-in to payments. +func FeeSharePayout(ctx sdk.Context, bankKeeper BankKeeper, totalFees sdk.Coins, revKeeper FeeShareKeeper, msgs []sdk.Msg) error { + params := revKeeper.GetParams(ctx) + if !params.EnableFeeShare { + return nil + } + + // Get valid withdraw addresses from contracts + toPay := make([]sdk.AccAddress, 0) + for _, msg := range msgs { + if _, ok := msg.(*wasmtypes.MsgExecuteContract); ok { + contractAddr, err := sdk.AccAddressFromBech32(msg.(*wasmtypes.MsgExecuteContract).Contract) + if err != nil { + return err + } + + shareData, _ := revKeeper.GetFeeShare(ctx, contractAddr) + + withdrawAddr := shareData.GetWithdrawerAddr() + if withdrawAddr != nil && !withdrawAddr.Empty() { + toPay = append(toPay, withdrawAddr) + } + } + } + + // Do nothing if no one needs payment + if len(toPay) == 0 { + return nil + } + + // Get only allowed governance fees to be paid (helps for taxes) + var fees sdk.Coins + if len(params.AllowedDenoms) == 0 { + // If empty, we allow all denoms to be used as payment + fees = totalFees + } else { + for _, fee := range totalFees.Sort() { + for _, allowed := range params.AllowedDenoms { + if fee.Denom == allowed { + fees = fees.Add(fee) + } + } + } + } + + // FeeShare logic payouts for contracts + numPairs := len(toPay) + if numPairs > 0 { + govPercent := params.DeveloperShares + splitFees := FeePayLogic(fees, govPercent, numPairs) + + // pay fees evenly between all withdraw addresses + for _, withdrawAddr := range toPay { + err := bankKeeper.SendCoinsFromModuleToAccount(ctx, authtypes.FeeCollectorName, withdrawAddr, splitFees) + if err != nil { + return errorsmod.Wrapf(feeshare.ErrFeeSharePayment, "failed to pay fees to contract developer: %s", err.Error()) + } + } + } + + return nil +} diff --git a/x/feeshare/ante/ante_test.go b/x/feeshare/ante/ante_test.go new file mode 100644 index 0000000..321110a --- /dev/null +++ b/x/feeshare/ante/ante_test.go @@ -0,0 +1,115 @@ +package ante_test + +import ( + "testing" + + "github.com/stretchr/testify/suite" + + sdk "github.com/cosmos/cosmos-sdk/types" + + ante "github.com/terpnetwork/terp-core/v2/x/feeshare/ante" +) + +type AnteTestSuite struct { + suite.Suite +} + +func TestAnteSuite(t *testing.T) { + suite.Run(t, new(AnteTestSuite)) +} + +func (suite *AnteTestSuite) TestFeeLogic() { + // We expect all to pass + feeCoins := sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(500)), sdk.NewCoin("utoken", sdk.NewInt(250))) + + testCases := []struct { + name string + incomingFee sdk.Coins + govPercent sdk.Dec + numContracts int + expectedFeePayment sdk.Coins + }{ + { + "100% fee / 1 contract", + feeCoins, + sdk.NewDecWithPrec(100, 2), + 1, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(500)), sdk.NewCoin("utoken", sdk.NewInt(250))), + }, + { + "100% fee / 2 contracts", + feeCoins, + sdk.NewDecWithPrec(100, 2), + 2, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(250)), sdk.NewCoin("utoken", sdk.NewInt(125))), + }, + { + "100% fee / 10 contracts", + feeCoins, + sdk.NewDecWithPrec(100, 2), + 10, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(50)), sdk.NewCoin("utoken", sdk.NewInt(25))), + }, + { + "67% fee / 7 contracts", + feeCoins, + sdk.NewDecWithPrec(67, 2), + 7, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(48)), sdk.NewCoin("utoken", sdk.NewInt(24))), + }, + { + "50% fee / 1 contracts", + feeCoins, + sdk.NewDecWithPrec(50, 2), + 1, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(250)), sdk.NewCoin("utoken", sdk.NewInt(125))), + }, + { + "50% fee / 2 contracts", + feeCoins, + sdk.NewDecWithPrec(50, 2), + 2, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(125)), sdk.NewCoin("utoken", sdk.NewInt(62))), + }, + { + "50% fee / 3 contracts", + feeCoins, + sdk.NewDecWithPrec(50, 2), + 3, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(83)), sdk.NewCoin("utoken", sdk.NewInt(42))), + }, + { + "25% fee / 2 contracts", + feeCoins, + sdk.NewDecWithPrec(25, 2), + 2, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(62)), sdk.NewCoin("utoken", sdk.NewInt(31))), + }, + { + "15% fee / 3 contracts", + feeCoins, + sdk.NewDecWithPrec(15, 2), + 3, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(25)), sdk.NewCoin("utoken", sdk.NewInt(12))), + }, + { + "1% fee / 2 contracts", + feeCoins, + sdk.NewDecWithPrec(1, 2), + 2, + sdk.NewCoins(sdk.NewCoin("uthiol", sdk.NewInt(2)), sdk.NewCoin("utoken", sdk.NewInt(1))), + }, + } + + for _, tc := range testCases { + coins := ante.FeePayLogic(tc.incomingFee, tc.govPercent, tc.numContracts) + + for _, coin := range coins { + for _, expectedCoin := range tc.expectedFeePayment { + if coin.Denom == expectedCoin.Denom { + suite.Require().Equal(expectedCoin.Amount.Int64(), coin.Amount.Int64(), tc.name) + } + } + } + } +} diff --git a/x/feeshare/ante/expected_keepers.go b/x/feeshare/ante/expected_keepers.go new file mode 100644 index 0000000..438c33b --- /dev/null +++ b/x/feeshare/ante/expected_keepers.go @@ -0,0 +1,19 @@ +package ante + +// Used for the Terp ante handler so we can properly send 50% of fees to dAPP developers via fee share module + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + revtypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +type BankKeeper interface { + SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error +} + +type FeeShareKeeper interface { + GetParams(ctx sdk.Context) revtypes.Params + GetFeeShare(ctx sdk.Context, contract sdk.Address) (revtypes.FeeShare, bool) +} diff --git a/x/feeshare/client/cli/query.go b/x/feeshare/client/cli/query.go new file mode 100644 index 0000000..fb5dc3c --- /dev/null +++ b/x/feeshare/client/cli/query.go @@ -0,0 +1,225 @@ +package cli + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/version" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd() *cobra.Command { + feesQueryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + feesQueryCmd.AddCommand( + GetCmdQueryFeeShares(), + GetCmdQueryFeeShare(), + GetCmdQueryParams(), + GetCmdQueryDeployerFeeShares(), + GetCmdQueryWithdrawerFeeShares(), + ) + + return feesQueryCmd +} + +// GetCmdQueryFeeShares implements a command to return all registered contracts +// for fee distribution +func GetCmdQueryFeeShares() *cobra.Command { + cmd := &cobra.Command{ + Use: "contracts", + Short: "Query all FeeShares", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + req := &types.QueryFeeSharesRequest{ + Pagination: pageReq, + } + + res, err := queryClient.FeeShares(context.Background(), req) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetCmdQueryFeeShare implements a command to return a registered contract for fee +// distribution +func GetCmdQueryFeeShare() *cobra.Command { + cmd := &cobra.Command{ + Use: "contract [contract_address]", + Args: cobra.ExactArgs(1), + Short: "Query a registered contract for fee distribution by its bech32 address", + Long: "Query a registered contract for fee distribution by its bech32 address", + Example: fmt.Sprintf("%s query feeshare contract ", version.AppName), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + req := &types.QueryFeeShareRequest{ContractAddress: args[0]} + if err := req.ValidateBasic(); err != nil { + return err + } + + // Query store + res, err := queryClient.FeeShare(context.Background(), req) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + flags.AddQueryFlagsToCmd(cmd) + return cmd +} + +// GetCmdQueryParams implements a command to return the current FeeShare +// parameters. +func GetCmdQueryParams() *cobra.Command { + cmd := &cobra.Command{ + Use: "params", + Short: "Query the current feeshare module parameters", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + params := &types.QueryParamsRequest{} + + res, err := queryClient.Params(context.Background(), params) + if err != nil { + return err + } + + return clientCtx.PrintProto(&res.Params) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetCmdQueryDeployerFeeShares implements a command that returns all contracts +// that a deployer has registered for fee distribution +func GetCmdQueryDeployerFeeShares() *cobra.Command { + cmd := &cobra.Command{ + Use: "deployer-contracts [deployer_address]", + Args: cobra.ExactArgs(1), + Short: "Query all contracts that a given deployer has registered for feeshare distribution", + Long: "Query all contracts that a given deployer has registered for feeshare distribution", + Example: fmt.Sprintf("%s query feeshare deployer-contracts ", version.AppName), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + deployerFeeShareReq := &types.QueryDeployerFeeSharesRequest{ + DeployerAddress: args[0], + Pagination: pageReq, + } + if deployerFeeShareReq.ValidateBasic() != nil { + return err + } + + // Query store + res, err := queryClient.DeployerFeeShares(context.Background(), deployerFeeShareReq) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + flags.AddQueryFlagsToCmd(cmd) + return cmd +} + +// GetCmdQueryWithdrawerFeeShares implements a command that returns all +// contracts that have registered for fee distribution with a given withdraw +// address +func GetCmdQueryWithdrawerFeeShares() *cobra.Command { + cmd := &cobra.Command{ + Use: "withdrawer-contracts [withdraw_address]", + Args: cobra.ExactArgs(1), + Short: "Query all contracts that have been registered for feeshare distribution with a given withdrawer address", + Long: "Query all contracts that have been registered for feeshare distribution with a given withdrawer address", + Example: fmt.Sprintf("%s query feeshare withdrawer-contracts ", version.AppName), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + + pageReq, err := client.ReadPageRequest(cmd.Flags()) + if err != nil { + return err + } + + withdrawReq := &types.QueryWithdrawerFeeSharesRequest{ + WithdrawerAddress: args[0], + Pagination: pageReq, + } + + if err := withdrawReq.ValidateBasic(); err != nil { + return err + } + + // Query store + res, err := queryClient.WithdrawerFeeShares(context.Background(), withdrawReq) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + flags.AddQueryFlagsToCmd(cmd) + return cmd +} diff --git a/x/feeshare/client/cli/tx.go b/x/feeshare/client/cli/tx.go new file mode 100644 index 0000000..e0b4dbd --- /dev/null +++ b/x/feeshare/client/cli/tx.go @@ -0,0 +1,146 @@ +package cli + +import ( + "fmt" + + "github.com/spf13/cobra" + + "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/terpnetwork/terp-core/v2/x/feeshare/types" +) + +// NewTxCmd returns a root CLI command handler for certain modules/FeeShare +// transaction commands. +func NewTxCmd() *cobra.Command { + txCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "FeeShare subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + txCmd.AddCommand( + NewRegisterFeeShare(), + NewCancelFeeShare(), + NewUpdateFeeShare(), + ) + return txCmd +} + +// NewRegisterFeeShare returns a CLI command handler for registering a +// contract for fee distribution +func NewRegisterFeeShare() *cobra.Command { + cmd := &cobra.Command{ + Use: "register [contract_bech32] [withdraw_bech32]", + Short: "Register a contract for fee distribution. Only the contract admin can register a contract.", + Long: "Register a contract for feeshare distribution. **NOTE** Please ensure, that the admin of the contract (or the DAO/factory that deployed the contract) is an account that is owned by your project, to avoid that an individual admin who leaves your project becomes malicious.", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + deployer := cliCtx.GetFromAddress() + + contract := args[0] + withdrawer := args[1] + + msg := &types.MsgRegisterFeeShare{ + ContractAddress: contract, + DeployerAddress: deployer.String(), + WithdrawerAddress: withdrawer, + } + + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} + +// NewCancelFeeShare returns a CLI command handler for canceling a +// contract for fee distribution +func NewCancelFeeShare() *cobra.Command { + cmd := &cobra.Command{ + Use: "cancel [contract_bech32]", + Short: "Cancel a contract from feeshare distribution", + Long: "Cancel a contract from feeshare distribution. The withdraw address will no longer receive fees from users interacting with the contract.\nOnly the contract admin can cancel a contract.", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + deployer := cliCtx.GetFromAddress() + + contract := args[0] + + msg := &types.MsgCancelFeeShare{ + ContractAddress: contract, + DeployerAddress: deployer.String(), + } + + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} + +// NewUpdateFeeShare returns a CLI command handler for updating the withdraw +// address of a contract for fee distribution +func NewUpdateFeeShare() *cobra.Command { + cmd := &cobra.Command{ + Use: "update [contract_bech32] [new_withdraw_bech32]", + Short: "Update withdrawer address for a contract registered for feeshare distribution.", + Long: "Update withdrawer address for a contract registered for feeshare distribution. \nOnly the contract admin can update the withdrawer address.", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + cliCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + deployer := cliCtx.GetFromAddress() + + contract := args[0] + if _, err := sdk.AccAddressFromBech32(contract); err != nil { + return fmt.Errorf("invalid contract bech32 address %w", err) + } + + withdrawer := args[1] + + msg := &types.MsgUpdateFeeShare{ + ContractAddress: contract, + DeployerAddress: deployer.String(), + WithdrawerAddress: withdrawer, + } + + if err := msg.ValidateBasic(); err != nil { + return err + } + + return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} diff --git a/x/wasm/exported/exported.go b/x/feeshare/exported/exported.go similarity index 100% rename from x/wasm/exported/exported.go rename to x/feeshare/exported/exported.go diff --git a/x/feeshare/genesis.go b/x/feeshare/genesis.go new file mode 100644 index 0000000..bae421b --- /dev/null +++ b/x/feeshare/genesis.go @@ -0,0 +1,41 @@ +package feeshare + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/keeper" + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +// InitGenesis import module genesis +func InitGenesis( + ctx sdk.Context, + k keeper.Keeper, + data types.GenesisState, +) { + if err := k.SetParams(ctx, data.Params); err != nil { + panic(err) + } + + for _, share := range data.FeeShare { + contract := share.GetContractAddr() + deployer := share.GetDeployerAddr() + withdrawer := share.GetWithdrawerAddr() + + // Set initial contracts receiving transaction fees + k.SetFeeShare(ctx, share) + k.SetDeployerMap(ctx, deployer, contract) + + if len(withdrawer) != 0 { + k.SetWithdrawerMap(ctx, withdrawer, contract) + } + } +} + +// ExportGenesis export module state +func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { + return &types.GenesisState{ + Params: k.GetParams(ctx), + FeeShare: k.GetFeeShares(ctx), + } +} diff --git a/x/feeshare/genesis_test.go b/x/feeshare/genesis_test.go new file mode 100644 index 0000000..33413ef --- /dev/null +++ b/x/feeshare/genesis_test.go @@ -0,0 +1,118 @@ +package feeshare_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/suite" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/app" + "github.com/terpnetwork/terp-core/v2/x/feeshare" + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +type GenesisTestSuite struct { + suite.Suite + + ctx sdk.Context + + app *app.TerpApp + genesis types.GenesisState +} + +func TestGenesisTestSuite(t *testing.T) { + suite.Run(t, new(GenesisTestSuite)) +} + +func (suite *GenesisTestSuite) SetupTest() { + app := app.Setup(suite.T()) + ctx := app.BaseApp.NewContext(false, tmproto.Header{ + ChainID: "testing", + }) + + suite.app = app + suite.ctx = ctx + + suite.genesis = *types.DefaultGenesisState() +} + +func (suite *GenesisTestSuite) TestFeeShareInitGenesis() { + testCases := []struct { + name string + genesis types.GenesisState + expPanic bool + }{ + { + "default genesis", + suite.genesis, + false, + }, + { + "custom genesis - feeshare disabled", + types.GenesisState{ + Params: types.Params{ + EnableFeeShare: false, + DeveloperShares: types.DefaultDeveloperShares, + AllowedDenoms: []string{"uthiol"}, + }, + }, + false, + }, + { + "custom genesis - feeshare enabled, 0% developer shares", + types.GenesisState{ + Params: types.Params{ + EnableFeeShare: true, + DeveloperShares: sdk.NewDecWithPrec(0, 2), + AllowedDenoms: []string{"uthiol"}, + }, + }, + false, + }, + { + "custom genesis - feeshare enabled, 100% developer shares", + types.GenesisState{ + Params: types.Params{ + EnableFeeShare: true, + DeveloperShares: sdk.NewDecWithPrec(100, 2), + AllowedDenoms: []string{"uthiol"}, + }, + }, + false, + }, + { + "custom genesis - feeshare enabled, all denoms allowed", + types.GenesisState{ + Params: types.Params{ + EnableFeeShare: true, + DeveloperShares: sdk.NewDecWithPrec(10, 2), + AllowedDenoms: []string(nil), + }, + }, + false, + }, + } + + for _, tc := range testCases { + suite.Run(fmt.Sprintf("Case %s", tc.name), func() { + suite.SetupTest() // reset + + if tc.expPanic { + suite.Require().Panics(func() { + feeshare.InitGenesis(suite.ctx, suite.app.FeeShareKeeper, tc.genesis) + }) + } else { + suite.Require().NotPanics(func() { + feeshare.InitGenesis(suite.ctx, suite.app.FeeShareKeeper, tc.genesis) + }) + + params := suite.app.FeeShareKeeper.GetParams(suite.ctx) + suite.Require().Equal(tc.genesis.Params, params) + } + }) + } +} diff --git a/x/feeshare/integration_test.go b/x/feeshare/integration_test.go new file mode 100644 index 0000000..8e8a8cd --- /dev/null +++ b/x/feeshare/integration_test.go @@ -0,0 +1,94 @@ +package feeshare_test + +import ( + "encoding/json" + "path/filepath" + "testing" + + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/log" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + + bam "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/snapshots" + snapshottypes "github.com/cosmos/cosmos-sdk/snapshots/types" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/mint/types" + + terpapp "github.com/terpnetwork/terp-core/v2/app" +) + +// returns context and an app with updated mint keeper +func CreateTestApp(t *testing.T, isCheckTx bool) (*terpapp.TerpApp, sdk.Context) { + app := Setup(t, isCheckTx) + + ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{ + ChainID: "testing", + }) + if err := app.MintKeeper.SetParams(ctx, types.DefaultParams()); err != nil { + panic(err) + } + app.MintKeeper.SetMinter(ctx, types.DefaultInitialMinter()) + + return app, ctx +} + +func Setup(t *testing.T, isCheckTx bool) *terpapp.TerpApp { + app, genesisState := GenApp(t, !isCheckTx) + if !isCheckTx { + // init chain must be called to stop deliverState from being nil + stateBytes, err := json.MarshalIndent(genesisState, "", " ") + if err != nil { + panic(err) + } + + // Initialize the chain + app.InitChain( + abci.RequestInitChain{ + Validators: []abci.ValidatorUpdate{}, + // ConsensusParams: &tmproto.ConsensusParams{}, + ConsensusParams: simtestutil.DefaultConsensusParams, + AppStateBytes: stateBytes, + ChainId: "testing", + }, + ) + } + + return app +} + +func GenApp(t *testing.T, withGenesis bool, opts ...wasmkeeper.Option) (*terpapp.TerpApp, terpapp.GenesisState) { + db := dbm.NewMemDB() + nodeHome := t.TempDir() + snapshotDir := filepath.Join(nodeHome, "data", "snapshots") + + snapshotDB, err := dbm.NewDB("metadata", dbm.GoLevelDBBackend, snapshotDir) + require.NoError(t, err) + t.Cleanup(func() { snapshotDB.Close() }) + snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) + require.NoError(t, err) + + app := terpapp.NewTerpApp( + log.NewNopLogger(), + db, + nil, + true, + wasmtypes.EnableAllProposals, + simtestutil.EmptyAppOptions{}, + opts, + bam.SetChainID("testing"), + bam.SetSnapshot(snapshotStore, snapshottypes.SnapshotOptions{KeepRecent: 2}), + ) + + if withGenesis { + return app, terpapp.NewDefaultGenesisState(app.AppCodec()) + } + + return app, terpapp.GenesisState{} +} diff --git a/x/feeshare/keeper/feeshare.go b/x/feeshare/keeper/feeshare.go new file mode 100644 index 0000000..0ccbe9a --- /dev/null +++ b/x/feeshare/keeper/feeshare.go @@ -0,0 +1,155 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +// GetFeeShares returns all registered FeeShares. +func (k Keeper) GetFeeShares(ctx sdk.Context) []types.FeeShare { + feeshares := []types.FeeShare{} + + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.KeyPrefixFeeShare) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + var feeshare types.FeeShare + k.cdc.MustUnmarshal(iterator.Value(), &feeshare) + + feeshares = append(feeshares, feeshare) + } + + return feeshares +} + +// IterateFeeShares iterates over all registered contracts and performs a +// callback with the corresponding FeeShare. +func (k Keeper) IterateFeeShares( + ctx sdk.Context, + handlerFn func(fee types.FeeShare) (stop bool), +) { + store := ctx.KVStore(k.storeKey) + iterator := sdk.KVStorePrefixIterator(store, types.KeyPrefixFeeShare) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + var feeshare types.FeeShare + k.cdc.MustUnmarshal(iterator.Value(), &feeshare) + + if handlerFn(feeshare) { + break + } + } +} + +// GetFeeShare returns the FeeShare for a registered contract +func (k Keeper) GetFeeShare( + ctx sdk.Context, + contract sdk.Address, +) (types.FeeShare, bool) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixFeeShare) + bz := store.Get(contract.Bytes()) + if len(bz) == 0 { + return types.FeeShare{}, false + } + + var feeshare types.FeeShare + k.cdc.MustUnmarshal(bz, &feeshare) + return feeshare, true +} + +// SetFeeShare stores the FeeShare for a registered contract. +func (k Keeper) SetFeeShare(ctx sdk.Context, feeshare types.FeeShare) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixFeeShare) + key := feeshare.GetContractAddr() + bz := k.cdc.MustMarshal(&feeshare) + store.Set(key.Bytes(), bz) +} + +// DeleteFeeShare deletes a FeeShare of a registered contract. +func (k Keeper) DeleteFeeShare(ctx sdk.Context, fee types.FeeShare) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixFeeShare) + key := fee.GetContractAddr() + store.Delete(key.Bytes()) +} + +// SetDeployerMap stores a contract-by-deployer mapping +func (k Keeper) SetDeployerMap( + ctx sdk.Context, + deployer sdk.AccAddress, + contract sdk.Address, +) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixDeployer) + key := append(deployer.Bytes(), contract.Bytes()...) + store.Set(key, []byte{1}) +} + +// DeleteDeployerMap deletes a contract-by-deployer mapping +func (k Keeper) DeleteDeployerMap( + ctx sdk.Context, + deployer sdk.AccAddress, + contract sdk.Address, +) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixDeployer) + key := append(deployer.Bytes(), contract.Bytes()...) + store.Delete(key) +} + +// SetWithdrawerMap stores a contract-by-withdrawer mapping +func (k Keeper) SetWithdrawerMap( + ctx sdk.Context, + withdrawer sdk.AccAddress, + contract sdk.Address, +) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixWithdrawer) + key := append(withdrawer.Bytes(), contract.Bytes()...) + store.Set(key, []byte{1}) +} + +// DeleteWithdrawMap deletes a contract-by-withdrawer mapping +func (k Keeper) DeleteWithdrawerMap( + ctx sdk.Context, + withdrawer sdk.AccAddress, + contract sdk.Address, +) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixWithdrawer) + key := append(withdrawer.Bytes(), contract.Bytes()...) + store.Delete(key) +} + +// IsFeeShareRegistered checks if a contract was registered for receiving +// transaction fees +func (k Keeper) IsFeeShareRegistered( + ctx sdk.Context, + contract sdk.Address, +) bool { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixFeeShare) + return store.Has(contract.Bytes()) +} + +// IsDeployerMapSet checks if a given contract-by-withdrawer mapping is set in +// store +func (k Keeper) IsDeployerMapSet( + ctx sdk.Context, + deployer sdk.AccAddress, + contract sdk.Address, +) bool { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixDeployer) + key := append(deployer.Bytes(), contract.Bytes()...) + return store.Has(key) +} + +// IsWithdrawerMapSet checks if a give contract-by-withdrawer mapping is set in +// store +func (k Keeper) IsWithdrawerMapSet( + ctx sdk.Context, + withdrawer sdk.AccAddress, + contract sdk.Address, +) bool { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixWithdrawer) + key := append(withdrawer.Bytes(), contract.Bytes()...) + return store.Has(key) +} diff --git a/x/feeshare/keeper/grpc_query.go b/x/feeshare/keeper/grpc_query.go new file mode 100644 index 0000000..67be214 --- /dev/null +++ b/x/feeshare/keeper/grpc_query.go @@ -0,0 +1,179 @@ +package keeper + +import ( + "context" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/cosmos/cosmos-sdk/store/prefix" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +var _ types.QueryServer = Querier{} + +// Querier defines a wrapper around the x/FeeShare keeper providing gRPC method +// handlers. +type Querier struct { + Keeper +} + +func NewQuerier(k Keeper) Querier { + return Querier{Keeper: k} +} + +// FeeShares returns all FeeShares that have been registered for fee distribution +func (q Querier) FeeShares( + c context.Context, + req *types.QueryFeeSharesRequest, +) (*types.QueryFeeSharesResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + var feeshares []types.FeeShare + store := prefix.NewStore(ctx.KVStore(q.storeKey), types.KeyPrefixFeeShare) + + pageRes, err := query.Paginate(store, req.Pagination, func(_, value []byte) error { + var feeshare types.FeeShare + if err := q.cdc.Unmarshal(value, &feeshare); err != nil { + return err + } + feeshares = append(feeshares, feeshare) + return nil + }) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + return &types.QueryFeeSharesResponse{ + Feeshare: feeshares, + Pagination: pageRes, + }, nil +} + +// FeeShare returns the FeeShare that has been registered for fee distribution for a given +// contract +func (q Querier) FeeShare( + c context.Context, + req *types.QueryFeeShareRequest, +) (*types.QueryFeeShareResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + // check if the contract is a non-zero hex address + contract, err := sdk.AccAddressFromBech32(req.ContractAddress) + if err != nil { + return nil, status.Errorf( + codes.InvalidArgument, + "invalid format for contract %s, should be bech32 ('terp...')", req.ContractAddress, + ) + } + + feeshare, found := q.GetFeeShare(ctx, contract) + if !found { + return nil, status.Errorf( + codes.NotFound, + "fees registered contract '%s'", + req.ContractAddress, + ) + } + + return &types.QueryFeeShareResponse{Feeshare: feeshare}, nil +} + +// Params returns the fees module params +func (q Querier) Params( + c context.Context, + _ *types.QueryParamsRequest, +) (*types.QueryParamsResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + params := q.GetParams(ctx) + return &types.QueryParamsResponse{Params: params}, nil +} + +// DeployerFeeShares returns all contracts that have been registered for fee +// distribution by a given deployer +func (q Querier) DeployerFeeShares( //nolint: dupl + c context.Context, + req *types.QueryDeployerFeeSharesRequest, +) (*types.QueryDeployerFeeSharesResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + deployer, err := sdk.AccAddressFromBech32(req.DeployerAddress) + if err != nil { + return nil, status.Errorf( + codes.InvalidArgument, + "invalid format for deployer %s, should be bech32 ('terp...')", req.DeployerAddress, + ) + } + + var contracts []string + store := prefix.NewStore( + ctx.KVStore(q.storeKey), + types.GetKeyPrefixDeployer(deployer), + ) + + pageRes, err := query.Paginate(store, req.Pagination, func(key, _ []byte) error { + contracts = append(contracts, sdk.AccAddress(key).String()) + return nil + }) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + + return &types.QueryDeployerFeeSharesResponse{ + ContractAddresses: contracts, + Pagination: pageRes, + }, nil +} + +// WithdrawerFeeShares returns all fees for a given withdraw address +func (q Querier) WithdrawerFeeShares( //nolint: dupl + c context.Context, + req *types.QueryWithdrawerFeeSharesRequest, +) (*types.QueryWithdrawerFeeSharesResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "empty request") + } + + ctx := sdk.UnwrapSDKContext(c) + + deployer, err := sdk.AccAddressFromBech32(req.WithdrawerAddress) + if err != nil { + return nil, status.Errorf( + codes.InvalidArgument, + "invalid format for withdraw addr %s, should be bech32 ('terp...')", req.WithdrawerAddress, + ) + } + + var contracts []string + store := prefix.NewStore( + ctx.KVStore(q.storeKey), + types.GetKeyPrefixWithdrawer(deployer), + ) + + pageRes, err := query.Paginate(store, req.Pagination, func(key, _ []byte) error { + contracts = append(contracts, sdk.AccAddress(key).String()) + + return nil + }) + if err != nil { + return nil, status.Error(codes.Internal, err.Error()) + } + return &types.QueryWithdrawerFeeSharesResponse{ + ContractAddresses: contracts, + Pagination: pageRes, + }, nil +} diff --git a/x/feeshare/keeper/grpc_query_test.go b/x/feeshare/keeper/grpc_query_test.go new file mode 100644 index 0000000..9cc2183 --- /dev/null +++ b/x/feeshare/keeper/grpc_query_test.go @@ -0,0 +1,260 @@ +package keeper_test + +import ( + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + + "github.com/terpnetwork/terp-core/v2/testutil/nullify" + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +func (s *IntegrationTestSuite) TestFeeShares() { + s.SetupTest() + _, _, sender := testdata.KeyTestPubAddr() + _ = s.FundAccount(s.ctx, sender, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1_000_000)))) + + _, _, withdrawer := testdata.KeyTestPubAddr() + + var contractAddressList []string + var index uint64 + for index < 5 { + contractAddress := s.InstantiateContract(sender.String(), "") + contractAddressList = append(contractAddressList, contractAddress) + index++ + } + + // RegsisFeeShare + var feeShares []types.FeeShare + for _, contractAddress := range contractAddressList { + goCtx := sdk.WrapSDKContext(s.ctx) + msg := &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + } + + feeShare := types.FeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + } + + feeShares = append(feeShares, feeShare) + + _, err := s.feeShareMsgServer.RegisterFeeShare(goCtx, msg) + s.Require().NoError(err) + } + + request := func(next []byte, offset, limit uint64, total bool) *types.QueryFeeSharesRequest { + return &types.QueryFeeSharesRequest{ + Pagination: &query.PageRequest{ + Key: next, + Offset: offset, + Limit: limit, + CountTotal: total, + }, + } + } + s.Run("ByOffset", func() { + step := 2 + goCtx := sdk.WrapSDKContext(s.ctx) + for i := 0; i < len(contractAddressList); i += step { + resp, err := s.queryClient.FeeShares(goCtx, request(nil, uint64(i), uint64(step), false)) + s.Require().NoError(err) + s.Require().LessOrEqual(len(resp.Feeshare), step) + s.Require().Subset(nullify.Fill(feeShares), nullify.Fill(resp.Feeshare)) + } + }) + s.Run("ByKey", func() { + step := 2 + var next []byte + goCtx := sdk.WrapSDKContext(s.ctx) + for i := 0; i < len(contractAddressList); i += step { + resp, err := s.queryClient.FeeShares(goCtx, request(next, 0, uint64(step), false)) + s.Require().NoError(err) + s.Require().LessOrEqual(len(resp.Feeshare), step) + s.Require().Subset(nullify.Fill(feeShares), nullify.Fill(resp.Feeshare)) + next = resp.Pagination.NextKey + } + }) + s.Run("Total", func() { + goCtx := sdk.WrapSDKContext(s.ctx) + resp, err := s.queryClient.FeeShares(goCtx, request(nil, 0, 0, true)) + s.Require().NoError(err) + s.Require().Equal(len(feeShares), int(resp.Pagination.Total)) + s.Require().ElementsMatch(nullify.Fill(feeShares), nullify.Fill(resp.Feeshare)) + }) +} + +func (s *IntegrationTestSuite) TestFeeShare() { + s.SetupTest() + _, _, sender := testdata.KeyTestPubAddr() + _ = s.FundAccount(s.ctx, sender, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1_000_000)))) + + _, _, withdrawer := testdata.KeyTestPubAddr() + + contractAddress := s.InstantiateContract(sender.String(), "") + goCtx := sdk.WrapSDKContext(s.ctx) + msg := &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + } + + feeShare := types.FeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + } + _, err := s.feeShareMsgServer.RegisterFeeShare(goCtx, msg) + s.Require().NoError(err) + + req := &types.QueryFeeShareRequest{ + ContractAddress: contractAddress, + } + goCtx = sdk.WrapSDKContext(s.ctx) + resp, err := s.queryClient.FeeShare(goCtx, req) + s.Require().NoError(err) + s.Require().Equal(resp.Feeshare, feeShare) +} + +func (s *IntegrationTestSuite) TestDeployerFeeShares() { + s.SetupTest() + _, _, sender := testdata.KeyTestPubAddr() + _ = s.FundAccount(s.ctx, sender, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1_000_000)))) + + _, _, withdrawer := testdata.KeyTestPubAddr() + + var contractAddressList []string + var index uint64 + for index < 5 { + contractAddress := s.InstantiateContract(sender.String(), "") + contractAddressList = append(contractAddressList, contractAddress) + index++ + } + + // RegsisFeeShare + for _, contractAddress := range contractAddressList { + goCtx := sdk.WrapSDKContext(s.ctx) + msg := &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + } + + _, err := s.feeShareMsgServer.RegisterFeeShare(goCtx, msg) + s.Require().NoError(err) + } + + request := func(next []byte, offset, limit uint64, total bool) *types.QueryDeployerFeeSharesRequest { + return &types.QueryDeployerFeeSharesRequest{ + DeployerAddress: sender.String(), + Pagination: &query.PageRequest{ + Key: next, + Offset: offset, + Limit: limit, + CountTotal: total, + }, + } + } + s.Run("ByOffset", func() { + step := 2 + goCtx := sdk.WrapSDKContext(s.ctx) + for i := 0; i < len(contractAddressList); i += step { + resp, err := s.queryClient.DeployerFeeShares(goCtx, request(nil, uint64(i), uint64(step), false)) + s.Require().NoError(err) + s.Require().LessOrEqual(len(resp.ContractAddresses), step) + s.Require().Subset(nullify.Fill(contractAddressList), nullify.Fill(resp.ContractAddresses)) + } + }) + s.Run("ByKey", func() { + step := 2 + var next []byte + goCtx := sdk.WrapSDKContext(s.ctx) + for i := 0; i < len(contractAddressList); i += step { + resp, err := s.queryClient.DeployerFeeShares(goCtx, request(next, 0, uint64(step), false)) + s.Require().NoError(err) + s.Require().LessOrEqual(len(resp.ContractAddresses), step) + s.Require().Subset(nullify.Fill(contractAddressList), nullify.Fill(resp.ContractAddresses)) + next = resp.Pagination.NextKey + } + }) + s.Run("Total", func() { + goCtx := sdk.WrapSDKContext(s.ctx) + resp, err := s.queryClient.DeployerFeeShares(goCtx, request(nil, 0, 0, true)) + s.Require().NoError(err) + s.Require().Equal(len(contractAddressList), int(resp.Pagination.Total)) + s.Require().ElementsMatch(nullify.Fill(contractAddressList), nullify.Fill(resp.ContractAddresses)) + }) +} + +func (s *IntegrationTestSuite) TestWithdrawerFeeShares() { + s.SetupTest() + _, _, sender := testdata.KeyTestPubAddr() + _ = s.FundAccount(s.ctx, sender, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1_000_000)))) + + _, _, withdrawer := testdata.KeyTestPubAddr() + + var contractAddressList []string + var index uint64 + for index < 5 { + contractAddress := s.InstantiateContract(sender.String(), "") + contractAddressList = append(contractAddressList, contractAddress) + index++ + } + + // RegsisFeeShare + for _, contractAddress := range contractAddressList { + goCtx := sdk.WrapSDKContext(s.ctx) + msg := &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + } + + _, err := s.feeShareMsgServer.RegisterFeeShare(goCtx, msg) + s.Require().NoError(err) + } + + request := func(next []byte, offset, limit uint64, total bool) *types.QueryWithdrawerFeeSharesRequest { + return &types.QueryWithdrawerFeeSharesRequest{ + WithdrawerAddress: withdrawer.String(), + Pagination: &query.PageRequest{ + Key: next, + Offset: offset, + Limit: limit, + CountTotal: total, + }, + } + } + s.Run("ByOffset", func() { + step := 2 + goCtx := sdk.WrapSDKContext(s.ctx) + for i := 0; i < len(contractAddressList); i += step { + resp, err := s.queryClient.WithdrawerFeeShares(goCtx, request(nil, uint64(i), uint64(step), false)) + s.Require().NoError(err) + s.Require().LessOrEqual(len(resp.ContractAddresses), step) + s.Require().Subset(nullify.Fill(contractAddressList), nullify.Fill(resp.ContractAddresses)) + } + }) + s.Run("ByKey", func() { + step := 2 + var next []byte + goCtx := sdk.WrapSDKContext(s.ctx) + for i := 0; i < len(contractAddressList); i += step { + resp, err := s.queryClient.WithdrawerFeeShares(goCtx, request(next, 0, uint64(step), false)) + s.Require().NoError(err) + s.Require().LessOrEqual(len(resp.ContractAddresses), step) + s.Require().Subset(nullify.Fill(contractAddressList), nullify.Fill(resp.ContractAddresses)) + next = resp.Pagination.NextKey + } + }) + s.Run("Total", func() { + goCtx := sdk.WrapSDKContext(s.ctx) + resp, err := s.queryClient.WithdrawerFeeShares(goCtx, request(nil, 0, 0, true)) + s.Require().NoError(err) + s.Require().Equal(len(contractAddressList), int(resp.Pagination.Total)) + s.Require().ElementsMatch(nullify.Fill(contractAddressList), nullify.Fill(resp.ContractAddresses)) + }) +} diff --git a/x/feeshare/keeper/keeper.go b/x/feeshare/keeper/keeper.go new file mode 100644 index 0000000..04e3df6 --- /dev/null +++ b/x/feeshare/keeper/keeper.go @@ -0,0 +1,63 @@ +package keeper + +import ( + "fmt" + + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + + "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" + + revtypes "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +// Keeper of this module maintains collections of feeshares for contracts +// registered to receive transaction fees. +type Keeper struct { + storeKey storetypes.StoreKey + cdc codec.BinaryCodec + + bankKeeper revtypes.BankKeeper + wasmKeeper wasmkeeper.Keeper + accountKeeper revtypes.AccountKeeper + + feeCollectorName string + + // the address capable of executing a MsgUpdateParams message. Typically, this + // should be the x/gov module account. + authority string +} + +// NewKeeper creates new instances of the fees Keeper +func NewKeeper( + storeKey storetypes.StoreKey, + cdc codec.BinaryCodec, + bk revtypes.BankKeeper, + wk wasmkeeper.Keeper, + ak revtypes.AccountKeeper, + feeCollector string, + authority string, +) Keeper { + return Keeper{ + storeKey: storeKey, + cdc: cdc, + bankKeeper: bk, + wasmKeeper: wk, + accountKeeper: ak, + feeCollectorName: feeCollector, + authority: authority, + } +} + +// GetAuthority returns the x/feeshare module's authority. +func (k Keeper) GetAuthority() string { + return k.authority +} + +// Logger returns a module-specific logger. +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", revtypes.ModuleName)) +} diff --git a/x/feeshare/keeper/keeper_test.go b/x/feeshare/keeper/keeper_test.go new file mode 100644 index 0000000..9144caa --- /dev/null +++ b/x/feeshare/keeper/keeper_test.go @@ -0,0 +1,73 @@ +package keeper_test + +import ( + "testing" + "time" + + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + "github.com/stretchr/testify/suite" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + + "github.com/terpnetwork/terp-core/v2/app" + "github.com/terpnetwork/terp-core/v2/x/feeshare/keeper" + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +// BankKeeper defines the expected interface needed to retrieve account balances. +type BankKeeper interface { + MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + SendCoins(ctx sdk.Context, fromAddr, toAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error +} + +type IntegrationTestSuite struct { + suite.Suite + + ctx sdk.Context + app *app.TerpApp + bankKeeper BankKeeper + accountKeeper types.AccountKeeper + queryClient types.QueryClient + feeShareMsgServer types.MsgServer + wasmMsgServer wasmtypes.MsgServer +} + +func (s *IntegrationTestSuite) SetupTest() { + isCheckTx := false + s.app = app.Setup(s.T()) + + s.ctx = s.app.BaseApp.NewContext(isCheckTx, tmproto.Header{ + ChainID: "testing", + Height: 9, + Time: time.Now().UTC(), + }) + + queryHelper := baseapp.NewQueryServerTestHelper(s.ctx, s.app.InterfaceRegistry()) + types.RegisterQueryServer(queryHelper, keeper.NewQuerier(s.app.FeeShareKeeper)) + + s.queryClient = types.NewQueryClient(queryHelper) + s.bankKeeper = s.app.BankKeeper + s.accountKeeper = s.app.AccountKeeper + s.feeShareMsgServer = s.app.FeeShareKeeper + s.wasmMsgServer = wasmkeeper.NewMsgServerImpl(&s.app.WasmKeeper) +} + +func (s *IntegrationTestSuite) FundAccount(ctx sdk.Context, addr sdk.AccAddress, amounts sdk.Coins) error { + if err := s.bankKeeper.MintCoins(ctx, minttypes.ModuleName, amounts); err != nil { + return err + } + + return s.bankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, amounts) +} + +func TestKeeperTestSuite(t *testing.T) { + suite.Run(t, new(IntegrationTestSuite)) +} diff --git a/x/feeshare/keeper/migrator.go b/x/feeshare/keeper/migrator.go new file mode 100644 index 0000000..77b9e72 --- /dev/null +++ b/x/feeshare/keeper/migrator.go @@ -0,0 +1,29 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/exported" + v2 "github.com/terpnetwork/terp-core/v2/x/feeshare/migrations/v2" +) + +// Migrator is a struct for handling in-place state migrations. +type Migrator struct { + keeper Keeper + legacySubspace exported.Subspace +} + +func NewMigrator(k Keeper, ss exported.Subspace) Migrator { + return Migrator{ + keeper: k, + legacySubspace: ss, + } +} + +// Migrate1to2 migrates the x/feeshare module state from the consensus version 1 to +// version 2. Specifically, it takes the parameters that are currently stored +// and managed by the x/params modules and stores them directly into the x/feeshare +// module state. +func (m Migrator) Migrate1to2(ctx sdk.Context) error { + return v2.Migrate(ctx, ctx.KVStore(m.keeper.storeKey), m.legacySubspace, m.keeper.cdc) +} diff --git a/x/feeshare/keeper/msg_server.go b/x/feeshare/keeper/msg_server.go new file mode 100644 index 0000000..c5d8474 --- /dev/null +++ b/x/feeshare/keeper/msg_server.go @@ -0,0 +1,309 @@ +package keeper + +import ( + "context" + + wasmTypes "github.com/CosmWasm/wasmd/x/wasm/types" + + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +var _ types.MsgServer = &Keeper{} + +func (k Keeper) GetIfContractWasCreatedFromFactory(ctx sdk.Context, _ sdk.AccAddress, info *wasmTypes.ContractInfo) bool { + // This will allow ANYONE to register FeeShare funds to its own contract if it was created from a factory contract + // Note: if there is no admin but a creator made it, then the creator can register it how they wish + + govAddress := k.accountKeeper.GetModuleAddress(govtypes.ModuleName).String() + + creator, err := sdk.AccAddressFromBech32(info.Creator) + if err != nil { + return false + } + + // If the admin is the gov module (ex: some subDAOs, its a factory contract. Allow register to itself) + if info.Admin == govAddress { + return true + } + + isFactoryContract := false + if len(info.Admin) == 0 { + // if there is no admin & the creator is a contract, then its a factory contract + isFactoryContract = k.wasmKeeper.HasContractInfo(ctx, creator) + } else { + admin, err := sdk.AccAddressFromBech32(info.Admin) + if err != nil { + return false + } + // if there is an admin & the admin is a contract, then its a factory contract + isFactoryContract = k.wasmKeeper.HasContractInfo(ctx, admin) + } + + return isFactoryContract +} + +// GetContractAdminOrCreatorAddress ensures the deployer is the contract's admin OR creator if no admin is set for all msg_server feeshare functions. +func (k Keeper) GetContractAdminOrCreatorAddress(ctx sdk.Context, contract sdk.AccAddress, deployer string) (sdk.AccAddress, error) { + var controllingAccount sdk.AccAddress + + // Ensures deployer String is valid + _, err := sdk.AccAddressFromBech32(deployer) + if err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid deployer address %s", deployer) + } + + info := k.wasmKeeper.GetContractInfo(ctx, contract) + + if len(info.Admin) == 0 { + // no admin, see if they are the creator of the contract + if info.Creator != deployer { + return nil, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "you are not the creator of this contract %s", info.Creator) + } + + creatorAddr, err := sdk.AccAddressFromBech32(info.Creator) + if err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address %s", info.Creator) + } + controllingAccount = creatorAddr + } else { + // Admin is set, so we check if the deployer is the admin + if info.Admin != deployer { + return nil, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "you are not an admin of this contract %s", deployer) + } + + adminAddr, err := sdk.AccAddressFromBech32(info.Admin) + if err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid admin address %s", info.Admin) + } + controllingAccount = adminAddr + } + + return controllingAccount, nil +} + +// RegisterFeeShare registers a contract to receive transaction fees +func (k Keeper) RegisterFeeShare( + goCtx context.Context, + msg *types.MsgRegisterFeeShare, +) (*types.MsgRegisterFeeShareResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + params := k.GetParams(ctx) + if !params.EnableFeeShare { + return nil, types.ErrFeeShareDisabled + } + + // Get Contract + contract, err := sdk.AccAddressFromBech32(msg.ContractAddress) + if err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid contract address (%s)", err) + } + + // Check if contract is already registered + if k.IsFeeShareRegistered(ctx, contract) { + return nil, errorsmod.Wrapf(types.ErrFeeShareAlreadyRegistered, "contract is already registered %s", contract) + } + + // Get the withdraw address of the contract + withdrawer, err := sdk.AccAddressFromBech32(msg.WithdrawerAddress) + if err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid withdrawer address %s", msg.WithdrawerAddress) + } + + var deployer sdk.AccAddress + + if k.GetIfContractWasCreatedFromFactory(ctx, contract, k.wasmKeeper.GetContractInfo(ctx, contract)) { + // Anyone is allowed to register a contract to itself if it was created from a factory contract + if msg.WithdrawerAddress != msg.ContractAddress { + return nil, errorsmod.Wrapf(types.ErrFeeShareInvalidWithdrawer, "withdrawer address must be the same as the contract address if it is from a factory contract withdraw:%s contract:%s", msg.WithdrawerAddress, msg.ContractAddress) + } + + // set the deployer address to the contract address so it can self register + msg.DeployerAddress = msg.ContractAddress + deployer, err = sdk.AccAddressFromBech32(msg.DeployerAddress) + if err != nil { + return nil, err + } + } else { + // Check that the person who signed the message is the wasm contract admin or creator (if no admin) + deployer, err = k.GetContractAdminOrCreatorAddress(ctx, contract, msg.DeployerAddress) + if err != nil { + return nil, err + } + } + + // prevent storing the same address for deployer and withdrawer + feeshare := types.NewFeeShare(contract, deployer, withdrawer) + k.SetFeeShare(ctx, feeshare) + k.SetDeployerMap(ctx, deployer, contract) + k.SetWithdrawerMap(ctx, withdrawer, contract) + + k.Logger(ctx).Debug( + "registering contract for transaction fees", + "contract", msg.ContractAddress, + "deployer", msg.DeployerAddress, + "withdraw", msg.WithdrawerAddress, + ) + + ctx.EventManager().EmitEvents( + sdk.Events{ + sdk.NewEvent( + types.EventTypeRegisterFeeShare, + // sdk.NewAttribute(sdk.AttributeKeySender, msg.DeployerAddress), // SDK v47 + sdk.NewAttribute(types.AttributeKeyContract, msg.ContractAddress), + sdk.NewAttribute(types.AttributeKeyWithdrawerAddress, msg.WithdrawerAddress), + ), + }, + ) + + return &types.MsgRegisterFeeShareResponse{}, nil +} + +// UpdateFeeShare updates the withdraw address of a given FeeShare. If the given +// withdraw address is empty or the same as the deployer address, the withdraw +// address is removed. +func (k Keeper) UpdateFeeShare( + goCtx context.Context, + msg *types.MsgUpdateFeeShare, +) (*types.MsgUpdateFeeShareResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + params := k.GetParams(ctx) + if !params.EnableFeeShare { + return nil, types.ErrFeeShareDisabled + } + + contract, err := sdk.AccAddressFromBech32(msg.ContractAddress) + if err != nil { + return nil, errorsmod.Wrapf( + sdkerrors.ErrInvalidAddress, + "invalid contract address (%s)", err, + ) + } + + feeshare, found := k.GetFeeShare(ctx, contract) + if !found { + return nil, errorsmod.Wrapf( + types.ErrFeeShareContractNotRegistered, + "contract %s is not registered", msg.ContractAddress, + ) + } + + // feeshare with the given withdraw address is already registered + if msg.WithdrawerAddress == feeshare.WithdrawerAddress { + return nil, errorsmod.Wrapf(types.ErrFeeShareAlreadyRegistered, "feeshare with withdraw address %s is already registered", msg.WithdrawerAddress) + } + + // Check that the person who signed the message is the wasm contract admin, if so return the deployer address + _, err = k.GetContractAdminOrCreatorAddress(ctx, contract, msg.DeployerAddress) + if err != nil { + return nil, err + } + + withdrawAddr, err := sdk.AccAddressFromBech32(feeshare.WithdrawerAddress) + if err != nil { + return nil, errorsmod.Wrapf( + sdkerrors.ErrInvalidAddress, + "invalid withdrawer address (%s)", err, + ) + } + newWithdrawAddr, err := sdk.AccAddressFromBech32(msg.WithdrawerAddress) + if err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid WithdrawerAddress %s", msg.WithdrawerAddress) + } + + k.DeleteWithdrawerMap(ctx, withdrawAddr, contract) + k.SetWithdrawerMap(ctx, newWithdrawAddr, contract) + + // update feeshare + feeshare.WithdrawerAddress = newWithdrawAddr.String() + k.SetFeeShare(ctx, feeshare) + + ctx.EventManager().EmitEvents( + sdk.Events{ + sdk.NewEvent( + types.EventTypeUpdateFeeShare, + // sdk.NewAttribute(sdk.AttributeKeySender, msg.DeployerAddress), // SDK v47 + sdk.NewAttribute(types.AttributeKeyContract, msg.ContractAddress), + sdk.NewAttribute(types.AttributeKeyWithdrawerAddress, msg.WithdrawerAddress), + ), + }, + ) + + return &types.MsgUpdateFeeShareResponse{}, nil +} + +// CancelFeeShare deletes the FeeShare for a given contract +func (k Keeper) CancelFeeShare( + goCtx context.Context, + msg *types.MsgCancelFeeShare, +) (*types.MsgCancelFeeShareResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + params := k.GetParams(ctx) + if !params.EnableFeeShare { + return nil, types.ErrFeeShareDisabled + } + + contract, err := sdk.AccAddressFromBech32(msg.ContractAddress) + if err != nil { + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid contract address (%s)", err) + } + + fee, found := k.GetFeeShare(ctx, contract) + if !found { + return nil, errorsmod.Wrapf(types.ErrFeeShareContractNotRegistered, "contract %s is not registered", msg.ContractAddress) + } + + // Check that the person who signed the message is the wasm contract admin, if so return the deployer address + _, err = k.GetContractAdminOrCreatorAddress(ctx, contract, msg.DeployerAddress) + if err != nil { + return nil, err + } + + k.DeleteFeeShare(ctx, fee) + k.DeleteDeployerMap( + ctx, + fee.GetDeployerAddr(), + contract, + ) + + withdrawAddr := fee.GetWithdrawerAddr() + if withdrawAddr != nil { + k.DeleteWithdrawerMap( + ctx, + withdrawAddr, + contract, + ) + } + + ctx.EventManager().EmitEvents( + sdk.Events{ + sdk.NewEvent( + types.EventTypeCancelFeeShare, + // sdk.NewAttribute(sdk.AttributeKeySender, msg.DeployerAddress), // SDK v47 + sdk.NewAttribute(types.AttributeKeyContract, msg.ContractAddress), + ), + }, + ) + + return &types.MsgCancelFeeShareResponse{}, nil +} + +func (k Keeper) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if k.authority != req.Authority { + return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", k.authority, req.Authority) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + if err := k.SetParams(ctx, req.Params); err != nil { + return nil, err + } + + return &types.MsgUpdateParamsResponse{}, nil +} diff --git a/x/feeshare/keeper/msg_server_test.go b/x/feeshare/keeper/msg_server_test.go new file mode 100644 index 0000000..7fa8116 --- /dev/null +++ b/x/feeshare/keeper/msg_server_test.go @@ -0,0 +1,363 @@ +package keeper_test + +import ( + "crypto/sha256" + + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + + _ "embed" + + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +//go:embed testdata/reflect.wasm +var wasmContract []byte + +func (s *IntegrationTestSuite) StoreCode() { + _, _, sender := testdata.KeyTestPubAddr() + msg := wasmtypes.MsgStoreCodeFixture(func(m *wasmtypes.MsgStoreCode) { + m.WASMByteCode = wasmContract + m.Sender = sender.String() + }) + rsp, err := s.app.MsgServiceRouter().Handler(msg)(s.ctx, msg) + s.Require().NoError(err) + var result wasmtypes.MsgStoreCodeResponse + s.Require().NoError(s.app.AppCodec().Unmarshal(rsp.Data, &result)) + s.Require().Equal(uint64(1), result.CodeID) + expHash := sha256.Sum256(wasmContract) + s.Require().Equal(expHash[:], result.Checksum) + // and + info := s.app.WasmKeeper.GetCodeInfo(s.ctx, 1) + s.Require().NotNil(info) + s.Require().Equal(expHash[:], info.CodeHash) + s.Require().Equal(sender.String(), info.Creator) + s.Require().Equal(wasmtypes.DefaultParams().InstantiateDefaultPermission.With(sender), info.InstantiateConfig) +} + +func (s *IntegrationTestSuite) InstantiateContract(sender string, admin string) string { + msgStoreCode := wasmtypes.MsgStoreCodeFixture(func(m *wasmtypes.MsgStoreCode) { + m.WASMByteCode = wasmContract + m.Sender = sender + }) + _, err := s.app.MsgServiceRouter().Handler(msgStoreCode)(s.ctx, msgStoreCode) + s.Require().NoError(err) + + msgInstantiate := wasmtypes.MsgInstantiateContractFixture(func(m *wasmtypes.MsgInstantiateContract) { + m.Sender = sender + m.Admin = admin + m.Msg = []byte(`{}`) + }) + resp, err := s.app.MsgServiceRouter().Handler(msgInstantiate)(s.ctx, msgInstantiate) + s.Require().NoError(err) + var result wasmtypes.MsgInstantiateContractResponse + s.Require().NoError(s.app.AppCodec().Unmarshal(resp.Data, &result)) + contractInfo := s.app.WasmKeeper.GetContractInfo(s.ctx, sdk.MustAccAddressFromBech32(result.Address)) + s.Require().Equal(contractInfo.CodeID, uint64(1)) + s.Require().Equal(contractInfo.Admin, admin) + s.Require().Equal(contractInfo.Creator, sender) + + return result.Address +} + +func (s *IntegrationTestSuite) TestGetContractAdminOrCreatorAddress() { + _, _, sender := testdata.KeyTestPubAddr() + _, _, admin := testdata.KeyTestPubAddr() + _ = s.FundAccount(s.ctx, sender, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1_000_000)))) + _ = s.FundAccount(s.ctx, admin, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1_000_000)))) + + noAdminContractAddress := s.InstantiateContract(sender.String(), "") + withAdminContractAddress := s.InstantiateContract(sender.String(), admin.String()) + + for _, tc := range []struct { + desc string + contractAddress string + deployerAddress string + shouldErr bool + }{ + { + desc: "Success - Creator", + contractAddress: noAdminContractAddress, + deployerAddress: sender.String(), + shouldErr: false, + }, + { + desc: "Success - Admin", + contractAddress: withAdminContractAddress, + deployerAddress: admin.String(), + shouldErr: false, + }, + { + desc: "Error - Invalid deployer", + contractAddress: noAdminContractAddress, + deployerAddress: "Invalid", + shouldErr: true, + }, + } { + tc := tc + s.Run(tc.desc, func() { + if !tc.shouldErr { + _, err := s.app.FeeShareKeeper.GetContractAdminOrCreatorAddress(s.ctx, sdk.MustAccAddressFromBech32(tc.contractAddress), tc.deployerAddress) + s.Require().NoError(err) + } else { + _, err := s.app.FeeShareKeeper.GetContractAdminOrCreatorAddress(s.ctx, sdk.MustAccAddressFromBech32(tc.contractAddress), tc.deployerAddress) + s.Require().Error(err) + } + }) + } +} + +func (s *IntegrationTestSuite) TestRegisterFeeShare() { + _, _, sender := testdata.KeyTestPubAddr() + _ = s.FundAccount(s.ctx, sender, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1_000_000)))) + + contractAddress := s.InstantiateContract(sender.String(), "") + contractAddress2 := s.InstantiateContract(contractAddress, contractAddress) + + _, _, withdrawer := testdata.KeyTestPubAddr() + + for _, tc := range []struct { + desc string + msg *types.MsgRegisterFeeShare + resp *types.MsgRegisterFeeShareResponse + shouldErr bool + }{ + { + desc: "Invalid contract address", + msg: &types.MsgRegisterFeeShare{ + ContractAddress: "Invalid", + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + }, + resp: &types.MsgRegisterFeeShareResponse{}, + shouldErr: true, + }, + { + desc: "Invalid deployer address", + msg: &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: "Invalid", + WithdrawerAddress: withdrawer.String(), + }, + resp: &types.MsgRegisterFeeShareResponse{}, + shouldErr: true, + }, + { + desc: "Invalid withdrawer address", + msg: &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: "Invalid", + }, + resp: &types.MsgRegisterFeeShareResponse{}, + shouldErr: true, + }, + { + desc: "Success", + msg: &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + }, + resp: &types.MsgRegisterFeeShareResponse{}, + shouldErr: false, + }, + { + desc: "Invalid withdraw address for factory contract", + msg: &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress2, + DeployerAddress: sender.String(), + WithdrawerAddress: sender.String(), + }, + resp: &types.MsgRegisterFeeShareResponse{}, + shouldErr: true, + }, + { + desc: "Success register factory contract to itself", + msg: &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress2, + DeployerAddress: sender.String(), + WithdrawerAddress: contractAddress2, + }, + resp: &types.MsgRegisterFeeShareResponse{}, + shouldErr: false, + }, + } { + tc := tc + s.Run(tc.desc, func() { + goCtx := sdk.WrapSDKContext(s.ctx) + if !tc.shouldErr { + resp, err := s.feeShareMsgServer.RegisterFeeShare(goCtx, tc.msg) + s.Require().NoError(err) + s.Require().Equal(resp, tc.resp) + } else { + resp, err := s.feeShareMsgServer.RegisterFeeShare(goCtx, tc.msg) + s.Require().Error(err) + s.Require().Nil(resp) + } + }) + } +} + +func (s *IntegrationTestSuite) TestUpdateFeeShare() { + _, _, sender := testdata.KeyTestPubAddr() + _ = s.FundAccount(s.ctx, sender, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1_000_000)))) + + contractAddress := s.InstantiateContract(sender.String(), "") + _, _, withdrawer := testdata.KeyTestPubAddr() + + contractAddressNoRegisFeeShare := s.InstantiateContract(sender.String(), "") + s.Require().NotEqual(contractAddress, contractAddressNoRegisFeeShare) + + // RegsisFeeShare + goCtx := sdk.WrapSDKContext(s.ctx) + msg := &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + } + _, err := s.feeShareMsgServer.RegisterFeeShare(goCtx, msg) + s.Require().NoError(err) + _, _, newWithdrawer := testdata.KeyTestPubAddr() + s.Require().NotEqual(withdrawer, newWithdrawer) + + for _, tc := range []struct { + desc string + msg *types.MsgUpdateFeeShare + resp *types.MsgCancelFeeShareResponse + shouldErr bool + }{ + { + desc: "Invalid - contract not regis", + msg: &types.MsgUpdateFeeShare{ + ContractAddress: contractAddressNoRegisFeeShare, + DeployerAddress: sender.String(), + WithdrawerAddress: newWithdrawer.String(), + }, + resp: nil, + shouldErr: true, + }, + { + desc: "Invalid - Invalid DeployerAddress", + msg: &types.MsgUpdateFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: "Invalid", + WithdrawerAddress: newWithdrawer.String(), + }, + resp: nil, + shouldErr: true, + }, + { + desc: "Invalid - Invalid WithdrawerAddress", + msg: &types.MsgUpdateFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: "Invalid", + }, + resp: nil, + shouldErr: true, + }, + { + desc: "Invalid - Invalid WithdrawerAddress not change", + msg: &types.MsgUpdateFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + }, + resp: nil, + shouldErr: true, + }, + { + desc: "Success", + msg: &types.MsgUpdateFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: newWithdrawer.String(), + }, + resp: &types.MsgCancelFeeShareResponse{}, + shouldErr: false, + }, + } { + tc := tc + s.Run(tc.desc, func() { + goCtx := sdk.WrapSDKContext(s.ctx) + if !tc.shouldErr { + _, err := s.feeShareMsgServer.UpdateFeeShare(goCtx, tc.msg) + s.Require().NoError(err) + } else { + resp, err := s.feeShareMsgServer.UpdateFeeShare(goCtx, tc.msg) + s.Require().Error(err) + s.Require().Nil(resp) + } + }) + } +} + +func (s *IntegrationTestSuite) TestCancelFeeShare() { + _, _, sender := testdata.KeyTestPubAddr() + _ = s.FundAccount(s.ctx, sender, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1_000_000)))) + + contractAddress := s.InstantiateContract(sender.String(), "") + _, _, withdrawer := testdata.KeyTestPubAddr() + + // RegsisFeeShare + goCtx := sdk.WrapSDKContext(s.ctx) + msg := &types.MsgRegisterFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + WithdrawerAddress: withdrawer.String(), + } + _, err := s.feeShareMsgServer.RegisterFeeShare(goCtx, msg) + s.Require().NoError(err) + + for _, tc := range []struct { + desc string + msg *types.MsgCancelFeeShare + resp *types.MsgCancelFeeShareResponse + shouldErr bool + }{ + { + desc: "Invalid - contract Address", + msg: &types.MsgCancelFeeShare{ + ContractAddress: "Invalid", + DeployerAddress: sender.String(), + }, + resp: nil, + shouldErr: true, + }, + { + desc: "Invalid - deployer Address", + msg: &types.MsgCancelFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: "Invalid", + }, + resp: nil, + shouldErr: true, + }, + { + desc: "Success", + msg: &types.MsgCancelFeeShare{ + ContractAddress: contractAddress, + DeployerAddress: sender.String(), + }, + resp: &types.MsgCancelFeeShareResponse{}, + shouldErr: false, + }, + } { + tc := tc + s.Run(tc.desc, func() { + goCtx := sdk.WrapSDKContext(s.ctx) + if !tc.shouldErr { + resp, err := s.feeShareMsgServer.CancelFeeShare(goCtx, tc.msg) + s.Require().NoError(err) + s.Require().Equal(resp, tc.resp) + } else { + resp, err := s.feeShareMsgServer.CancelFeeShare(goCtx, tc.msg) + s.Require().Error(err) + s.Require().Equal(resp, tc.resp) + } + }) + } +} diff --git a/x/feeshare/keeper/params.go b/x/feeshare/keeper/params.go new file mode 100644 index 0000000..3b6f3c5 --- /dev/null +++ b/x/feeshare/keeper/params.go @@ -0,0 +1,32 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +// GetParams returns the total set of fees parameters. +func (k Keeper) GetParams(ctx sdk.Context) (p types.Params) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ParamsKey) + if bz == nil { + return p + } + + k.cdc.MustUnmarshal(bz, &p) + return p +} + +// SetParams sets the fees parameters to the param space. +func (k Keeper) SetParams(ctx sdk.Context, p types.Params) error { + if err := p.Validate(); err != nil { + return err + } + + store := ctx.KVStore(k.storeKey) + bz := k.cdc.MustMarshal(&p) + store.Set(types.ParamsKey, bz) + + return nil +} diff --git a/x/feeshare/keeper/testdata/reflect.wasm b/x/feeshare/keeper/testdata/reflect.wasm new file mode 100644 index 0000000..4122411 Binary files /dev/null and b/x/feeshare/keeper/testdata/reflect.wasm differ diff --git a/x/feeshare/migrations/v2/migrate.go b/x/feeshare/migrations/v2/migrate.go new file mode 100644 index 0000000..3aa51cc --- /dev/null +++ b/x/feeshare/migrations/v2/migrate.go @@ -0,0 +1,39 @@ +package v2 + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/exported" + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +const ( + ModuleName = "feeshare" +) + +// ParamsKey Feeshare/types/keys.go -> prefixParams +var ParamsKey = []byte{0x04} + +// Migrate migrates the x/feeshare module state from the consensus version 1 to +// version 2. Specifically, it takes the parameters that are currently stored +// and managed by the x/params modules and stores them directly into the x/feeshare +// module state. +func Migrate( + ctx sdk.Context, + store sdk.KVStore, + legacySubspace exported.Subspace, + cdc codec.BinaryCodec, +) error { + var currParams types.Params + legacySubspace.GetParamSet(ctx, &currParams) + + if err := currParams.Validate(); err != nil { + return err + } + + bz := cdc.MustMarshal(&currParams) + store.Set(ParamsKey, bz) + + return nil +} diff --git a/x/wasm/migrations/v2/store_test.go b/x/feeshare/migrations/v2/migrate_test.go similarity index 57% rename from x/wasm/migrations/v2/store_test.go rename to x/feeshare/migrations/v2/migrate_test.go index c5dcc7e..18095a4 100644 --- a/x/wasm/migrations/v2/store_test.go +++ b/x/feeshare/migrations/v2/migrate_test.go @@ -9,10 +9,10 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - "github.com/terpnetwork/terp-core/x/wasm" - "github.com/terpnetwork/terp-core/x/wasm/exported" - v2 "github.com/terpnetwork/terp-core/x/wasm/migrations/v2" - "github.com/terpnetwork/terp-core/x/wasm/types" + "github.com/terpnetwork/terp-core/v2/x/feeshare" + "github.com/terpnetwork/terp-core/v2/x/feeshare/exported" + v2 "github.com/terpnetwork/terp-core/v2/x/feeshare/migrations/v2" + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" ) type mockSubspace struct { @@ -23,22 +23,24 @@ func newMockSubspace(ps types.Params) mockSubspace { return mockSubspace{ps: ps} } -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { +func (ms mockSubspace) GetParamSet(_ sdk.Context, ps exported.ParamSet) { *ps.(*types.Params) = ms.ps } func TestMigrate(t *testing.T) { - cdc := moduletestutil.MakeTestEncodingConfig(wasm.AppModuleBasic{}).Codec - storeKey := sdk.NewKVStoreKey(types.StoreKey) + encCfg := moduletestutil.MakeTestEncodingConfig(feeshare.AppModuleBasic{}) + cdc := encCfg.Codec + + storeKey := sdk.NewKVStoreKey(v2.ModuleName) tKey := sdk.NewTransientStoreKey("transient_test") ctx := testutil.DefaultContext(storeKey, tKey) store := ctx.KVStore(storeKey) legacySubspace := newMockSubspace(types.DefaultParams()) - require.NoError(t, v2.MigrateStore(ctx, storeKey, legacySubspace, cdc)) + require.NoError(t, v2.Migrate(ctx, store, legacySubspace, cdc)) var res types.Params - bz := store.Get(types.ParamsKey) + bz := store.Get(v2.ParamsKey) require.NoError(t, cdc.Unmarshal(bz, &res)) require.Equal(t, legacySubspace.ps, res) } diff --git a/x/feeshare/module.go b/x/feeshare/module.go new file mode 100644 index 0000000..b9735a0 --- /dev/null +++ b/x/feeshare/module.go @@ -0,0 +1,203 @@ +package feeshare + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/gorilla/mux" + "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" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + + "github.com/terpnetwork/terp-core/v2/x/feeshare/client/cli" + "github.com/terpnetwork/terp-core/v2/x/feeshare/exported" + "github.com/terpnetwork/terp-core/v2/x/feeshare/keeper" + "github.com/terpnetwork/terp-core/v2/x/feeshare/types" +) + +// type check to ensure the interface is properly implemented +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModule{} +) + +// ConsensusVersion defines the current x/feeshare module consensus version. +const ConsensusVersion = 2 + +// AppModuleBasic type for the fees module +type AppModuleBasic struct{} + +// Name returns the fees module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec performs a no-op as the fees do not support Amino +// encoding. +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) +} + +// ConsensusVersion returns the consensus state-breaking version for the module. +func (AppModuleBasic) ConsensusVersion() uint64 { + return ConsensusVersion +} + +// RegisterInterfaces registers interfaces and implementations of the fees +// module. +func (AppModuleBasic) RegisterInterfaces(interfaceRegistry codectypes.InterfaceRegistry) { + types.RegisterInterfaces(interfaceRegistry) +} + +// DefaultGenesis returns default genesis state as raw bytes for the fees +// module. +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesisState()) +} + +// ValidateGenesis performs genesis state validation for the fees module. +func (b AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { + var genesisState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genesisState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return genesisState.Validate() +} + +// RegisterRESTRoutes performs a no-op as the fees module doesn't expose REST +// endpoints +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) {} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the fees +// module. +func (b AppModuleBasic) RegisterGRPCGatewayRoutes(c client.Context, serveMux *runtime.ServeMux) { + if err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(c)); err != nil { + panic(err) + } +} + +// GetTxCmd returns the root tx command for the fees module. +func (AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.NewTxCmd() +} + +// GetQueryCmd returns the fees module's root query command. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// ___________________________________________________________________________ + +// AppModule implements the AppModule interface for the fees module. +type AppModule struct { + AppModuleBasic + keeper keeper.Keeper + ak authkeeper.AccountKeeper + + // legacySubspace is used solely for migration of x/params managed parameters + legacySubspace exported.Subspace +} + +// NewAppModule creates a new AppModule Object +func NewAppModule( + k keeper.Keeper, + ak authkeeper.AccountKeeper, + ss exported.Subspace, +) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{}, + keeper: k, + ak: ak, + legacySubspace: ss, + } +} + +// Name returns the fees module's name. +func (AppModule) Name() string { + return types.ModuleName +} + +// RegisterInvariants registers the fees module's invariants. +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// NewHandler returns nil - fees module doesn't expose tx gRPC endpoints +func (am AppModule) NewHandler() sdk.Handler { + return nil +} + +// QuerierRoute returns the claim module's query routing key. +func (am AppModule) QuerierRoute() string { + return types.RouterKey +} + +// 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(), am.keeper) + types.RegisterQueryServer(cfg.QueryServer(), keeper.NewQuerier(am.keeper)) + + m := keeper.NewMigrator(am.keeper, am.legacySubspace) + if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { + panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err)) + } +} + +// BeginBlock executes all ABCI BeginBlock logic respective to the fees module. +func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { +} + +// EndBlock executes all ABCI EndBlock logic respective to the fee-share module. It +// returns no validator updates. +func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +// InitGenesis performs the fees module's genesis initialization. It returns +// no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState types.GenesisState + + cdc.MustUnmarshalJSON(data, &genesisState) + InitGenesis(ctx, am.keeper, genesisState) + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the fees module's exported genesis state as raw JSON bytes. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + gs := ExportGenesis(ctx, am.keeper) + return cdc.MustMarshalJSON(gs) +} + +// ___________________________________________________________________________ + +// AppModuleSimulation functions + +// GenerateGenesisState creates a randomized GenState of the fees module. +func (am AppModule) GenerateGenesisState(_ *module.SimulationState) { +} + +// ProposalContents returns content functions for governance proposals. +func (am AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalMsg { + return []simtypes.WeightedProposalMsg{} +} + +// RegisterStoreDecoder registers a decoder for fees module's types. +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) { +} + +// WeightedOperations returns fees module weighted operations +func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { + return []simtypes.WeightedOperation{} +} diff --git a/x/feeshare/spec/00_register.md b/x/feeshare/spec/00_register.md new file mode 100644 index 0000000..5865811 --- /dev/null +++ b/x/feeshare/spec/00_register.md @@ -0,0 +1,31 @@ +# Register a contract + +`terpd tx feeshare register [contract_bech32] [withdraw_bech32] --from [key]` + +Registers the withdrawal address for the given contract. + +## Parameters + +`contract_bech32 (string, required)`: The bech32 address of the contract whose interaction fees will be shared. + +`withdraw_bech32 (string, required)`: The bech32 address where the interaction fees will be sent every block. + +## Description + +This command registers the withdrawal address for the given contract. Any time a user interacts with your contract, the funds will be sent to the withdrawal address. It can be any valid address, such as a DAO, normal account, another contract, or a multi-sig. + +## Permissions + +This command can only be run by the admin of the contract. If there is no admin, then it can only be run by the contract creator. + +## Exceptions + +```text +withdraw_bech32 can not be the community pool (distribution) address. This is a limitation of the way the SDK handles this module account +``` + +```text +For contracts created or administered by a contract factory, the withdrawal address can only be the same as the contract address. This can be registered by anyone, but it's unchangeable. This is helpful for SubDAOs or public goods to save fees in the treasury. + +If you create a contract like this, it's best to create an execution method for withdrawing fees to an account. To do this, you'll need to save the withdrawal address in the contract's state before uploading a non-migratable contract. +``` diff --git a/x/feeshare/spec/00_update.md b/x/feeshare/spec/00_update.md new file mode 100644 index 0000000..d9d6b60 --- /dev/null +++ b/x/feeshare/spec/00_update.md @@ -0,0 +1,11 @@ +# Update a Contract's Withdrawal Address + +This can be changed at any time so long as you are still the admin or creator of a contract with the command: + +`terpd tx feeshare update [contract] [new_withdraw_address]` + +## Update Exception + +```text +This can not be done if the contract was created from or is administered by another contract (a contract factory). There is not currently a way for a contract to change its own withdrawal address directly. +``` diff --git a/x/feeshare/spec/01_concepts.md b/x/feeshare/spec/01_concepts.md new file mode 100644 index 0000000..bc48af7 --- /dev/null +++ b/x/feeshare/spec/01_concepts.md @@ -0,0 +1,27 @@ + + +# Concepts + +## FeeShare + +The FeeShare module is a revenue-per-transaction model, which allows developers to get paid for deploying their decentralized applications (dApps) on Terp Network. This helps developers to generate revenue every time a user interacts with their contracts on the chain. This registration is permissionless to sign up for and begin earning fees from. By default, 50% of all transaction fees for Execute Messages are shared. This can be changed by governance and implemented by the `x/feeshare` module. + +## Registration + +Developers register their contract applications to gain their cut of fees per execution. Any contract can be registered by a developer by submitting a signed transaction. After the transaction is executed successfully, the developer will start receiving a portion of the transaction fees paid when a user interacts with the registered contract. The developer can have the funds sent to their wallet, a DAO, or any other wallet address on the Terp network. + +::: tip + **NOTE**: If your contract is part of a development project, please ensure that the deployer of the contract (or the factory/DAO that deployed the contract) is an account that is owned by that project. This avoids the situation, that an individual deployer who leaves your project could become malicious. +::: + +## Fee Distribution + +As described above, developers will earn a portion of the transaction fee after registering their contracts. To understand how transaction fees are distributed, we will look at the following in detail: + +* The transactions eligible are only [Wasm Execute Txs](https://github.com/CosmWasm/wasmd/blob/main/proto/cosmwasm/wasm/v1/tx.proto#L115-L127) (`MsgExecuteContract`). + +### WASM Transaction Fees + +Users pay transaction fees to pay to interact with smart contracts on Terp. When a transaction is executed, the entire fee amount (`gas limit * gas price`) is sent to the `FeeCollector` module account during the [Cosmos SDK AnteHandler](https://docs.cosmos.network/main/modules/auth/#antehandlers) execution. After this step, the `FeeCollector` sends 50% of the funds and splits them between contracts that were executed on the transaction. If the fees paid are not accepted by governance, there is no payout to the developers (for example, niche base tokens) for tax purposes. If a user sends a message and it does not interact with any contracts (ex: bankSend), then the entire fee is sent to the `FeeCollector` as expected. diff --git a/x/feeshare/spec/02_state.md b/x/feeshare/spec/02_state.md new file mode 100644 index 0000000..e8edbc7 --- /dev/null +++ b/x/feeshare/spec/02_state.md @@ -0,0 +1,59 @@ + + +# State + +## State Objects + +The `x/feeshare` module keeps the following objects in the state: + +| State Object | Description | Key | Value | Store | +| :-------------------- | :------------------------------------ | :---------------------------------------------------------------- | :----------------- | :---- | +| `FeeShare` | Fee split bytecode | `[]byte{1} + []byte(contract_address)` | `[]byte{feeshare}` | KV | +| `DeployerFeeShares` | Contract by deployer address bytecode | `[]byte{2} + []byte(deployer_address) + []byte(contract_address)` | `[]byte{1}` | KV | +| `WithdrawerFeeShares` | Contract by withdraw address bytecode | `[]byte{3} + []byte(withdraw_address) + []byte(contract_address)` | `[]byte{1}` | KV | + +### FeeShare + +A FeeShare defines an instance that organizes fee distribution conditions for +the owner of a given smart contract + +```go +type FeeShare struct { + // contract_address is the bech32 address of a registered contract in string form + ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` + // deployer_address is the bech32 address of message sender. It must be the + // same as the contracts admin address. + DeployerAddress string `protobuf:"bytes,2,opt,name=deployer_address,json=deployerAddress,proto3" json:"deployer_address,omitempty"` + // withdrawer_address is the bech32 address of account receiving the + // transaction fees. + WithdrawerAddress string `protobuf:"bytes,3,opt,name=withdrawer_address,json=withdrawerAddress,proto3" json:"withdrawer_address,omitempty"` +} +``` + +### ContractAddress + +`ContractAddress` defines the contract address that has been registered for fee distribution. + +### DeployerAddress + +A `DeployerAddress` is the admin address for a registered contract. + +### WithdrawerAddress + +The `WithdrawerAddress` is the address that receives transaction fees for a registered contract. + +## Genesis State + +The `x/feeshare` module's `GenesisState` defines the state necessary for initializing the chain from a previously exported height. It contains the module parameters and the fee share for registered contracts: + +```go +// GenesisState defines the module's genesis state. +type GenesisState struct { + // module parameters + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + // active registered contracts for fee distribution + FeeShares []FeeShare `protobuf:"bytes,2,rep,name=feeshares,json=feeshares,proto3" json:"feeshares"` +} +``` diff --git a/x/feeshare/spec/03_state_transitions.md b/x/feeshare/spec/03_state_transitions.md new file mode 100644 index 0000000..998b4b5 --- /dev/null +++ b/x/feeshare/spec/03_state_transitions.md @@ -0,0 +1,49 @@ + + +# State Transitions + +The `x/feeshare` module allows for three types of state transitions: `RegisterFeeShare`, `UpdateFeeShare` and `CancelFeeShare`. The logic for distributing transaction fees is handled through the [Ante handler](/app/ante.go). + +## Register Fee Share + +A developer registers a contract for receiving transaction fees by defining the contract address and the withdrawal address for fees to be paid too. If this is not set, the developer can not get income from the contract. This is opt-in for tax purposes. When registering for fees to be paid, you MUST be the admin of said wasm contract. The withdrawal address can be the same as the contract's address if you so choose. + +1. User submits a `RegisterFeeShare` to register a contract address, along with a withdrawal address that they would like to receive the fees to +2. Check if the following conditions pass: + 1. `x/feeshare` module is enabled via Governance + 2. the contract was not previously registered + 3. deployer has a valid account (it has done at least one transaction) + 4. the contract address exists + 5. the deployer signing the transaction is the admin of the contract + 6. the contract is already deployed +3. Store an instance of the provided share. + +All transactions sent to the registered contract occurring after registration will have their fees distributed to the developer, according to the global `DeveloperShares` parameter in governance. + +### Update Fee Split + +A developer updates the withdraw address for a registered contract, defining the contract address and the new withdraw address. + +1. The user submits a `UpdateFeeShare` +2. Check if the following conditions pass: + 1. `x/feeshare` module is enabled + 2. the contract is registered + 3. the signer of the transaction is the same as the contract admin per the WasmVM +3. Update the fee with the new withdrawal address. + +After this update, the developer receives the fees on the new withdrawal address. + +### Cancel Fee Split + +A developer cancels receiving fees for a registered contract, defining the contract address. + +1. The user submits a `CancelFeeShare` +2. Check if the following conditions pass: + 1. `x/feeshare` module is enabled + 2. the contract is registered + 3. the signer of the transaction is the same as the contract admin per the WasmVM +3. Remove share from storage + +The developer no longer receives fees from transactions sent to this contract. All fees go to the community. diff --git a/x/feeshare/spec/04_transactions.md b/x/feeshare/spec/04_transactions.md new file mode 100644 index 0000000..b0981d5 --- /dev/null +++ b/x/feeshare/spec/04_transactions.md @@ -0,0 +1,73 @@ + + +# Transactions + +This section defines the `sdk.Msg` concrete types that result in the state transitions defined on the previous section. + +## `MsgRegisterFeeShare` + +Defines a transaction signed by a developer to register a contract for transaction fee distribution. The sender must be an EOA that corresponds to the contract deployer address. + +```go +type MsgRegisterFeeShare struct { + // contract_address in bech32 format + ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` + // deployer_address is the bech32 address of message sender. It must be the + // same the contract's admin address + DeployerAddress string `protobuf:"bytes,2,opt,name=deployer_address,json=deployerAddress,proto3" json:"deployer_address,omitempty"` + // withdrawer_address is the bech32 address of account receiving the + // transaction fees + WithdrawerAddress string `protobuf:"bytes,3,opt,name=withdrawer_address,json=withdrawerAddress,proto3" json:"withdrawer_address,omitempty"` +} +``` + +The message content stateless validation fails if: + +- Contract bech32 address is invalid +- Deployer bech32 address is invalid +- Withdraw bech32 address is invalid + +### `MsgUpdateFeeShare` + +Defines a transaction signed by a developer to update the withdraw address of a contract registered for transaction fee distribution. The sender must be the admin of the contract. + +```go +type MsgUpdateFeeShare struct { + // contract_address in bech32 format + ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` + // deployer_address is the bech32 address of message sender. It must be the + // same the contract's admin address + DeployerAddress string `protobuf:"bytes,2,opt,name=deployer_address,json=deployerAddress,proto3" json:"deployer_address,omitempty"` + // withdrawer_address is the bech32 address of account receiving the + // transaction fees + WithdrawerAddress string `protobuf:"bytes,3,opt,name=withdrawer_address,json=withdrawerAddress,proto3" json:"withdrawer_address,omitempty"` +} +``` + +The message content stateless validation fails if: + +- Contract bech32 address is invalid +- Deployer bech32 address is invalid +- Withdraw bech32 address is invalid + +### `MsgCancelFeeShare` + +Defines a transaction signed by a developer to remove the information for a registered contract. Transaction fees will no longer be distributed to the developer for this smart contract. The sender must be an admin that corresponds to the contract. + +```go +type MsgCancelFeeShare struct { + // contract_address in bech32 format + ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` + // deployer_address is the bech32 address of message sender. It must be the + // same the contract's admin address + DeployerAddress string `protobuf:"bytes,2,opt,name=deployer_address,json=deployerAddress,proto3" json:"deployer_address,omitempty"` +} +``` + +The message content stateless validation fails if: + +- Contract bech32 address is invalid +- Contract bech32 address is zero +- Deployer bech32 address is invalid diff --git a/x/feeshare/spec/05_ante.md b/x/feeshare/spec/05_ante.md new file mode 100644 index 0000000..24c5a72 --- /dev/null +++ b/x/feeshare/spec/05_ante.md @@ -0,0 +1,25 @@ + + +# Ante + +The fees module uses the ante handler to distribute fees between developers and the community. + +## Handling + +An [Ante Decorator](/x/feeshare/ante/ante.go) executes custom logic after each successful WasmExecuteMsg transaction. All fees paid by a user for transaction execution are sent to the `FeeCollector` module account during the `AnteHandler` execution before being redistributed to the registered contract developers. + +If the `x/feeshare` module is disabled or the Wasm Execute Msg transaction targets an unregistered contract, the handler returns `nil`, without performing any actions. In this case, 100% of the transaction fees remain in the `FeeCollector` module, to be distributed elsewhere. + +If the `x/feeshare` module is enabled and a Wasm Execute Msg transaction targets a registered contract, the handler sends a percentage of the transaction fees (paid by the user) to the withdraw address set for that contract. + +1. The user submits an Execute transaction (`MsgExecuteContract`) to a smart contract and the transaction is executed successfully +2. Check if + * fees module is enabled + * the smart contract is registered to receive fee split +3. Calculate developer fees according to the `DeveloperShares` parameter. +4. Check what fees governance allows to be paid in +5. Check which contracts the user executed that also have been registered. +6. Calculate the total amount of fees to be paid to the developer(s). If multiple, split the 50% between all registered withdrawal addresses. +7. Distribute the remaining amount in the `FeeCollector` to validators according to the [SDK Distribution Scheme](https://docs.cosmos.network/main/modules/distribution/03_begin_block.html#the-distribution-scheme). diff --git a/x/feeshare/spec/06_events.md b/x/feeshare/spec/06_events.md new file mode 100644 index 0000000..dedf981 --- /dev/null +++ b/x/feeshare/spec/06_events.md @@ -0,0 +1,30 @@ + + +# Events + +The `x/feeshare` module emits the following events: + +## Register Fee Split + +| Type | Attribute Key | Attribute Value | +| :------------------- | :--------------------- | :------------------------ | +| `register_feeshare` | `"contract"` | `{msg.ContractAddress}` | +| `register_feeshare` | `"sender"` | `{msg.DeployerAddress}` | +| `register_feeshare` | `"withdrawer_address"` | `{msg.WithdrawerAddress}` | + +## Update Fee Split + +| Type | Attribute Key | Attribute Value | +| :----------------- | :--------------------- | :------------------------ | +| `update_feeshare` | `"contract"` | `{msg.ContractAddress}` | +| `update_feeshare` | `"sender"` | `{msg.DeployerAddress}` | +| `update_feeshare` | `"withdrawer_address"` | `{msg.WithdrawerAddress}` | + +## Cancel Fee Split + +| Type | Attribute Key | Attribute Value | +| :----------------- | :------------ | :---------------------- | +| `cancel_feeshare` | `"contract"` | `{msg.ContractAddress}` | +| `cancel_feeshare` | `"sender"` | `{msg.DeployerAddress}` | diff --git a/x/feeshare/spec/07_parameters.md b/x/feeshare/spec/07_parameters.md new file mode 100644 index 0000000..4694460 --- /dev/null +++ b/x/feeshare/spec/07_parameters.md @@ -0,0 +1,25 @@ + + +# Parameters + +The fee Split module contains the following parameters: + +| Key | Type | Default Value | +| :------------------------- | :---------- | :--------------- | +| `EnableFeeShare` | bool | `true` | +| `DeveloperShares` | sdk.Dec | `50%` | +| `AllowedDenoms` | []string{} | `[]string(nil)` | + +## Enable FeeShare Module + +The `EnableFeeShare` parameter toggles all state transitions in the module. When the parameter is disabled, it will prevent any transaction fees from being distributed to contract deplorers and it will disallow contract registrations, updates or cancellations. + +### Developer Shares Amount + +The `DeveloperShares` parameter is the percentage of transaction fees that are sent to the contract deplorers. + +### Allowed Denominations + +The `AllowedDenoms` parameter is used to specify which fees coins will be paid to contract developers. If this is empty, all fees paid will be split. If not, only fees specified here will be paid out to the withdrawal address. diff --git a/x/feeshare/spec/08_clients.md b/x/feeshare/spec/08_clients.md new file mode 100644 index 0000000..77db360 --- /dev/null +++ b/x/feeshare/spec/08_clients.md @@ -0,0 +1,57 @@ + + +# Clients + +## Command Line Interface + +Find below a list of `terpd` commands added with the `x/feeshare` module. You can obtain the full list by using the `terpd -h` command. A CLI command can look like this: + +```bash +terpd query feeshare params +``` + +### Queries + +| Command | Subcommand | Description | +| :----------------- | :--------------------- | :--------------------------------------- | +| `query` `feeshare` | `params` | Get feeshare params | +| `query` `feeshare` | `contract` | Get the feeshare for a given contract | +| `query` `feeshare` | `contracts` | Get all feeshares | +| `query` `feeshare` | `deployer-contracts` | Get all feeshares of a given deployer | +| `query` `feeshare` | `withdrawer-contracts` | Get all feeshares of a given withdrawer | + +### Transactions + +| Command | Subcommand | Description | +| :-------------- | :--------- | :----------------------------------------- | +| `tx` `feeshare` | `register` | Register a contract for receiving feeshare | +| `tx` `feeshare` | `update` | Update the withdraw address for a contract | +| `tx` `feeshare` | `cancel` | Remove the feeshare for a contract | + +## gRPC Queries + +| Verb | Method | Description | +| :----- | :------------------------------------------------ | :--------------------------------------- | +| `gRPC` | `terp.feeshare.v1.Query/Params` | Get feeshare params | +| `gRPC` | `terp.feeshare.v1.Query/FeeShare` | Get the feeshare for a given contract | +| `gRPC` | `terp.feeshare.v1.Query/FeeShares` | Get all feeshares | +| `gRPC` | `terp.feeshare.v1.Query/DeployerFeeShares` | Get all feeshares of a given deployer | +| `gRPC` | `terp.feeshare.v1.Query/WithdrawerFeeShares` | Get all feeshares of a given withdrawer | +| `GET` | `/terp/feeshare/v1/params` | Get feeshare params | +| `GET` | `/terp/feeshare/v1/feeshares/{contract_address}` | Get the feeshare for a given contract | +| `GET` | `/terp/feeshare/v1/feeshares` | Get all feeshares | +| `GET` | `/terp/feeshare/v1/feeshares/{deployer_address}` | Get all feeshares of a given deployer | +| `GET` | `/terp/feeshare/v1/feeshares/{withdraw_address}` | Get all feeshares of a given withdrawer | + +### gRPC Transactions + +| Verb | Method | Description | +| :----- | :----------------------------------------- | :----------------------------------------- | +| `gRPC` | `terp.feeshare.v1.Msg/RegisterFeeShare` | Register a contract for receiving feeshare | +| `gRPC` | `terp.feeshare.v1.Msg/UpdateFeeShare` | Update the withdraw address for a contract | +| `gRPC` | `terp.feeshare.v1.Msg/CancelFeeShare` | Remove the feeshare for a contract | +| `POST` | `/terp/feeshare/v1/tx/register_feeshare` | Register a contract for receiving feeshare | +| `POST` | `/terp/feeshare/v1/tx/update_feeshare` | Update the withdraw address for a contract | +| `POST` | `/terp/feeshare/v1/tx/cancel_feeshare` | Remove the feeshare for a contract | diff --git a/x/feeshare/spec/README.md b/x/feeshare/spec/README.md new file mode 100644 index 0000000..a8f0ee2 --- /dev/null +++ b/x/feeshare/spec/README.md @@ -0,0 +1,25 @@ + + +# `feeshare` + +## Abstract + +This document specifies the internal `x/feeshare` module of Terp network. + +The `x/feeshare` module enables the Terp to support splitting transaction fees between the community and smart contract deployer. This aims to increase the adoption of Terp by offering a new way of income for CosmWasm smart contract developers. Developers can register their smart contracts and every time someone interacts with a registered smart contract, the contract deployer or their assigned withdrawal account receives a part of the transaction fees. + +## Contents + +1. **[Concepts](01_concepts.md)** +2. **[State](02_state.md)** +3. **[State Transitions](03_state_transitions.md)** +4. **[Transactions](04_transactions.md)** +5. **[Hooks](05_hooks.md)** +6. **[Events](06_events.md)** +7. **[Parameters](07_parameters.md)** +8. **[Clients](08_clients.md)** diff --git a/x/feeshare/types/codec.go b/x/feeshare/types/codec.go new file mode 100644 index 0000000..57b85fb --- /dev/null +++ b/x/feeshare/types/codec.go @@ -0,0 +1,66 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" +) + +var ( + amino = codec.NewLegacyAmino() + + // ModuleCdc references the global erc20 module codec. Note, the codec should + // ONLY be used in certain instances of tests and for JSON encoding. + // + // The actual codec used for serialization should be provided to modules/erc20 and + // defined at the application level. + ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) + + // AminoCdc is a amino codec created to support amino JSON compatible msgs. + AminoCdc = codec.NewAminoCodec(amino) +) + +const ( + // Amino names + cancelFeeShareName = "terp/MsgCancelFeeShare" + registerFeeShareName = "terp/MsgRegisterFeeShare" + updateFeeShareName = "terp/MsgUpdateFeeShare" + updateFeeShareParams = "terp/MsgUpdateParams" +) + +// NOTE: This is required for the GetSignBytes function +func init() { + RegisterLegacyAminoCodec(amino) + + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec + // so that this can later be used to properly serialize MsgGrant and MsgExec + // instances. + RegisterLegacyAminoCodec(authzcodec.Amino) +} + +// RegisterInterfaces register implementations +func RegisterInterfaces(registry codectypes.InterfaceRegistry) { + registry.RegisterImplementations( + (*sdk.Msg)(nil), + &MsgRegisterFeeShare{}, + &MsgCancelFeeShare{}, + &MsgUpdateFeeShare{}, + &MsgUpdateParams{}, + ) + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} + +// RegisterLegacyAminoCodec registers the necessary x/FeeShare interfaces and +// concrete types on the provided LegacyAmino codec. These types are used for +// Amino JSON serialization and EIP-712 compatibility. +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(&MsgCancelFeeShare{}, cancelFeeShareName, nil) + cdc.RegisterConcrete(&MsgRegisterFeeShare{}, registerFeeShareName, nil) + cdc.RegisterConcrete(&MsgUpdateFeeShare{}, updateFeeShareName, nil) + cdc.RegisterConcrete(&MsgUpdateParams{}, updateFeeShareParams, nil) +} diff --git a/x/feeshare/types/codec_test.go b/x/feeshare/types/codec_test.go new file mode 100644 index 0000000..effdaea --- /dev/null +++ b/x/feeshare/types/codec_test.go @@ -0,0 +1,33 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/suite" + + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type CodecTestSuite struct { + suite.Suite +} + +func TestCodecSuite(t *testing.T) { + suite.Run(t, new(CodecTestSuite)) +} + +func (suite *CodecTestSuite) TestRegisterInterfaces() { + registry := codectypes.NewInterfaceRegistry() + registry.RegisterInterface(sdk.MsgInterfaceProtoName, (*sdk.Msg)(nil)) + RegisterInterfaces(registry) + + impls := registry.ListImplementations(sdk.MsgInterfaceProtoName) + suite.Require().Equal(4, len(impls)) + suite.Require().ElementsMatch([]string{ + "/terp.feeshare.v1.MsgRegisterFeeShare", + "/terp.feeshare.v1.MsgCancelFeeShare", + "/terp.feeshare.v1.MsgUpdateFeeShare", + "/terp.feeshare.v1.MsgUpdateParams", + }, impls) +} diff --git a/x/feeshare/types/errors.go b/x/feeshare/types/errors.go new file mode 100644 index 0000000..231c855 --- /dev/null +++ b/x/feeshare/types/errors.go @@ -0,0 +1,15 @@ +package types + +import ( + errorsmod "cosmossdk.io/errors" +) + +// errors +var ( + ErrFeeShareDisabled = errorsmod.Register(ModuleName, 1, "feeshare module is disabled by governance") + ErrFeeShareAlreadyRegistered = errorsmod.Register(ModuleName, 2, "feeshare already exists for given contract") + ErrFeeShareNoContractDeployed = errorsmod.Register(ModuleName, 3, "no contract deployed") + ErrFeeShareContractNotRegistered = errorsmod.Register(ModuleName, 4, "no feeshare registered for contract") + ErrFeeSharePayment = errorsmod.Register(ModuleName, 5, "feeshare payment error") + ErrFeeShareInvalidWithdrawer = errorsmod.Register(ModuleName, 6, "invalid withdrawer address") +) diff --git a/x/feeshare/types/events.go b/x/feeshare/types/events.go new file mode 100644 index 0000000..a21a760 --- /dev/null +++ b/x/feeshare/types/events.go @@ -0,0 +1,11 @@ +package types + +// feeshare events +const ( + EventTypeRegisterFeeShare = "register_feeshare" + EventTypeCancelFeeShare = "cancel_feeshare" + EventTypeUpdateFeeShare = "update_feeshare" + + AttributeKeyContract = "contract" + AttributeKeyWithdrawerAddress = "withdrawer_address" +) diff --git a/x/feeshare/types/expected_keepers.go b/x/feeshare/types/expected_keepers.go new file mode 100644 index 0000000..1592cf2 --- /dev/null +++ b/x/feeshare/types/expected_keepers.go @@ -0,0 +1,32 @@ +package types + +import ( + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types" + + // "github.com/cosmos/cosmos-sdk/client" + sdk "github.com/cosmos/cosmos-sdk/types" + acctypes "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// AccountKeeper defines the expected interface needed to retrieve account info. +type AccountKeeper interface { + GetModuleAddress(moduleName string) sdk.AccAddress + GetModuleAccount(ctx sdk.Context, name string) acctypes.ModuleAccountI + + HasAccount(ctx sdk.Context, addr sdk.AccAddress) bool + GetAccount(ctx sdk.Context, addr sdk.AccAddress) (account acctypes.AccountI) +} + +// BankKeeper defines the expected interface needed to retrieve account balances. +type BankKeeper interface { + SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin + GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins +} + +// WasmKeeper defines the expected interface needed to retrieve cosmwasm contracts. +type WasmKeeper interface { + GetContractInfo(ctx sdk.Context, contractAddr sdk.AccAddress) (wasmtypes.ContractInfo, error) +} diff --git a/x/feeshare/types/feeshare.go b/x/feeshare/types/feeshare.go new file mode 100644 index 0000000..97e6a1e --- /dev/null +++ b/x/feeshare/types/feeshare.go @@ -0,0 +1,66 @@ +package types + +import ( + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerror "github.com/cosmos/cosmos-sdk/types/errors" +) + +// NewFeeShare returns an instance of FeeShare. +func NewFeeShare(contract sdk.Address, deployer, withdrawer sdk.AccAddress) FeeShare { + return FeeShare{ + ContractAddress: contract.String(), + DeployerAddress: deployer.String(), + WithdrawerAddress: withdrawer.String(), + } +} + +// GetContractAddr returns the contract address +func (fs FeeShare) GetContractAddr() sdk.Address { + contract, err := sdk.AccAddressFromBech32(fs.ContractAddress) + if err != nil { + return nil + } + return contract +} + +// GetDeployerAddr returns the contract deployer address +func (fs FeeShare) GetDeployerAddr() sdk.AccAddress { + contract, err := sdk.AccAddressFromBech32(fs.DeployerAddress) + if err != nil { + return nil + } + return contract +} + +// GetWithdrawerAddr returns the account address to where the funds proceeding +// from the fees will be received. +func (fs FeeShare) GetWithdrawerAddr() sdk.AccAddress { + contract, err := sdk.AccAddressFromBech32(fs.WithdrawerAddress) + if err != nil { + return nil + } + return contract +} + +// Validate performs a stateless validation of a FeeShare +func (fs FeeShare) Validate() error { + if _, err := sdk.AccAddressFromBech32(fs.ContractAddress); err != nil { + return err + } + + if _, err := sdk.AccAddressFromBech32(fs.DeployerAddress); err != nil { + return err + } + + if fs.WithdrawerAddress == "" { + return errorsmod.Wrap(sdkerror.ErrInvalidAddress, "withdrawer address cannot be empty") + } + + if _, err := sdk.AccAddressFromBech32(fs.WithdrawerAddress); err != nil { + return err + } + + return nil +} diff --git a/x/feeshare/types/feeshare.pb.go b/x/feeshare/types/feeshare.pb.go new file mode 100644 index 0000000..5182b93 --- /dev/null +++ b/x/feeshare/types/feeshare.pb.go @@ -0,0 +1,428 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: terp/feeshare/v1/feeshare.proto + +package types + +import ( + fmt "fmt" + 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 + +// FeeShare defines an instance that organizes fee distribution conditions for +// the owner of a given smart contract +type FeeShare struct { + // contract_address is the bech32 address of a registered contract in string + // form + ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` + // deployer_address is the bech32 address of message sender. It must be the + // same as the contracts admin address. + DeployerAddress string `protobuf:"bytes,2,opt,name=deployer_address,json=deployerAddress,proto3" json:"deployer_address,omitempty"` + // withdrawer_address is the bech32 address of account receiving the + // transaction fees. + WithdrawerAddress string `protobuf:"bytes,3,opt,name=withdrawer_address,json=withdrawerAddress,proto3" json:"withdrawer_address,omitempty"` +} + +func (m *FeeShare) Reset() { *m = FeeShare{} } +func (m *FeeShare) String() string { return proto.CompactTextString(m) } +func (*FeeShare) ProtoMessage() {} +func (*FeeShare) Descriptor() ([]byte, []int) { + return fileDescriptor_3fd5d33ef9423a38, []int{0} +} +func (m *FeeShare) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *FeeShare) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_FeeShare.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 *FeeShare) XXX_Merge(src proto.Message) { + xxx_messageInfo_FeeShare.Merge(m, src) +} +func (m *FeeShare) XXX_Size() int { + return m.Size() +} +func (m *FeeShare) XXX_DiscardUnknown() { + xxx_messageInfo_FeeShare.DiscardUnknown(m) +} + +var xxx_messageInfo_FeeShare proto.InternalMessageInfo + +func (m *FeeShare) GetContractAddress() string { + if m != nil { + return m.ContractAddress + } + return "" +} + +func (m *FeeShare) GetDeployerAddress() string { + if m != nil { + return m.DeployerAddress + } + return "" +} + +func (m *FeeShare) GetWithdrawerAddress() string { + if m != nil { + return m.WithdrawerAddress + } + return "" +} + +func init() { + proto.RegisterType((*FeeShare)(nil), "terp.feeshare.v1.FeeShare") +} + +func init() { proto.RegisterFile("terp/feeshare/v1/feeshare.proto", fileDescriptor_3fd5d33ef9423a38) } + +var fileDescriptor_3fd5d33ef9423a38 = []byte{ + // 213 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x2f, 0x49, 0x2d, 0x2a, + 0xd0, 0x4f, 0x4b, 0x4d, 0x2d, 0xce, 0x48, 0x2c, 0x4a, 0xd5, 0x2f, 0x33, 0x84, 0xb3, 0xf5, 0x0a, + 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x04, 0x40, 0x0a, 0xf4, 0xe0, 0x82, 0x65, 0x86, 0x4a, 0xfd, 0x8c, + 0x5c, 0x1c, 0x6e, 0xa9, 0xa9, 0xc1, 0x20, 0xbe, 0x90, 0x26, 0x97, 0x40, 0x72, 0x7e, 0x5e, 0x49, + 0x51, 0x62, 0x72, 0x49, 0x7c, 0x62, 0x4a, 0x4a, 0x51, 0x6a, 0x71, 0xb1, 0x04, 0xa3, 0x02, 0xa3, + 0x06, 0x67, 0x10, 0x3f, 0x4c, 0xdc, 0x11, 0x22, 0x0c, 0x52, 0x9a, 0x92, 0x5a, 0x90, 0x93, 0x5f, + 0x99, 0x5a, 0x04, 0x57, 0xca, 0x04, 0x51, 0x0a, 0x13, 0x87, 0x29, 0xd5, 0xe5, 0x12, 0x2a, 0xcf, + 0x2c, 0xc9, 0x48, 0x29, 0x4a, 0x2c, 0x47, 0x52, 0xcc, 0x0c, 0x56, 0x2c, 0x88, 0x90, 0x81, 0x2a, + 0x77, 0xf2, 0x3e, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, + 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xc3, 0xf4, 0xcc, + 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x90, 0x47, 0xf2, 0x52, 0x4b, 0xca, 0xf3, + 0x8b, 0xb2, 0xc1, 0x6c, 0xdd, 0xe4, 0xfc, 0xa2, 0x54, 0xfd, 0x0a, 0x84, 0xe7, 0x4b, 0x2a, 0x0b, + 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0xfe, 0x36, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x68, 0x11, 0x65, + 0x11, 0x1a, 0x01, 0x00, 0x00, +} + +func (m *FeeShare) 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 *FeeShare) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *FeeShare) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.WithdrawerAddress) > 0 { + i -= len(m.WithdrawerAddress) + copy(dAtA[i:], m.WithdrawerAddress) + i = encodeVarintFeeshare(dAtA, i, uint64(len(m.WithdrawerAddress))) + i-- + dAtA[i] = 0x1a + } + if len(m.DeployerAddress) > 0 { + i -= len(m.DeployerAddress) + copy(dAtA[i:], m.DeployerAddress) + i = encodeVarintFeeshare(dAtA, i, uint64(len(m.DeployerAddress))) + i-- + dAtA[i] = 0x12 + } + if len(m.ContractAddress) > 0 { + i -= len(m.ContractAddress) + copy(dAtA[i:], m.ContractAddress) + i = encodeVarintFeeshare(dAtA, i, uint64(len(m.ContractAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintFeeshare(dAtA []byte, offset int, v uint64) int { + offset -= sovFeeshare(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *FeeShare) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ContractAddress) + if l > 0 { + n += 1 + l + sovFeeshare(uint64(l)) + } + l = len(m.DeployerAddress) + if l > 0 { + n += 1 + l + sovFeeshare(uint64(l)) + } + l = len(m.WithdrawerAddress) + if l > 0 { + n += 1 + l + sovFeeshare(uint64(l)) + } + return n +} + +func sovFeeshare(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozFeeshare(x uint64) (n int) { + return sovFeeshare(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *FeeShare) 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 ErrIntOverflowFeeshare + } + 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: FeeShare: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: FeeShare: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeshare + } + 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 ErrInvalidLengthFeeshare + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeshare + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ContractAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DeployerAddress", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeshare + } + 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 ErrInvalidLengthFeeshare + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeshare + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DeployerAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WithdrawerAddress", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowFeeshare + } + 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 ErrInvalidLengthFeeshare + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthFeeshare + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.WithdrawerAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipFeeshare(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthFeeshare + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipFeeshare(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, ErrIntOverflowFeeshare + } + 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, ErrIntOverflowFeeshare + } + 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, ErrIntOverflowFeeshare + } + 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, ErrInvalidLengthFeeshare + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupFeeshare + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthFeeshare + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthFeeshare = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowFeeshare = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupFeeshare = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/feeshare/types/feeshare_test.go b/x/feeshare/types/feeshare_test.go new file mode 100644 index 0000000..8b20566 --- /dev/null +++ b/x/feeshare/types/feeshare_test.go @@ -0,0 +1,146 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/suite" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type FeeShareTestSuite struct { + suite.Suite + address1 sdk.AccAddress + address2 sdk.AccAddress + contract sdk.AccAddress +} + +func TestFeeShareSuite(t *testing.T) { + suite.Run(t, new(FeeShareTestSuite)) +} + +func (suite *FeeShareTestSuite) SetupTest() { + suite.address1 = sdk.AccAddress([]byte("cosmos1")) + suite.address2 = sdk.AccAddress([]byte("cosmos2")) + + suite.contract = sdk.AccAddress([]byte("cosmos1contract")) +} + +func (suite *FeeShareTestSuite) TestFeeNew() { + testCases := []struct { + name string + contract sdk.Address + deployer sdk.AccAddress + withdraw sdk.AccAddress + expectPass bool + }{ + { + "Create feeshare- pass", + suite.contract, + suite.address1, + suite.address2, + true, + }, + { + "Create feeshare- invalid contract address", + sdk.AccAddress{}, + suite.address1, + suite.address2, + false, + }, + { + "Create feeshare- invalid deployer address", + suite.contract, + sdk.AccAddress{}, + suite.address2, + false, + }, + } + + for _, tc := range testCases { + i := NewFeeShare(tc.contract, tc.deployer, tc.withdraw) + err := i.Validate() + + if tc.expectPass { + suite.Require().NoError(err, tc.name) + } else { + suite.Require().Error(err, tc.name) + } + } +} + +func (suite *FeeShareTestSuite) TestFee() { + testCases := []struct { + msg string + feeshare FeeShare + expectPass bool + }{ + { + "Create feeshare- pass", + FeeShare{ + suite.contract.String(), + suite.address1.String(), + suite.address2.String(), + }, + true, + }, + { + "Create feeshare- invalid contract address (invalid length 2)", + FeeShare{ + "terp15u3dt79t6sxxa3x3kpkhzsy56edaa5a66kxmukqjz2sx0hes5sn38g", + suite.address1.String(), + suite.address2.String(), + }, + false, + }, + { + "Create feeshare- invalid deployer address", + FeeShare{ + suite.contract.String(), + "terp1hj5fveer5cjtn4wd6wstzugjfdxzl0xppxm7xs", + suite.address2.String(), + }, + false, + }, + { + "Create feeshare- invalid withdraw address", + FeeShare{ + suite.contract.String(), + suite.address1.String(), + "terp1hj5fveer5cjtn4wd6wstzugjfdxzl0xppxm7xs", + }, + false, + }, + } + + for _, tc := range testCases { + err := tc.feeshare.Validate() + + if tc.expectPass { + suite.Require().NoError(err, tc.msg) + } else { + suite.Require().Error(err, tc.msg) + } + } +} + +func (suite *FeeShareTestSuite) TestFeeShareGetters() { + contract := sdk.AccAddress([]byte("cosmos1contract")) + fs := FeeShare{ + contract.String(), + suite.address1.String(), + suite.address2.String(), + } + suite.Equal(fs.GetContractAddr(), contract) + suite.Equal(fs.GetDeployerAddr(), suite.address1) + suite.Equal(fs.GetWithdrawerAddr(), suite.address2) + + fs = FeeShare{ + contract.String(), + suite.address1.String(), + "", + } + suite.Equal(fs.GetContractAddr(), contract) + suite.Equal(fs.GetDeployerAddr(), suite.address1) + suite.Equal(len(fs.GetWithdrawerAddr()), 0) +} diff --git a/x/feeshare/types/genesis.go b/x/feeshare/types/genesis.go new file mode 100644 index 0000000..459183b --- /dev/null +++ b/x/feeshare/types/genesis.go @@ -0,0 +1,39 @@ +package types + +import "fmt" + +// NewGenesisState creates a new genesis state. +func NewGenesisState(params Params, feeshare []FeeShare) GenesisState { + return GenesisState{ + Params: params, + FeeShare: feeshare, + } +} + +// DefaultGenesisState sets default evm genesis state with empty accounts and +// default params and chain config values. +func DefaultGenesisState() *GenesisState { + return &GenesisState{ + Params: DefaultParams(), + } +} + +// Validate performs basic genesis state validation returning an error upon any +// failure. +func (gs GenesisState) Validate() error { + seenContract := make(map[string]bool) + for _, fs := range gs.FeeShare { + // only one fee per contract + if seenContract[fs.ContractAddress] { + return fmt.Errorf("contract duplicated on genesis '%s'", fs.ContractAddress) + } + + if err := fs.Validate(); err != nil { + return err + } + + seenContract[fs.ContractAddress] = true + } + + return gs.Params.Validate() +} diff --git a/x/feeshare/types/genesis.pb.go b/x/feeshare/types/genesis.pb.go new file mode 100644 index 0000000..753938b --- /dev/null +++ b/x/feeshare/types/genesis.pb.go @@ -0,0 +1,665 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: terp/feeshare/v1/genesis.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 + +// GenesisState defines the module's genesis state. +type GenesisState struct { + // params are the feeshare module parameters + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + // FeeShare is a slice of active registered contracts for fee distribution + FeeShare []FeeShare `protobuf:"bytes,2,rep,name=fee_share,json=feeShare,proto3" json:"fee_share"` +} + +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_7f942c377ec7c32d, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func (m *GenesisState) GetFeeShare() []FeeShare { + if m != nil { + return m.FeeShare + } + return nil +} + +// Params defines the feeshare module params +type Params struct { + // enable_feeshare defines a parameter to enable the feeshare module + EnableFeeShare bool `protobuf:"varint,1,opt,name=enable_fee_share,json=enableFeeShare,proto3" json:"enable_fee_share,omitempty"` + // developer_shares defines the proportion of the transaction fees to be + // distributed to the registered contract owner + DeveloperShares github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,2,opt,name=developer_shares,json=developerShares,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"developer_shares"` + // allowed_denoms defines the list of denoms that are allowed to be paid to + // the contract withdraw addresses. If said denom is not in the list, the fees + // will ONLY be sent to the community pool. + // If this list is empty, all denoms are allowed. + AllowedDenoms []string `protobuf:"bytes,3,rep,name=allowed_denoms,json=allowedDenoms,proto3" json:"allowed_denoms,omitempty"` +} + +func (m *Params) Reset() { *m = Params{} } +func (m *Params) String() string { return proto.CompactTextString(m) } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_7f942c377ec7c32d, []int{1} +} +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) GetEnableFeeShare() bool { + if m != nil { + return m.EnableFeeShare + } + return false +} + +func (m *Params) GetAllowedDenoms() []string { + if m != nil { + return m.AllowedDenoms + } + return nil +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "terp.feeshare.v1.GenesisState") + proto.RegisterType((*Params)(nil), "terp.feeshare.v1.Params") +} + +func init() { proto.RegisterFile("terp/feeshare/v1/genesis.proto", fileDescriptor_7f942c377ec7c32d) } + +var fileDescriptor_7f942c377ec7c32d = []byte{ + // 348 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x64, 0x91, 0xb1, 0x4e, 0xc2, 0x40, + 0x1c, 0xc6, 0x7b, 0x60, 0x08, 0x1c, 0x8a, 0xa4, 0x71, 0x68, 0x18, 0x4a, 0x43, 0xa2, 0xe9, 0xc2, + 0x5d, 0xc0, 0xc4, 0xcd, 0x85, 0x10, 0x1d, 0x5c, 0x4c, 0x99, 0x74, 0x21, 0xa5, 0xfd, 0x53, 0x08, + 0x6d, 0xaf, 0xb9, 0x3b, 0x41, 0x1f, 0xc0, 0xdd, 0x87, 0xf1, 0x21, 0x18, 0x19, 0x8d, 0x03, 0x31, + 0xf0, 0x22, 0xa6, 0xd7, 0x02, 0x46, 0xa6, 0x7e, 0xfd, 0xbe, 0xff, 0xf7, 0xbb, 0xcb, 0xfd, 0xb1, + 0x29, 0x81, 0x27, 0x74, 0x0c, 0x20, 0x26, 0x2e, 0x07, 0x3a, 0xef, 0xd0, 0x00, 0x62, 0x10, 0x53, + 0x41, 0x12, 0xce, 0x24, 0xd3, 0xeb, 0x69, 0x4e, 0x76, 0x39, 0x99, 0x77, 0x1a, 0xcd, 0xa3, 0xc6, + 0x3e, 0x55, 0x95, 0xc6, 0x45, 0xc0, 0x02, 0xa6, 0x24, 0x4d, 0x55, 0xe6, 0xb6, 0xde, 0x11, 0x3e, + 0xbd, 0xcf, 0xd0, 0x03, 0xe9, 0x4a, 0xd0, 0x6f, 0x70, 0x29, 0x71, 0xb9, 0x1b, 0x09, 0x03, 0x59, + 0xc8, 0xae, 0x76, 0x0d, 0xf2, 0xff, 0x28, 0xf2, 0xa8, 0xf2, 0xde, 0xc9, 0x72, 0xdd, 0xd4, 0x9c, + 0x7c, 0x5a, 0xbf, 0xc5, 0x95, 0x31, 0xc0, 0x50, 0x0d, 0x19, 0x05, 0xab, 0x68, 0x57, 0xbb, 0x8d, + 0xe3, 0xea, 0x1d, 0xc0, 0x20, 0xd5, 0x79, 0xb9, 0x3c, 0xce, 0xff, 0x5b, 0x9f, 0x08, 0x97, 0x32, + 0xae, 0x6e, 0xe3, 0x3a, 0xc4, 0xee, 0x28, 0x84, 0xe1, 0x01, 0x98, 0xde, 0xa5, 0xec, 0xd4, 0x32, + 0x7f, 0x07, 0xd1, 0x9f, 0x70, 0xdd, 0x87, 0x39, 0x84, 0x2c, 0x01, 0x9e, 0x0d, 0x0a, 0xa3, 0x60, + 0x21, 0xbb, 0xd2, 0x23, 0x29, 0xfe, 0x7b, 0xdd, 0xbc, 0x0a, 0xa6, 0x72, 0xf2, 0x32, 0x22, 0x1e, + 0x8b, 0xa8, 0xc7, 0x44, 0xc4, 0x44, 0xfe, 0x69, 0x0b, 0x7f, 0x46, 0xe5, 0x5b, 0x02, 0x82, 0xf4, + 0xc1, 0x73, 0xce, 0xf7, 0x1c, 0x45, 0x16, 0xfa, 0x25, 0xae, 0xb9, 0x61, 0xc8, 0x16, 0xe0, 0x0f, + 0x7d, 0x88, 0x59, 0x24, 0x8c, 0xa2, 0x55, 0xb4, 0x2b, 0xce, 0x59, 0xee, 0xf6, 0x95, 0xd9, 0x7b, + 0x58, 0x6e, 0x4c, 0xb4, 0xda, 0x98, 0xe8, 0x67, 0x63, 0xa2, 0x8f, 0xad, 0xa9, 0xad, 0xb6, 0xa6, + 0xf6, 0xb5, 0x35, 0xb5, 0xe7, 0xce, 0x9f, 0x93, 0xd3, 0x67, 0x88, 0x41, 0x2e, 0x18, 0x9f, 0x29, + 0xdd, 0xf6, 0x18, 0x07, 0xfa, 0x7a, 0xd8, 0x96, 0xba, 0xc8, 0xa8, 0xa4, 0x56, 0x72, 0xfd, 0x1b, + 0x00, 0x00, 0xff, 0xff, 0xfe, 0x14, 0xac, 0xac, 0xfd, 0x01, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.FeeShare) > 0 { + for iNdEx := len(m.FeeShare) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.FeeShare[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *Params) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.AllowedDenoms) > 0 { + for iNdEx := len(m.AllowedDenoms) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.AllowedDenoms[iNdEx]) + copy(dAtA[i:], m.AllowedDenoms[iNdEx]) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.AllowedDenoms[iNdEx]))) + i-- + dAtA[i] = 0x1a + } + } + { + size := m.DeveloperShares.Size() + i -= size + if _, err := m.DeveloperShares.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if m.EnableFeeShare { + i-- + if m.EnableFeeShare { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovGenesis(uint64(l)) + if len(m.FeeShare) > 0 { + for _, e := range m.FeeShare { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.EnableFeeShare { + n += 2 + } + l = m.DeveloperShares.Size() + n += 1 + l + sovGenesis(uint64(l)) + if len(m.AllowedDenoms) > 0 { + for _, s := range m.AllowedDenoms { + l = len(s) + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FeeShare", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.FeeShare = append(m.FeeShare, FeeShare{}) + if err := m.FeeShare[len(m.FeeShare)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (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 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: 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 EnableFeeShare", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.EnableFeeShare = bool(v != 0) + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DeveloperShares", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.DeveloperShares.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AllowedDenoms", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AllowedDenoms = append(m.AllowedDenoms, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func 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/feeshare/types/genesis_test.go b/x/feeshare/types/genesis_test.go new file mode 100644 index 0000000..a6297b1 --- /dev/null +++ b/x/feeshare/types/genesis_test.go @@ -0,0 +1,138 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/suite" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type GenesisTestSuite struct { + suite.Suite + address1 string + address2 string + contractA string + contractB string +} + +func TestGenesisTestSuite(t *testing.T) { + suite.Run(t, new(GenesisTestSuite)) +} + +func (suite *GenesisTestSuite) SetupTest() { + suite.address1 = sdk.AccAddress([]byte("cosmos1")).String() + suite.address2 = sdk.AccAddress([]byte("cosmos2")).String() + + suite.contractA = "cosmos15u3dt79t6sxxa3x3kpkhzsy56edaa5a66wvt3kxmukqjz2sx0hesh45zsv" + suite.contractB = "cosmos168ctmpyppk90d34p3jjy658zf5a5l3w8wk35wht6ccqj4mr0yv8skhnwe8" +} + +func (suite *GenesisTestSuite) TestValidateGenesis() { + newGen := NewGenesisState(DefaultParams(), []FeeShare{}) + testCases := []struct { + name string + genState *GenesisState + expPass bool + }{ + { + name: "valid genesis constructor", + genState: &newGen, + expPass: true, + }, + { + name: "default", + genState: DefaultGenesisState(), + expPass: true, + }, + { + name: "valid genesis", + genState: &GenesisState{ + Params: DefaultParams(), + FeeShare: []FeeShare{}, + }, + expPass: true, + }, + { + name: "valid genesis - with fee", + genState: &GenesisState{ + Params: DefaultParams(), + FeeShare: []FeeShare{ + { + ContractAddress: suite.contractA, + DeployerAddress: suite.address1, + WithdrawerAddress: suite.address1, + }, + { + ContractAddress: suite.contractB, + DeployerAddress: suite.address2, + WithdrawerAddress: suite.address2, + }, + }, + }, + expPass: true, + }, + { + name: "empty genesis", + genState: &GenesisState{}, + expPass: false, + }, + { + name: "invalid genesis - duplicated fee", + genState: &GenesisState{ + Params: DefaultParams(), + FeeShare: []FeeShare{ + { + ContractAddress: suite.contractA, + DeployerAddress: suite.address1, + }, + { + ContractAddress: suite.contractA, + DeployerAddress: suite.address1, + }, + }, + }, + expPass: false, + }, + { + name: "invalid genesis - duplicated fee with different deployer address", + genState: &GenesisState{ + Params: DefaultParams(), + FeeShare: []FeeShare{ + { + ContractAddress: suite.contractA, + DeployerAddress: suite.address1, + }, + { + ContractAddress: suite.contractA, + DeployerAddress: suite.address2, + }, + }, + }, + expPass: false, + }, + { + name: "invalid genesis - invalid withdrawer address", + genState: &GenesisState{ + Params: DefaultParams(), + FeeShare: []FeeShare{ + { + ContractAddress: suite.contractA, + DeployerAddress: suite.address1, + WithdrawerAddress: "withdraw", + }, + }, + }, + expPass: false, + }, + } + + for _, tc := range testCases { + err := tc.genState.Validate() + if tc.expPass { + suite.Require().NoError(err, tc.name) + } else { + suite.Require().Error(err, tc.name) + } + } +} diff --git a/x/feeshare/types/keys.go b/x/feeshare/types/keys.go new file mode 100644 index 0000000..a844483 --- /dev/null +++ b/x/feeshare/types/keys.go @@ -0,0 +1,43 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// constants +const ( + // module name + ModuleName = "feeshare" + + // StoreKey to be used when creating the KVStore + StoreKey = ModuleName + + // RouterKey to be used for message routing + RouterKey = ModuleName +) + +// prefix bytes for the fees persistent store +const ( + prefixFeeShare = iota + 1 + prefixDeployer + prefixWithdrawer + prefixParams +) + +// KVStore key prefixes +var ( + KeyPrefixFeeShare = []byte{prefixFeeShare} + KeyPrefixDeployer = []byte{prefixDeployer} + KeyPrefixWithdrawer = []byte{prefixWithdrawer} + ParamsKey = []byte{prefixParams} +) + +// GetKeyPrefixDeployer returns the KVStore key prefix for storing +// registered feeshare contract for a deployer +func GetKeyPrefixDeployer(deployerAddress sdk.AccAddress) []byte { + return append(KeyPrefixDeployer, deployerAddress.Bytes()...) +} + +// GetKeyPrefixWithdrawer returns the KVStore key prefix for storing +// registered feeshare contract for a withdrawer +func GetKeyPrefixWithdrawer(withdrawerAddress sdk.AccAddress) []byte { + return append(KeyPrefixWithdrawer, withdrawerAddress.Bytes()...) +} diff --git a/x/feeshare/types/msg.go b/x/feeshare/types/msg.go new file mode 100644 index 0000000..ab2da10 --- /dev/null +++ b/x/feeshare/types/msg.go @@ -0,0 +1,183 @@ +package types + +import ( + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var ( + _ sdk.Msg = &MsgRegisterFeeShare{} + _ sdk.Msg = &MsgCancelFeeShare{} + _ sdk.Msg = &MsgUpdateFeeShare{} +) + +const ( + TypeMsgRegisterFeeShare = "register_feeshare" + TypeMsgCancelFeeShare = "cancel_feeshare" + TypeMsgUpdateFeeShare = "update_feeshare" +) + +// NewMsgRegisterFeeShare creates new instance of MsgRegisterFeeShare +func NewMsgRegisterFeeShare( + contract sdk.Address, + deployer, + withdrawer sdk.AccAddress, +) *MsgRegisterFeeShare { + withdrawerAddress := "" + if withdrawer != nil { + withdrawerAddress = withdrawer.String() + } + + return &MsgRegisterFeeShare{ + ContractAddress: contract.String(), + DeployerAddress: deployer.String(), + WithdrawerAddress: withdrawerAddress, + } +} + +// Route returns the name of the module +func (msg MsgRegisterFeeShare) Route() string { return RouterKey } + +// Type returns the the action +func (msg MsgRegisterFeeShare) Type() string { return TypeMsgRegisterFeeShare } + +// ValidateBasic runs stateless checks on the message +func (msg MsgRegisterFeeShare) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(msg.DeployerAddress); err != nil { + return errorsmod.Wrapf(err, "invalid deployer address %s", msg.DeployerAddress) + } + + if _, err := sdk.AccAddressFromBech32(msg.ContractAddress); err != nil { + return errorsmod.Wrapf(err, "invalid contract address %s", msg.ContractAddress) + } + + if msg.WithdrawerAddress != "" { + if _, err := sdk.AccAddressFromBech32(msg.WithdrawerAddress); err != nil { + return errorsmod.Wrapf(err, "invalid withdraw address %s", msg.WithdrawerAddress) + } + } + + return nil +} + +// GetSignBytes encodes the message for signing +func (msg *MsgRegisterFeeShare) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(msg)) +} + +// GetSigners defines whose signature is required +func (msg MsgRegisterFeeShare) GetSigners() []sdk.AccAddress { + from, _ := sdk.AccAddressFromBech32(msg.DeployerAddress) + return []sdk.AccAddress{from} +} + +// NewMsgCancelFeeShare creates new instance of MsgCancelFeeShare. +func NewMsgCancelFeeShare( + contract sdk.Address, + deployer sdk.AccAddress, +) *MsgCancelFeeShare { + return &MsgCancelFeeShare{ + ContractAddress: contract.String(), + DeployerAddress: deployer.String(), + } +} + +// Route returns the message route for a MsgCancelFeeShare. +func (msg MsgCancelFeeShare) Route() string { return RouterKey } + +// Type returns the message type for a MsgCancelFeeShare. +func (msg MsgCancelFeeShare) Type() string { return TypeMsgCancelFeeShare } + +// ValidateBasic runs stateless checks on the message +func (msg MsgCancelFeeShare) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(msg.DeployerAddress); err != nil { + return errorsmod.Wrapf(err, "invalid deployer address %s", msg.DeployerAddress) + } + + if _, err := sdk.AccAddressFromBech32(msg.ContractAddress); err != nil { + return errorsmod.Wrapf(err, "invalid deployer address %s", msg.DeployerAddress) + } + + return nil +} + +// GetSignBytes encodes the message for signing +func (msg *MsgCancelFeeShare) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(msg)) +} + +// GetSigners defines whose signature is required +func (msg MsgCancelFeeShare) GetSigners() []sdk.AccAddress { + funder, _ := sdk.AccAddressFromBech32(msg.DeployerAddress) + return []sdk.AccAddress{funder} +} + +// NewMsgUpdateFeeShare creates new instance of MsgUpdateFeeShare +func NewMsgUpdateFeeShare( + contract sdk.Address, + deployer, + withdraw sdk.AccAddress, +) *MsgUpdateFeeShare { + return &MsgUpdateFeeShare{ + ContractAddress: contract.String(), + DeployerAddress: deployer.String(), + WithdrawerAddress: withdraw.String(), + } +} + +// Route returns the name of the module +func (msg MsgUpdateFeeShare) Route() string { return RouterKey } + +// Type returns the the action +func (msg MsgUpdateFeeShare) Type() string { return TypeMsgUpdateFeeShare } + +// ValidateBasic runs stateless checks on the message +func (msg MsgUpdateFeeShare) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(msg.DeployerAddress); err != nil { + return errorsmod.Wrapf(err, "invalid deployer address %s", msg.DeployerAddress) + } + + if _, err := sdk.AccAddressFromBech32(msg.ContractAddress); err != nil { + return errorsmod.Wrapf(err, "invalid contract address %s", msg.ContractAddress) + } + + if _, err := sdk.AccAddressFromBech32(msg.WithdrawerAddress); err != nil { + return errorsmod.Wrapf(err, "invalid withdraw address %s", msg.WithdrawerAddress) + } + + return nil +} + +// GetSignBytes encodes the message for signing +func (msg *MsgUpdateFeeShare) GetSignBytes() []byte { + return sdk.MustSortJSON(AminoCdc.MustMarshalJSON(msg)) +} + +// GetSigners defines whose signature is required +func (msg MsgUpdateFeeShare) GetSigners() []sdk.AccAddress { + from, _ := sdk.AccAddressFromBech32(msg.DeployerAddress) + return []sdk.AccAddress{from} +} + +var _ sdk.Msg = &MsgUpdateParams{} + +// GetSignBytes implements the LegacyMsg interface. +func (m MsgUpdateParams) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +// GetSigners returns the expected signers for a MsgUpdateParams message. +func (m *MsgUpdateParams) GetSigners() []sdk.AccAddress { + addr, _ := sdk.AccAddressFromBech32(m.Authority) + return []sdk.AccAddress{addr} +} + +// ValidateBasic does a sanity check on the provided data. +func (m *MsgUpdateParams) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { + return errorsmod.Wrap(err, "invalid authority address") + } + + return m.Params.Validate() +} diff --git a/x/feeshare/types/msg_test.go b/x/feeshare/types/msg_test.go new file mode 100644 index 0000000..9a597c3 --- /dev/null +++ b/x/feeshare/types/msg_test.go @@ -0,0 +1,223 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/suite" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type MsgsTestSuite struct { + suite.Suite + contract sdk.AccAddress + deployer sdk.AccAddress + deployerStr string + withdrawerStr string +} + +func TestMsgsTestSuite(t *testing.T) { + suite.Run(t, new(MsgsTestSuite)) +} + +func (suite *MsgsTestSuite) SetupTest() { + deployer := "cosmos1" + withdraw := "cosmos2" + suite.contract = sdk.AccAddress([]byte("terp15u3dt79t6sxxa3x3kpkhzsy56edaa5a66wvt3kxmukqjz2sx0hes5zcavm")) + suite.deployer = sdk.AccAddress([]byte(deployer)) + suite.deployerStr = suite.deployer.String() + suite.withdrawerStr = sdk.AccAddress([]byte(withdraw)).String() +} + +func (suite *MsgsTestSuite) TestMsgRegisterFeeShareGetters() { + msgInvalid := MsgRegisterFeeShare{} + msg := NewMsgRegisterFeeShare( + suite.contract, + suite.deployer, + suite.deployer, + ) + suite.Require().Equal(RouterKey, msg.Route()) + suite.Require().Equal(TypeMsgRegisterFeeShare, msg.Type()) + suite.Require().NotNil(msgInvalid.GetSignBytes()) + suite.Require().NotNil(msg.GetSigners()) +} + +func (suite *MsgsTestSuite) TestMsgRegisterFeeShareNew() { + testCases := []struct { + msg string + contract string + deployer string + withdraw string + expectPass bool + }{ + { + "pass", + suite.contract.String(), + suite.deployerStr, + suite.withdrawerStr, + true, + }, + { + "pass - empty withdrawer address", + suite.contract.String(), + suite.deployerStr, + "", + true, + }, + { + "pass - same withdrawer and deployer address", + suite.contract.String(), + suite.deployerStr, + suite.deployerStr, + true, + }, + { + "invalid contract address", + "", + suite.deployerStr, + suite.withdrawerStr, + false, + }, + { + "invalid deployer address", + suite.contract.String(), + "", + suite.withdrawerStr, + false, + }, + { + "invalid withdraw address", + suite.contract.String(), + suite.deployerStr, + "withdraw", + false, + }, + } + + for i, tc := range testCases { + tx := MsgRegisterFeeShare{ + ContractAddress: tc.contract, + DeployerAddress: tc.deployer, + WithdrawerAddress: tc.withdraw, + } + err := tx.ValidateBasic() + + if tc.expectPass { + suite.Require().NoError(err, "valid test %d failed: %s", i, tc.msg) + } else { + suite.Require().Error(err, "invalid test %d passed: %s", i, tc.msg) + suite.Require().Contains(err.Error(), tc.msg) + } + } +} + +func (suite *MsgsTestSuite) TestMsgCancelFeeShareGetters() { + msgInvalid := MsgCancelFeeShare{} + msg := NewMsgCancelFeeShare( + suite.contract, + sdk.AccAddress(suite.deployer.Bytes()), + ) + suite.Require().Equal(RouterKey, msg.Route()) + suite.Require().Equal(TypeMsgCancelFeeShare, msg.Type()) + suite.Require().NotNil(msgInvalid.GetSignBytes()) + suite.Require().NotNil(msg.GetSigners()) +} + +func (suite *MsgsTestSuite) TestMsgCancelFeeShareNew() { + testCases := []struct { + msg string + contract string + deployer string + expectPass bool + }{ + { + "msg cancel contract fee - pass", + suite.contract.String(), + suite.deployerStr, + true, + }, + } + + for i, tc := range testCases { + tx := MsgCancelFeeShare{ + ContractAddress: tc.contract, + DeployerAddress: tc.deployer, + } + err := tx.ValidateBasic() + + if tc.expectPass { + suite.Require().NoError(err, "valid test %d failed: %s, %v", i, tc.msg) + } else { + suite.Require().Error(err, "invalid test %d passed: %s, %v", i, tc.msg) + suite.Require().Contains(err.Error(), tc.msg) + } + } +} + +func (suite *MsgsTestSuite) TestMsgUpdateFeeShareGetters() { + msgInvalid := MsgUpdateFeeShare{} + msg := NewMsgUpdateFeeShare( + suite.contract, + sdk.AccAddress(suite.deployer.Bytes()), + sdk.AccAddress(suite.deployer.Bytes()), + ) + suite.Require().Equal(RouterKey, msg.Route()) + suite.Require().Equal(TypeMsgUpdateFeeShare, msg.Type()) + suite.Require().NotNil(msgInvalid.GetSignBytes()) + suite.Require().NotNil(msg.GetSigners()) +} + +func (suite *MsgsTestSuite) TestMsgUpdateFeeShareNew() { + testCases := []struct { + msg string + contract string + deployer string + withdraw string + expectPass bool + }{ + { + "msg update fee - pass", + suite.contract.String(), + suite.deployerStr, + suite.withdrawerStr, + true, + }, + { + "invalid contract address", + "", + suite.deployerStr, + suite.withdrawerStr, + false, + }, + { + "invalid withdraw address", + suite.contract.String(), + suite.deployerStr, + "withdraw", + false, + }, + { + "change fee withdrawer to deployer - pass", + suite.contract.String(), + suite.deployerStr, + suite.deployerStr, + true, + }, + } + + for i, tc := range testCases { + tx := MsgUpdateFeeShare{ + ContractAddress: tc.contract, + DeployerAddress: tc.deployer, + WithdrawerAddress: tc.withdraw, + } + err := tx.ValidateBasic() + + if tc.expectPass { + suite.Require().NoError(err, "valid test %d failed: %s, %v", i, tc.msg) + } else { + suite.Require().Error(err, "invalid test %d passed: %s, %v", i, tc.msg) + suite.Require().Contains(err.Error(), tc.msg) + } + } +} diff --git a/x/feeshare/types/params.go b/x/feeshare/types/params.go new file mode 100644 index 0000000..48fba20 --- /dev/null +++ b/x/feeshare/types/params.go @@ -0,0 +1,85 @@ +package types + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// NewParams creates a new Params object +func NewParams( + enableFeeShare bool, + developerShares sdk.Dec, + allowedDenoms []string, +) Params { + return Params{ + EnableFeeShare: enableFeeShare, + DeveloperShares: developerShares, + AllowedDenoms: allowedDenoms, + } +} + +func DefaultParams() Params { + return Params{ + EnableFeeShare: DefaultEnableFeeShare, + DeveloperShares: DefaultDeveloperShares, + AllowedDenoms: DefaultAllowedDenoms, + } +} + +func validateBool(i interface{}) error { + _, ok := i.(bool) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + return nil +} + +func validateShares(i interface{}) error { + v, ok := i.(sdk.Dec) + + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.IsNil() { + return fmt.Errorf("invalid parameter: nil") + } + + if v.IsNegative() { + return fmt.Errorf("value cannot be negative: %T", i) + } + + if v.GT(sdk.OneDec()) { + return fmt.Errorf("value cannot be greater than 1: %T", i) + } + + return nil +} + +func validateArray(i interface{}) error { + _, ok := i.([]string) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + for _, denom := range i.([]string) { + if denom == "" { + return fmt.Errorf("denom cannot be blank") + } + } + + return nil +} + +func (p Params) Validate() error { + if err := validateBool(p.EnableFeeShare); err != nil { + return err + } + if err := validateShares(p.DeveloperShares); err != nil { + return err + } + err := validateArray(p.AllowedDenoms) + return err +} diff --git a/x/feeshare/types/params_legacy.go b/x/feeshare/types/params_legacy.go new file mode 100644 index 0000000..cb4f045 --- /dev/null +++ b/x/feeshare/types/params_legacy.go @@ -0,0 +1,33 @@ +package types + +// TODO: Remove this and params_legacy_test.go after v0.47.x (v16) upgrade + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +// Parameter store key +var ( + DefaultEnableFeeShare = true + DefaultDeveloperShares = sdk.NewDecWithPrec(50, 2) // 50% + DefaultAllowedDenoms = []string(nil) // all allowed + + ParamStoreKeyEnableFeeShare = []byte("EnableFeeShare") + ParamStoreKeyDeveloperShares = []byte("DeveloperShares") + ParamStoreKeyAllowedDenoms = []byte("AllowedDenoms") +) + +// ParamKeyTable returns the parameter key table. +func ParamKeyTable() paramtypes.KeyTable { + return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) +} + +// ParamSetPairs returns the parameter set pairs. +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{ + paramtypes.NewParamSetPair(ParamStoreKeyEnableFeeShare, &p.EnableFeeShare, validateBool), + paramtypes.NewParamSetPair(ParamStoreKeyDeveloperShares, &p.DeveloperShares, validateShares), + paramtypes.NewParamSetPair(ParamStoreKeyAllowedDenoms, &p.AllowedDenoms, validateArray), + } +} diff --git a/x/feeshare/types/params_legacy_test.go b/x/feeshare/types/params_legacy_test.go new file mode 100644 index 0000000..f79c59a --- /dev/null +++ b/x/feeshare/types/params_legacy_test.go @@ -0,0 +1,117 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +func TestLegacyParamKeyTable(t *testing.T) { + require.IsType(t, paramtypes.KeyTable{}, ParamKeyTable()) + require.NotEmpty(t, ParamKeyTable()) +} + +func TestLegacyParamSetPairs(t *testing.T) { + params := DefaultParams() + require.NotEmpty(t, params.ParamSetPairs()) +} + +func TestLegacyParamsValidate(t *testing.T) { + devShares := sdk.NewDecWithPrec(60, 2) + acceptedDenoms := []string{"uthiol"} + + testCases := []struct { + name string + params Params + expError bool + }{ + {"default", DefaultParams(), false}, + { + "valid: enabled", + NewParams(true, devShares, acceptedDenoms), + false, + }, + { + "valid: disabled", + NewParams(false, devShares, acceptedDenoms), + false, + }, + { + "valid: 100% devs", + Params{true, sdk.NewDecFromInt(sdk.NewInt(1)), acceptedDenoms}, + false, + }, + { + "empty", + Params{}, + true, + }, + { + "invalid: share > 1", + Params{true, sdk.NewDecFromInt(sdk.NewInt(2)), acceptedDenoms}, + true, + }, + { + "invalid: share < 0", + Params{true, sdk.NewDecFromInt(sdk.NewInt(-1)), acceptedDenoms}, + true, + }, + { + "valid: all denoms allowed", + Params{true, sdk.NewDecFromInt(sdk.NewInt(-1)), []string{}}, + true, + }, + } + for _, tc := range testCases { + err := tc.params.Validate() + + if tc.expError { + require.Error(t, err, tc.name) + } else { + require.NoError(t, err, tc.name) + } + } +} + +func TestLegacyParamsValidateShares(t *testing.T) { + testCases := []struct { + name string + value interface{} + expError bool + }{ + {"default", DefaultDeveloperShares, false}, + {"valid", sdk.NewDecFromInt(sdk.NewInt(1)), false}, + {"invalid - wrong type - bool", false, true}, + {"invalid - wrong type - string", "", true}, + {"invalid - wrong type - int64", int64(123), true}, + {"invalid - wrong type - math.Int", sdk.NewInt(1), true}, + {"invalid - is nil", nil, true}, + {"invalid - is negative", sdk.NewDecFromInt(sdk.NewInt(-1)), true}, + {"invalid - is > 1", sdk.NewDecFromInt(sdk.NewInt(2)), true}, + } + for _, tc := range testCases { + err := validateShares(tc.value) + + if tc.expError { + require.Error(t, err, tc.name) + } else { + require.NoError(t, err, tc.name) + } + } +} + +func TestLegacyParamsValidateBool(t *testing.T) { + err := validateBool(DefaultEnableFeeShare) + require.NoError(t, err) + err = validateBool(true) + require.NoError(t, err) + err = validateBool(false) + require.NoError(t, err) + err = validateBool("") + require.Error(t, err) + err = validateBool(int64(123)) + require.Error(t, err) +} diff --git a/x/feeshare/types/params_test.go b/x/feeshare/types/params_test.go new file mode 100644 index 0000000..e0c9d16 --- /dev/null +++ b/x/feeshare/types/params_test.go @@ -0,0 +1,116 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// func TestParamKeyTable(t *testing.T) { +// require.IsType(t, paramtypes.KeyTable{}, ParamKeyTable()) +// require.NotEmpty(t, ParamKeyTable()) +// } + +func TestDefaultParams(t *testing.T) { + params := DefaultParams() + require.NotEmpty(t, params) +} + +func TestParamsValidate(t *testing.T) { + devShares := sdk.NewDecWithPrec(60, 2) + acceptedDenoms := []string{"uthiolx"} + + testCases := []struct { + name string + params Params + expError bool + }{ + {"default", DefaultParams(), false}, + { + "valid: enabled", + NewParams(true, devShares, acceptedDenoms), + false, + }, + { + "valid: disabled", + NewParams(false, devShares, acceptedDenoms), + false, + }, + { + "valid: 100% devs", + Params{true, sdk.NewDecFromInt(sdk.NewInt(1)), acceptedDenoms}, + false, + }, + { + "empty", + Params{}, + true, + }, + { + "invalid: share > 1", + Params{true, sdk.NewDecFromInt(sdk.NewInt(2)), acceptedDenoms}, + true, + }, + { + "invalid: share < 0", + Params{true, sdk.NewDecFromInt(sdk.NewInt(-1)), acceptedDenoms}, + true, + }, + { + "valid: all denoms allowed", + Params{true, sdk.NewDecFromInt(sdk.NewInt(-1)), []string{}}, + true, + }, + } + for _, tc := range testCases { + err := tc.params.Validate() + + if tc.expError { + require.Error(t, err, tc.name) + } else { + require.NoError(t, err, tc.name) + } + } +} + +func TestParamsValidateShares(t *testing.T) { + testCases := []struct { + name string + value interface{} + expError bool + }{ + {"default", DefaultDeveloperShares, false}, + {"valid", sdk.NewDecFromInt(sdk.NewInt(1)), false}, + {"invalid - wrong type - bool", false, true}, + {"invalid - wrong type - string", "", true}, + {"invalid - wrong type - int64", int64(123), true}, + {"invalid - wrong type - math.Int", sdk.NewInt(1), true}, + {"invalid - is nil", nil, true}, + {"invalid - is negative", sdk.NewDecFromInt(sdk.NewInt(-1)), true}, + {"invalid - is > 1", sdk.NewDecFromInt(sdk.NewInt(2)), true}, + } + for _, tc := range testCases { + err := validateShares(tc.value) + + if tc.expError { + require.Error(t, err, tc.name) + } else { + require.NoError(t, err, tc.name) + } + } +} + +func TestParamsValidateBool(t *testing.T) { + err := validateBool(DefaultEnableFeeShare) + require.NoError(t, err) + err = validateBool(true) + require.NoError(t, err) + err = validateBool(false) + require.NoError(t, err) + err = validateBool("") + require.Error(t, err) + err = validateBool(int64(123)) + require.Error(t, err) +} diff --git a/x/feeshare/types/query.go b/x/feeshare/types/query.go new file mode 100644 index 0000000..89a51e6 --- /dev/null +++ b/x/feeshare/types/query.go @@ -0,0 +1,34 @@ +package types + +import ( + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// ValidateBasic runs stateless checks on the query requests +func (q QueryFeeShareRequest) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(q.ContractAddress); err != nil { + return errorsmod.Wrapf(err, "invalid contract address %s", q.ContractAddress) + } + + return nil +} + +// ValidateBasic runs stateless checks on the query requests +func (q QueryDeployerFeeSharesRequest) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(q.DeployerAddress); err != nil { + return errorsmod.Wrapf(err, "invalid deployer address %s", q.DeployerAddress) + } + + return nil +} + +// ValidateBasic runs stateless checks on the query requests +func (q QueryWithdrawerFeeSharesRequest) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(q.WithdrawerAddress); err != nil { + return errorsmod.Wrapf(err, "invalid withdraw address %s", q.WithdrawerAddress) + } + + return nil +} diff --git a/x/feeshare/types/query.pb.go b/x/feeshare/types/query.pb.go new file mode 100644 index 0000000..eaea051 --- /dev/null +++ b/x/feeshare/types/query.pb.go @@ -0,0 +1,2435 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: terp/feeshare/v1/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 + +// QueryFeeSharesRequest is the request type for the Query/FeeShares RPC method. +type QueryFeeSharesRequest struct { + // pagination defines an optional pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryFeeSharesRequest) Reset() { *m = QueryFeeSharesRequest{} } +func (m *QueryFeeSharesRequest) String() string { return proto.CompactTextString(m) } +func (*QueryFeeSharesRequest) ProtoMessage() {} +func (*QueryFeeSharesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_e972f6890c795a75, []int{0} +} +func (m *QueryFeeSharesRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryFeeSharesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryFeeSharesRequest.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 *QueryFeeSharesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryFeeSharesRequest.Merge(m, src) +} +func (m *QueryFeeSharesRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryFeeSharesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryFeeSharesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryFeeSharesRequest proto.InternalMessageInfo + +func (m *QueryFeeSharesRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryFeeSharesResponse is the response type for the Query/FeeShares RPC +// method. +type QueryFeeSharesResponse struct { + // FeeShare is a slice of all stored Reveneue + Feeshare []FeeShare `protobuf:"bytes,1,rep,name=feeshare,proto3" json:"feeshare"` + // pagination defines the pagination in the response. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryFeeSharesResponse) Reset() { *m = QueryFeeSharesResponse{} } +func (m *QueryFeeSharesResponse) String() string { return proto.CompactTextString(m) } +func (*QueryFeeSharesResponse) ProtoMessage() {} +func (*QueryFeeSharesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e972f6890c795a75, []int{1} +} +func (m *QueryFeeSharesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryFeeSharesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryFeeSharesResponse.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 *QueryFeeSharesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryFeeSharesResponse.Merge(m, src) +} +func (m *QueryFeeSharesResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryFeeSharesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryFeeSharesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryFeeSharesResponse proto.InternalMessageInfo + +func (m *QueryFeeSharesResponse) GetFeeshare() []FeeShare { + if m != nil { + return m.Feeshare + } + return nil +} + +func (m *QueryFeeSharesResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryFeeShareRequest is the request type for the Query/FeeShare RPC method. +type QueryFeeShareRequest struct { + // contract_address of a registered contract in bech32 format + ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` +} + +func (m *QueryFeeShareRequest) Reset() { *m = QueryFeeShareRequest{} } +func (m *QueryFeeShareRequest) String() string { return proto.CompactTextString(m) } +func (*QueryFeeShareRequest) ProtoMessage() {} +func (*QueryFeeShareRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_e972f6890c795a75, []int{2} +} +func (m *QueryFeeShareRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryFeeShareRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryFeeShareRequest.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 *QueryFeeShareRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryFeeShareRequest.Merge(m, src) +} +func (m *QueryFeeShareRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryFeeShareRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryFeeShareRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryFeeShareRequest proto.InternalMessageInfo + +func (m *QueryFeeShareRequest) GetContractAddress() string { + if m != nil { + return m.ContractAddress + } + return "" +} + +// QueryFeeShareResponse is the response type for the Query/FeeShare RPC method. +type QueryFeeShareResponse struct { + // FeeShare is a stored Reveneue for the queried contract + Feeshare FeeShare `protobuf:"bytes,1,opt,name=feeshare,proto3" json:"feeshare"` +} + +func (m *QueryFeeShareResponse) Reset() { *m = QueryFeeShareResponse{} } +func (m *QueryFeeShareResponse) String() string { return proto.CompactTextString(m) } +func (*QueryFeeShareResponse) ProtoMessage() {} +func (*QueryFeeShareResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e972f6890c795a75, []int{3} +} +func (m *QueryFeeShareResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryFeeShareResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryFeeShareResponse.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 *QueryFeeShareResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryFeeShareResponse.Merge(m, src) +} +func (m *QueryFeeShareResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryFeeShareResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryFeeShareResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryFeeShareResponse proto.InternalMessageInfo + +func (m *QueryFeeShareResponse) GetFeeshare() FeeShare { + if m != nil { + return m.Feeshare + } + return FeeShare{} +} + +// QueryParamsRequest is the 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_e972f6890c795a75, []int{4} +} +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 the response type for the Query/Params RPC method. +type QueryParamsResponse struct { + // params is the returned FeeShare parameter + 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_e972f6890c795a75, []int{5} +} +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{} +} + +// QueryDeployerFeeSharesRequest is the request type for the +// Query/DeployerFeeShares RPC method. +type QueryDeployerFeeSharesRequest struct { + // deployer_address in bech32 format + DeployerAddress string `protobuf:"bytes,1,opt,name=deployer_address,json=deployerAddress,proto3" json:"deployer_address,omitempty"` + // pagination defines an optional pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryDeployerFeeSharesRequest) Reset() { *m = QueryDeployerFeeSharesRequest{} } +func (m *QueryDeployerFeeSharesRequest) String() string { return proto.CompactTextString(m) } +func (*QueryDeployerFeeSharesRequest) ProtoMessage() {} +func (*QueryDeployerFeeSharesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_e972f6890c795a75, []int{6} +} +func (m *QueryDeployerFeeSharesRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryDeployerFeeSharesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryDeployerFeeSharesRequest.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 *QueryDeployerFeeSharesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryDeployerFeeSharesRequest.Merge(m, src) +} +func (m *QueryDeployerFeeSharesRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryDeployerFeeSharesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryDeployerFeeSharesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryDeployerFeeSharesRequest proto.InternalMessageInfo + +func (m *QueryDeployerFeeSharesRequest) GetDeployerAddress() string { + if m != nil { + return m.DeployerAddress + } + return "" +} + +func (m *QueryDeployerFeeSharesRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryDeployerFeeSharesResponse is the response type for the +// Query/DeployerFeeShares RPC method. +type QueryDeployerFeeSharesResponse struct { + // contract_addresses is the slice of registered contract addresses for a + // deployer + ContractAddresses []string `protobuf:"bytes,1,rep,name=contract_addresses,json=contractAddresses,proto3" json:"contract_addresses,omitempty"` + // pagination defines the pagination in the response. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryDeployerFeeSharesResponse) Reset() { *m = QueryDeployerFeeSharesResponse{} } +func (m *QueryDeployerFeeSharesResponse) String() string { return proto.CompactTextString(m) } +func (*QueryDeployerFeeSharesResponse) ProtoMessage() {} +func (*QueryDeployerFeeSharesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e972f6890c795a75, []int{7} +} +func (m *QueryDeployerFeeSharesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryDeployerFeeSharesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryDeployerFeeSharesResponse.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 *QueryDeployerFeeSharesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryDeployerFeeSharesResponse.Merge(m, src) +} +func (m *QueryDeployerFeeSharesResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryDeployerFeeSharesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryDeployerFeeSharesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryDeployerFeeSharesResponse proto.InternalMessageInfo + +func (m *QueryDeployerFeeSharesResponse) GetContractAddresses() []string { + if m != nil { + return m.ContractAddresses + } + return nil +} + +func (m *QueryDeployerFeeSharesResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryWithdrawerFeeSharesRequest is the request type for the +// Query/WithdrawerFeeShares RPC method. +type QueryWithdrawerFeeSharesRequest struct { + // withdrawer_address in bech32 format + WithdrawerAddress string `protobuf:"bytes,1,opt,name=withdrawer_address,json=withdrawerAddress,proto3" json:"withdrawer_address,omitempty"` + // pagination defines an optional pagination for the request. + Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryWithdrawerFeeSharesRequest) Reset() { *m = QueryWithdrawerFeeSharesRequest{} } +func (m *QueryWithdrawerFeeSharesRequest) String() string { return proto.CompactTextString(m) } +func (*QueryWithdrawerFeeSharesRequest) ProtoMessage() {} +func (*QueryWithdrawerFeeSharesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_e972f6890c795a75, []int{8} +} +func (m *QueryWithdrawerFeeSharesRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryWithdrawerFeeSharesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryWithdrawerFeeSharesRequest.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 *QueryWithdrawerFeeSharesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryWithdrawerFeeSharesRequest.Merge(m, src) +} +func (m *QueryWithdrawerFeeSharesRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryWithdrawerFeeSharesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryWithdrawerFeeSharesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryWithdrawerFeeSharesRequest proto.InternalMessageInfo + +func (m *QueryWithdrawerFeeSharesRequest) GetWithdrawerAddress() string { + if m != nil { + return m.WithdrawerAddress + } + return "" +} + +func (m *QueryWithdrawerFeeSharesRequest) GetPagination() *query.PageRequest { + if m != nil { + return m.Pagination + } + return nil +} + +// QueryWithdrawerFeeSharesResponse is the response type for the +// Query/WithdrawerFeeShares RPC method. +type QueryWithdrawerFeeSharesResponse struct { + // contract_addresses is the slice of registered contract addresses for a + // withdrawer + ContractAddresses []string `protobuf:"bytes,1,rep,name=contract_addresses,json=contractAddresses,proto3" json:"contract_addresses,omitempty"` + // pagination defines the pagination in the response. + Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +} + +func (m *QueryWithdrawerFeeSharesResponse) Reset() { *m = QueryWithdrawerFeeSharesResponse{} } +func (m *QueryWithdrawerFeeSharesResponse) String() string { return proto.CompactTextString(m) } +func (*QueryWithdrawerFeeSharesResponse) ProtoMessage() {} +func (*QueryWithdrawerFeeSharesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_e972f6890c795a75, []int{9} +} +func (m *QueryWithdrawerFeeSharesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryWithdrawerFeeSharesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryWithdrawerFeeSharesResponse.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 *QueryWithdrawerFeeSharesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryWithdrawerFeeSharesResponse.Merge(m, src) +} +func (m *QueryWithdrawerFeeSharesResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryWithdrawerFeeSharesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryWithdrawerFeeSharesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryWithdrawerFeeSharesResponse proto.InternalMessageInfo + +func (m *QueryWithdrawerFeeSharesResponse) GetContractAddresses() []string { + if m != nil { + return m.ContractAddresses + } + return nil +} + +func (m *QueryWithdrawerFeeSharesResponse) GetPagination() *query.PageResponse { + if m != nil { + return m.Pagination + } + return nil +} + +func init() { + proto.RegisterType((*QueryFeeSharesRequest)(nil), "terp.feeshare.v1.QueryFeeSharesRequest") + proto.RegisterType((*QueryFeeSharesResponse)(nil), "terp.feeshare.v1.QueryFeeSharesResponse") + proto.RegisterType((*QueryFeeShareRequest)(nil), "terp.feeshare.v1.QueryFeeShareRequest") + proto.RegisterType((*QueryFeeShareResponse)(nil), "terp.feeshare.v1.QueryFeeShareResponse") + proto.RegisterType((*QueryParamsRequest)(nil), "terp.feeshare.v1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "terp.feeshare.v1.QueryParamsResponse") + proto.RegisterType((*QueryDeployerFeeSharesRequest)(nil), "terp.feeshare.v1.QueryDeployerFeeSharesRequest") + proto.RegisterType((*QueryDeployerFeeSharesResponse)(nil), "terp.feeshare.v1.QueryDeployerFeeSharesResponse") + proto.RegisterType((*QueryWithdrawerFeeSharesRequest)(nil), "terp.feeshare.v1.QueryWithdrawerFeeSharesRequest") + proto.RegisterType((*QueryWithdrawerFeeSharesResponse)(nil), "terp.feeshare.v1.QueryWithdrawerFeeSharesResponse") +} + +func init() { proto.RegisterFile("terp/feeshare/v1/query.proto", fileDescriptor_e972f6890c795a75) } + +var fileDescriptor_e972f6890c795a75 = []byte{ + // 675 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x95, 0xcf, 0x6b, 0x13, 0x41, + 0x14, 0xc7, 0x33, 0x55, 0x43, 0xfb, 0x7a, 0xb0, 0x9d, 0x56, 0x09, 0x4b, 0xdd, 0x86, 0xa5, 0xf6, + 0x87, 0xd0, 0x1d, 0x37, 0x05, 0x45, 0xf0, 0xd2, 0x22, 0xf5, 0x20, 0x42, 0x8d, 0x88, 0xe0, 0xa5, + 0x4c, 0x92, 0xe7, 0x36, 0xd8, 0xee, 0x6c, 0x77, 0xb6, 0x8d, 0x45, 0x7a, 0x11, 0x4f, 0x9e, 0x44, + 0x3d, 0x14, 0x2f, 0xfe, 0x09, 0x1e, 0xfd, 0x17, 0x7a, 0x2c, 0x78, 0xf1, 0x24, 0xd2, 0xfa, 0x87, + 0x48, 0x66, 0x66, 0x53, 0xb3, 0x9b, 0x6d, 0x8c, 0x14, 0xbc, 0x2d, 0xf3, 0x7e, 0x7c, 0x3f, 0xef, + 0xcd, 0x9b, 0xb7, 0x30, 0x15, 0x63, 0x14, 0xb2, 0xe7, 0x88, 0x72, 0x83, 0x47, 0xc8, 0x76, 0x3d, + 0xb6, 0xbd, 0x83, 0xd1, 0x9e, 0x1b, 0x46, 0x22, 0x16, 0x74, 0xac, 0x6d, 0x75, 0x13, 0xab, 0xbb, + 0xeb, 0x59, 0x37, 0xea, 0x42, 0x6e, 0x09, 0xc9, 0x6a, 0x5c, 0xa2, 0x76, 0x65, 0xbb, 0x5e, 0x0d, + 0x63, 0xee, 0xb1, 0x90, 0xfb, 0xcd, 0x80, 0xc7, 0x4d, 0x11, 0xe8, 0x68, 0xcb, 0xce, 0xe4, 0xf6, + 0x31, 0x40, 0xd9, 0x94, 0xc6, 0x3e, 0x9d, 0xb1, 0x77, 0x94, 0xb4, 0xc3, 0xa4, 0x2f, 0x7c, 0xa1, + 0x3e, 0x59, 0xfb, 0xcb, 0x9c, 0x4e, 0xf9, 0x42, 0xf8, 0x9b, 0xc8, 0x78, 0xd8, 0x64, 0x3c, 0x08, + 0x44, 0xac, 0x34, 0x4d, 0x52, 0x67, 0x1d, 0xae, 0x3c, 0x6a, 0x63, 0xad, 0x22, 0x3e, 0x6e, 0xa7, + 0x92, 0x55, 0xdc, 0xde, 0x41, 0x19, 0xd3, 0x55, 0x80, 0x53, 0xc2, 0x12, 0x29, 0x93, 0xf9, 0xd1, + 0xca, 0xac, 0xab, 0xcb, 0x71, 0xdb, 0xe5, 0xb8, 0xba, 0x72, 0x53, 0x8e, 0xbb, 0xc6, 0x7d, 0x34, + 0xb1, 0xd5, 0x3f, 0x22, 0x9d, 0xcf, 0x04, 0xae, 0xa6, 0x15, 0x64, 0x28, 0x02, 0x89, 0xf4, 0x2e, + 0x0c, 0x27, 0x15, 0x94, 0x48, 0xf9, 0xc2, 0xfc, 0x68, 0xc5, 0x72, 0xd3, 0x1d, 0x74, 0x93, 0xb0, + 0x95, 0x8b, 0x87, 0x3f, 0xa6, 0x0b, 0xd5, 0x4e, 0x04, 0xbd, 0xdf, 0x05, 0x38, 0xa4, 0x00, 0xe7, + 0xfa, 0x02, 0x6a, 0xe9, 0x2e, 0xc2, 0x65, 0x98, 0xec, 0x02, 0x4c, 0x3a, 0xb0, 0x00, 0x63, 0x75, + 0x11, 0xc4, 0x11, 0xaf, 0xc7, 0xeb, 0xbc, 0xd1, 0x88, 0x50, 0x4a, 0xd5, 0x87, 0x91, 0xea, 0xe5, + 0xe4, 0x7c, 0x59, 0x1f, 0x3b, 0x4f, 0x52, 0x5d, 0xcc, 0x29, 0x91, 0x0c, 0x56, 0xa2, 0x33, 0x09, + 0x54, 0xa5, 0x5d, 0xe3, 0x11, 0xdf, 0x4a, 0x6e, 0xc6, 0x79, 0x08, 0x13, 0x5d, 0xa7, 0x46, 0xea, + 0x16, 0x14, 0x43, 0x75, 0x62, 0x84, 0x4a, 0x59, 0x21, 0x1d, 0x61, 0x64, 0x8c, 0xb7, 0xf3, 0x9e, + 0xc0, 0x35, 0x95, 0xef, 0x1e, 0x86, 0x9b, 0x62, 0x0f, 0xa3, 0xcc, 0x28, 0x2c, 0xc0, 0x58, 0xc3, + 0xd8, 0xd2, 0x8d, 0x48, 0xce, 0x4d, 0x23, 0x52, 0x53, 0x33, 0xf4, 0xcf, 0x53, 0x73, 0x40, 0xc0, + 0xce, 0x83, 0x32, 0xf5, 0x2e, 0x02, 0x4d, 0x5f, 0x0f, 0x4a, 0x35, 0x47, 0x23, 0xd5, 0xf1, 0xd4, + 0x05, 0xa1, 0x3c, 0xbf, 0x71, 0x39, 0x20, 0x30, 0xad, 0xd0, 0x9e, 0x36, 0xe3, 0x8d, 0x46, 0xc4, + 0x5b, 0x3d, 0x3a, 0xb6, 0x08, 0xb4, 0xd5, 0xb1, 0xa6, 0x7a, 0x36, 0x7e, 0x6a, 0x39, 0xef, 0xae, + 0x7d, 0x22, 0x50, 0xce, 0x47, 0xfb, 0xbf, 0x7d, 0xab, 0xbc, 0x2d, 0xc2, 0x25, 0x05, 0x47, 0xdf, + 0x10, 0x18, 0xe9, 0x70, 0xd1, 0xb9, 0xec, 0x9c, 0xf6, 0xdc, 0x48, 0xd6, 0x7c, 0x7f, 0x47, 0x2d, + 0xeb, 0xcc, 0xbc, 0xfe, 0xf6, 0xeb, 0xc3, 0x90, 0x4d, 0xa7, 0x58, 0xaf, 0x95, 0xb9, 0x2e, 0xb5, + 0xf0, 0x47, 0x02, 0xc3, 0x49, 0x2c, 0x9d, 0xed, 0x93, 0x3c, 0x81, 0x98, 0xeb, 0xeb, 0x67, 0x18, + 0x6e, 0x2b, 0x06, 0x8f, 0xb2, 0xb3, 0x18, 0xd8, 0xab, 0xf4, 0x55, 0xec, 0xd3, 0x16, 0x14, 0xf5, + 0x3b, 0xa5, 0x33, 0x39, 0x5a, 0x5d, 0xeb, 0xc0, 0xba, 0xde, 0xc7, 0xcb, 0xf0, 0x94, 0x15, 0x8f, + 0x45, 0x4b, 0x59, 0x1e, 0xbd, 0x08, 0xe8, 0x17, 0x02, 0xe3, 0x99, 0xe7, 0x46, 0x59, 0x4e, 0xfa, + 0xbc, 0x6d, 0x61, 0xdd, 0xfc, 0xfb, 0x80, 0xc1, 0x5a, 0x95, 0xde, 0x41, 0xfb, 0xf4, 0x2b, 0x81, + 0x89, 0x1e, 0xa3, 0x4e, 0xbd, 0x1c, 0x84, 0xfc, 0x17, 0x6b, 0x55, 0x06, 0x09, 0x31, 0xdc, 0x77, + 0x14, 0xf7, 0x12, 0xf5, 0xce, 0xe6, 0xce, 0x6e, 0x82, 0xfd, 0x95, 0x07, 0x87, 0xc7, 0x36, 0x39, + 0x3a, 0xb6, 0xc9, 0xcf, 0x63, 0x9b, 0xbc, 0x3b, 0xb1, 0x0b, 0x47, 0x27, 0x76, 0xe1, 0xfb, 0x89, + 0x5d, 0x78, 0xe6, 0xf9, 0xcd, 0x78, 0x63, 0xa7, 0xe6, 0xd6, 0xc5, 0x96, 0x4a, 0x1b, 0x60, 0xdc, + 0x12, 0xd1, 0x0b, 0xf5, 0xbd, 0x58, 0x17, 0x11, 0xb2, 0x97, 0xa7, 0x4a, 0xf1, 0x5e, 0x88, 0xb2, + 0x56, 0x54, 0xbf, 0xf2, 0xa5, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0x64, 0x9c, 0x4f, 0x2c, 0x9d, + 0x08, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// 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 { + // FeeShares retrieves all registered FeeShares + FeeShares(ctx context.Context, in *QueryFeeSharesRequest, opts ...grpc.CallOption) (*QueryFeeSharesResponse, error) + // FeeShare retrieves a registered FeeShare for a given contract address + FeeShare(ctx context.Context, in *QueryFeeShareRequest, opts ...grpc.CallOption) (*QueryFeeShareResponse, error) + // Params retrieves the FeeShare module params + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + // DeployerFeeShares retrieves all FeeShares that a given deployer has + // registered + DeployerFeeShares(ctx context.Context, in *QueryDeployerFeeSharesRequest, opts ...grpc.CallOption) (*QueryDeployerFeeSharesResponse, error) + // WithdrawerFeeShares retrieves all FeeShares with a given withdrawer + // address + WithdrawerFeeShares(ctx context.Context, in *QueryWithdrawerFeeSharesRequest, opts ...grpc.CallOption) (*QueryWithdrawerFeeSharesResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) FeeShares(ctx context.Context, in *QueryFeeSharesRequest, opts ...grpc.CallOption) (*QueryFeeSharesResponse, error) { + out := new(QueryFeeSharesResponse) + err := c.cc.Invoke(ctx, "/terp.feeshare.v1.Query/FeeShares", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) FeeShare(ctx context.Context, in *QueryFeeShareRequest, opts ...grpc.CallOption) (*QueryFeeShareResponse, error) { + out := new(QueryFeeShareResponse) + err := c.cc.Invoke(ctx, "/terp.feeshare.v1.Query/FeeShare", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/terp.feeshare.v1.Query/Params", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) DeployerFeeShares(ctx context.Context, in *QueryDeployerFeeSharesRequest, opts ...grpc.CallOption) (*QueryDeployerFeeSharesResponse, error) { + out := new(QueryDeployerFeeSharesResponse) + err := c.cc.Invoke(ctx, "/terp.feeshare.v1.Query/DeployerFeeShares", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) WithdrawerFeeShares(ctx context.Context, in *QueryWithdrawerFeeSharesRequest, opts ...grpc.CallOption) (*QueryWithdrawerFeeSharesResponse, error) { + out := new(QueryWithdrawerFeeSharesResponse) + err := c.cc.Invoke(ctx, "/terp.feeshare.v1.Query/WithdrawerFeeShares", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // FeeShares retrieves all registered FeeShares + FeeShares(context.Context, *QueryFeeSharesRequest) (*QueryFeeSharesResponse, error) + // FeeShare retrieves a registered FeeShare for a given contract address + FeeShare(context.Context, *QueryFeeShareRequest) (*QueryFeeShareResponse, error) + // Params retrieves the FeeShare module params + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + // DeployerFeeShares retrieves all FeeShares that a given deployer has + // registered + DeployerFeeShares(context.Context, *QueryDeployerFeeSharesRequest) (*QueryDeployerFeeSharesResponse, error) + // WithdrawerFeeShares retrieves all FeeShares with a given withdrawer + // address + WithdrawerFeeShares(context.Context, *QueryWithdrawerFeeSharesRequest) (*QueryWithdrawerFeeSharesResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) FeeShares(ctx context.Context, req *QueryFeeSharesRequest) (*QueryFeeSharesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method FeeShares not implemented") +} +func (*UnimplementedQueryServer) FeeShare(ctx context.Context, req *QueryFeeShareRequest) (*QueryFeeShareResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method FeeShare not implemented") +} +func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") +} +func (*UnimplementedQueryServer) DeployerFeeShares(ctx context.Context, req *QueryDeployerFeeSharesRequest) (*QueryDeployerFeeSharesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method DeployerFeeShares not implemented") +} +func (*UnimplementedQueryServer) WithdrawerFeeShares(ctx context.Context, req *QueryWithdrawerFeeSharesRequest) (*QueryWithdrawerFeeSharesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method WithdrawerFeeShares not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_FeeShares_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryFeeSharesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).FeeShares(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/terp.feeshare.v1.Query/FeeShares", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).FeeShares(ctx, req.(*QueryFeeSharesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_FeeShare_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryFeeShareRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).FeeShare(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/terp.feeshare.v1.Query/FeeShare", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).FeeShare(ctx, req.(*QueryFeeShareRequest)) + } + return interceptor(ctx, in, info, handler) +} + +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: "/terp.feeshare.v1.Query/Params", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_DeployerFeeShares_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryDeployerFeeSharesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).DeployerFeeShares(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/terp.feeshare.v1.Query/DeployerFeeShares", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).DeployerFeeShares(ctx, req.(*QueryDeployerFeeSharesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_WithdrawerFeeShares_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryWithdrawerFeeSharesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).WithdrawerFeeShares(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/terp.feeshare.v1.Query/WithdrawerFeeShares", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).WithdrawerFeeShares(ctx, req.(*QueryWithdrawerFeeSharesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "terp.feeshare.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "FeeShares", + Handler: _Query_FeeShares_Handler, + }, + { + MethodName: "FeeShare", + Handler: _Query_FeeShare_Handler, + }, + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + { + MethodName: "DeployerFeeShares", + Handler: _Query_DeployerFeeShares_Handler, + }, + { + MethodName: "WithdrawerFeeShares", + Handler: _Query_WithdrawerFeeShares_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "terp/feeshare/v1/query.proto", +} + +func (m *QueryFeeSharesRequest) 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 *QueryFeeSharesRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryFeeSharesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Pagination != nil { + { + size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryFeeSharesResponse) 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 *QueryFeeSharesResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryFeeSharesResponse) 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.Feeshare) > 0 { + for iNdEx := len(m.Feeshare) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Feeshare[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryFeeShareRequest) 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 *QueryFeeShareRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryFeeShareRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ContractAddress) > 0 { + i -= len(m.ContractAddress) + copy(dAtA[i:], m.ContractAddress) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ContractAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryFeeShareResponse) 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 *QueryFeeShareResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryFeeShareResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Feeshare.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 *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 *QueryDeployerFeeSharesRequest) 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 *QueryDeployerFeeSharesRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryDeployerFeeSharesRequest) 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.DeployerAddress) > 0 { + i -= len(m.DeployerAddress) + copy(dAtA[i:], m.DeployerAddress) + i = encodeVarintQuery(dAtA, i, uint64(len(m.DeployerAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryDeployerFeeSharesResponse) 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 *QueryDeployerFeeSharesResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryDeployerFeeSharesResponse) 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.ContractAddresses) > 0 { + for iNdEx := len(m.ContractAddresses) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.ContractAddresses[iNdEx]) + copy(dAtA[i:], m.ContractAddresses[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ContractAddresses[iNdEx]))) + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryWithdrawerFeeSharesRequest) 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 *QueryWithdrawerFeeSharesRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryWithdrawerFeeSharesRequest) 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.WithdrawerAddress) > 0 { + i -= len(m.WithdrawerAddress) + copy(dAtA[i:], m.WithdrawerAddress) + i = encodeVarintQuery(dAtA, i, uint64(len(m.WithdrawerAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryWithdrawerFeeSharesResponse) 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 *QueryWithdrawerFeeSharesResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryWithdrawerFeeSharesResponse) 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.ContractAddresses) > 0 { + for iNdEx := len(m.ContractAddresses) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.ContractAddresses[iNdEx]) + copy(dAtA[i:], m.ContractAddresses[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.ContractAddresses[iNdEx]))) + 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 *QueryFeeSharesRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryFeeSharesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Feeshare) > 0 { + for _, e := range m.Feeshare { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryFeeShareRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ContractAddress) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryFeeShareResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Feeshare.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +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 *QueryDeployerFeeSharesRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.DeployerAddress) + 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 *QueryDeployerFeeSharesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.ContractAddresses) > 0 { + for _, s := range m.ContractAddresses { + l = len(s) + n += 1 + l + sovQuery(uint64(l)) + } + } + if m.Pagination != nil { + l = m.Pagination.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryWithdrawerFeeSharesRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.WithdrawerAddress) + 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 *QueryWithdrawerFeeSharesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.ContractAddresses) > 0 { + for _, s := range m.ContractAddresses { + l = len(s) + 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 *QueryFeeSharesRequest) 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: QueryFeeSharesRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryFeeSharesRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageRequest{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryFeeSharesResponse) 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: QueryFeeSharesResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryFeeSharesResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Feeshare", 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.Feeshare = append(m.Feeshare, FeeShare{}) + if err := m.Feeshare[len(m.Feeshare)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Pagination == nil { + m.Pagination = &query.PageResponse{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryFeeShareRequest) 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: QueryFeeShareRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryFeeShareRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", 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.ContractAddress = 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 *QueryFeeShareResponse) 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: QueryFeeShareResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryFeeShareResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Feeshare", 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.Feeshare.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 *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 *QueryDeployerFeeSharesRequest) 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: QueryDeployerFeeSharesRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryDeployerFeeSharesRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DeployerAddress", 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.DeployerAddress = 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 *QueryDeployerFeeSharesResponse) 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: QueryDeployerFeeSharesResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryDeployerFeeSharesResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractAddresses", 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.ContractAddresses = append(m.ContractAddresses, 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.PageResponse{} + } + if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryWithdrawerFeeSharesRequest) 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: QueryWithdrawerFeeSharesRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryWithdrawerFeeSharesRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WithdrawerAddress", 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.WithdrawerAddress = 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 *QueryWithdrawerFeeSharesResponse) 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: QueryWithdrawerFeeSharesResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryWithdrawerFeeSharesResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractAddresses", 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.ContractAddresses = append(m.ContractAddresses, 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.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/feeshare/types/query.pb.gw.go b/x/feeshare/types/query.pb.gw.go new file mode 100644 index 0000000..0db12fa --- /dev/null +++ b/x/feeshare/types/query.pb.gw.go @@ -0,0 +1,575 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: terp/feeshare/v1/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +var ( + filter_Query_FeeShares_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_FeeShares_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryFeeSharesRequest + 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_FeeShares_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.FeeShares(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_FeeShares_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryFeeSharesRequest + 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_FeeShares_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.FeeShares(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_FeeShare_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryFeeShareRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["contract_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "contract_address") + } + + protoReq.ContractAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "contract_address", err) + } + + msg, err := client.FeeShare(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_FeeShare_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryFeeShareRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["contract_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "contract_address") + } + + protoReq.ContractAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "contract_address", err) + } + + msg, err := server.FeeShare(ctx, &protoReq) + return msg, metadata, err + +} + +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 + +} + +var ( + filter_Query_DeployerFeeShares_0 = &utilities.DoubleArray{Encoding: map[string]int{"deployer_address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} +) + +func request_Query_DeployerFeeShares_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryDeployerFeeSharesRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["deployer_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "deployer_address") + } + + protoReq.DeployerAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "deployer_address", 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_DeployerFeeShares_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.DeployerFeeShares(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_DeployerFeeShares_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryDeployerFeeSharesRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["deployer_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "deployer_address") + } + + protoReq.DeployerAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "deployer_address", 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_DeployerFeeShares_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.DeployerFeeShares(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_Query_WithdrawerFeeShares_0 = &utilities.DoubleArray{Encoding: map[string]int{"withdrawer_address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} +) + +func request_Query_WithdrawerFeeShares_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryWithdrawerFeeSharesRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["withdrawer_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "withdrawer_address") + } + + protoReq.WithdrawerAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "withdrawer_address", 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_WithdrawerFeeShares_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.WithdrawerFeeShares(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_WithdrawerFeeShares_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryWithdrawerFeeSharesRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["withdrawer_address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "withdrawer_address") + } + + protoReq.WithdrawerAddress, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "withdrawer_address", 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_WithdrawerFeeShares_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.WithdrawerFeeShares(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_FeeShares_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_FeeShares_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_FeeShares_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_FeeShare_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_FeeShare_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_FeeShare_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + 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_DeployerFeeShares_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_DeployerFeeShares_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_DeployerFeeShares_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_WithdrawerFeeShares_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_WithdrawerFeeShares_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_WithdrawerFeeShares_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_FeeShares_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_FeeShares_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_FeeShares_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_FeeShare_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_FeeShare_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_FeeShare_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + 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_DeployerFeeShares_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_DeployerFeeShares_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_DeployerFeeShares_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_WithdrawerFeeShares_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_WithdrawerFeeShares_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_WithdrawerFeeShares_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_FeeShares_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"terp", "feeshare", "v1", "fee_shares"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_FeeShare_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"terp", "feeshare", "v1", "fee_shares", "contract_address"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"terp", "feeshare", "v1", "params"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_DeployerFeeShares_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"terp", "feeshare", "v1", "fee_shares", "deployer_address"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_WithdrawerFeeShares_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"terp", "feeshare", "v1", "fee_shares", "withdrawer_address"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_FeeShares_0 = runtime.ForwardResponseMessage + + forward_Query_FeeShare_0 = runtime.ForwardResponseMessage + + forward_Query_Params_0 = runtime.ForwardResponseMessage + + forward_Query_DeployerFeeShares_0 = runtime.ForwardResponseMessage + + forward_Query_WithdrawerFeeShares_0 = runtime.ForwardResponseMessage +) diff --git a/x/feeshare/types/tx.pb.go b/x/feeshare/types/tx.pb.go new file mode 100644 index 0000000..7279250 --- /dev/null +++ b/x/feeshare/types/tx.pb.go @@ -0,0 +1,1871 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: terp/feeshare/v1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" + _ "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 + +// MsgRegisterFeeShare defines a message that registers a FeeShare +type MsgRegisterFeeShare struct { + // contract_address in bech32 format + ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` + // deployer_address is the bech32 address of message sender. It must be the + // same the contract's admin address + DeployerAddress string `protobuf:"bytes,2,opt,name=deployer_address,json=deployerAddress,proto3" json:"deployer_address,omitempty"` + // withdrawer_address is the bech32 address of account receiving the + // transaction fees + WithdrawerAddress string `protobuf:"bytes,3,opt,name=withdrawer_address,json=withdrawerAddress,proto3" json:"withdrawer_address,omitempty"` +} + +func (m *MsgRegisterFeeShare) Reset() { *m = MsgRegisterFeeShare{} } +func (m *MsgRegisterFeeShare) String() string { return proto.CompactTextString(m) } +func (*MsgRegisterFeeShare) ProtoMessage() {} +func (*MsgRegisterFeeShare) Descriptor() ([]byte, []int) { + return fileDescriptor_1e1ba58fd1f48d8c, []int{0} +} +func (m *MsgRegisterFeeShare) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgRegisterFeeShare) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgRegisterFeeShare.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 *MsgRegisterFeeShare) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRegisterFeeShare.Merge(m, src) +} +func (m *MsgRegisterFeeShare) XXX_Size() int { + return m.Size() +} +func (m *MsgRegisterFeeShare) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRegisterFeeShare.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgRegisterFeeShare proto.InternalMessageInfo + +func (m *MsgRegisterFeeShare) GetContractAddress() string { + if m != nil { + return m.ContractAddress + } + return "" +} + +func (m *MsgRegisterFeeShare) GetDeployerAddress() string { + if m != nil { + return m.DeployerAddress + } + return "" +} + +func (m *MsgRegisterFeeShare) GetWithdrawerAddress() string { + if m != nil { + return m.WithdrawerAddress + } + return "" +} + +// MsgRegisterFeeShareResponse defines the MsgRegisterFeeShare response type +type MsgRegisterFeeShareResponse struct { +} + +func (m *MsgRegisterFeeShareResponse) Reset() { *m = MsgRegisterFeeShareResponse{} } +func (m *MsgRegisterFeeShareResponse) String() string { return proto.CompactTextString(m) } +func (*MsgRegisterFeeShareResponse) ProtoMessage() {} +func (*MsgRegisterFeeShareResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_1e1ba58fd1f48d8c, []int{1} +} +func (m *MsgRegisterFeeShareResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgRegisterFeeShareResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgRegisterFeeShareResponse.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 *MsgRegisterFeeShareResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgRegisterFeeShareResponse.Merge(m, src) +} +func (m *MsgRegisterFeeShareResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgRegisterFeeShareResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgRegisterFeeShareResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgRegisterFeeShareResponse proto.InternalMessageInfo + +// MsgUpdateFeeShare defines a message that updates the withdrawer address for a +// registered FeeShare +type MsgUpdateFeeShare struct { + // contract_address in bech32 format + ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` + // deployer_address is the bech32 address of message sender. It must be the + // same the contract's admin address + DeployerAddress string `protobuf:"bytes,2,opt,name=deployer_address,json=deployerAddress,proto3" json:"deployer_address,omitempty"` + // withdrawer_address is the bech32 address of account receiving the + // transaction fees + WithdrawerAddress string `protobuf:"bytes,3,opt,name=withdrawer_address,json=withdrawerAddress,proto3" json:"withdrawer_address,omitempty"` +} + +func (m *MsgUpdateFeeShare) Reset() { *m = MsgUpdateFeeShare{} } +func (m *MsgUpdateFeeShare) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateFeeShare) ProtoMessage() {} +func (*MsgUpdateFeeShare) Descriptor() ([]byte, []int) { + return fileDescriptor_1e1ba58fd1f48d8c, []int{2} +} +func (m *MsgUpdateFeeShare) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateFeeShare) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateFeeShare.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 *MsgUpdateFeeShare) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateFeeShare.Merge(m, src) +} +func (m *MsgUpdateFeeShare) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateFeeShare) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateFeeShare.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateFeeShare proto.InternalMessageInfo + +func (m *MsgUpdateFeeShare) GetContractAddress() string { + if m != nil { + return m.ContractAddress + } + return "" +} + +func (m *MsgUpdateFeeShare) GetDeployerAddress() string { + if m != nil { + return m.DeployerAddress + } + return "" +} + +func (m *MsgUpdateFeeShare) GetWithdrawerAddress() string { + if m != nil { + return m.WithdrawerAddress + } + return "" +} + +// MsgUpdateFeeShareResponse defines the MsgUpdateFeeShare response type +type MsgUpdateFeeShareResponse struct { +} + +func (m *MsgUpdateFeeShareResponse) Reset() { *m = MsgUpdateFeeShareResponse{} } +func (m *MsgUpdateFeeShareResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateFeeShareResponse) ProtoMessage() {} +func (*MsgUpdateFeeShareResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_1e1ba58fd1f48d8c, []int{3} +} +func (m *MsgUpdateFeeShareResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateFeeShareResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateFeeShareResponse.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 *MsgUpdateFeeShareResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateFeeShareResponse.Merge(m, src) +} +func (m *MsgUpdateFeeShareResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateFeeShareResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateFeeShareResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateFeeShareResponse proto.InternalMessageInfo + +// MsgCancelFeeShare defines a message that cancels a registered FeeShare +type MsgCancelFeeShare struct { + // contract_address in bech32 format + ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` + // deployer_address is the bech32 address of message sender. It must be the + // same the contract's admin address + DeployerAddress string `protobuf:"bytes,2,opt,name=deployer_address,json=deployerAddress,proto3" json:"deployer_address,omitempty"` +} + +func (m *MsgCancelFeeShare) Reset() { *m = MsgCancelFeeShare{} } +func (m *MsgCancelFeeShare) String() string { return proto.CompactTextString(m) } +func (*MsgCancelFeeShare) ProtoMessage() {} +func (*MsgCancelFeeShare) Descriptor() ([]byte, []int) { + return fileDescriptor_1e1ba58fd1f48d8c, []int{4} +} +func (m *MsgCancelFeeShare) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgCancelFeeShare) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgCancelFeeShare.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 *MsgCancelFeeShare) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgCancelFeeShare.Merge(m, src) +} +func (m *MsgCancelFeeShare) XXX_Size() int { + return m.Size() +} +func (m *MsgCancelFeeShare) XXX_DiscardUnknown() { + xxx_messageInfo_MsgCancelFeeShare.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgCancelFeeShare proto.InternalMessageInfo + +func (m *MsgCancelFeeShare) GetContractAddress() string { + if m != nil { + return m.ContractAddress + } + return "" +} + +func (m *MsgCancelFeeShare) GetDeployerAddress() string { + if m != nil { + return m.DeployerAddress + } + return "" +} + +// MsgCancelFeeShareResponse defines the MsgCancelFeeShare response type +type MsgCancelFeeShareResponse struct { +} + +func (m *MsgCancelFeeShareResponse) Reset() { *m = MsgCancelFeeShareResponse{} } +func (m *MsgCancelFeeShareResponse) String() string { return proto.CompactTextString(m) } +func (*MsgCancelFeeShareResponse) ProtoMessage() {} +func (*MsgCancelFeeShareResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_1e1ba58fd1f48d8c, []int{5} +} +func (m *MsgCancelFeeShareResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgCancelFeeShareResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgCancelFeeShareResponse.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 *MsgCancelFeeShareResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgCancelFeeShareResponse.Merge(m, src) +} +func (m *MsgCancelFeeShareResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgCancelFeeShareResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgCancelFeeShareResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgCancelFeeShareResponse proto.InternalMessageInfo + +// MsgUpdateParams is the Msg/UpdateParams request type. +// +// Since: cosmos-sdk 0.47 +type MsgUpdateParams struct { + // authority is the address that controls the module (defaults to x/gov unless overwritten). + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` + // params defines the x/feeshare parameters to update. + // + // NOTE: All parameters must be supplied. + Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` +} + +func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } +func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParams) ProtoMessage() {} +func (*MsgUpdateParams) Descriptor() ([]byte, []int) { + return fileDescriptor_1e1ba58fd1f48d8c, []int{6} +} +func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParams.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 *MsgUpdateParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParams.Merge(m, src) +} +func (m *MsgUpdateParams) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParams) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo + +func (m *MsgUpdateParams) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func (m *MsgUpdateParams) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +// +// Since: cosmos-sdk 0.47 +type MsgUpdateParamsResponse struct { +} + +func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } +func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParamsResponse) ProtoMessage() {} +func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_1e1ba58fd1f48d8c, []int{7} +} +func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParamsResponse.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 *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) +} +func (m *MsgUpdateParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgRegisterFeeShare)(nil), "terp.feeshare.v1.MsgRegisterFeeShare") + proto.RegisterType((*MsgRegisterFeeShareResponse)(nil), "terp.feeshare.v1.MsgRegisterFeeShareResponse") + proto.RegisterType((*MsgUpdateFeeShare)(nil), "terp.feeshare.v1.MsgUpdateFeeShare") + proto.RegisterType((*MsgUpdateFeeShareResponse)(nil), "terp.feeshare.v1.MsgUpdateFeeShareResponse") + proto.RegisterType((*MsgCancelFeeShare)(nil), "terp.feeshare.v1.MsgCancelFeeShare") + proto.RegisterType((*MsgCancelFeeShareResponse)(nil), "terp.feeshare.v1.MsgCancelFeeShareResponse") + proto.RegisterType((*MsgUpdateParams)(nil), "terp.feeshare.v1.MsgUpdateParams") + proto.RegisterType((*MsgUpdateParamsResponse)(nil), "terp.feeshare.v1.MsgUpdateParamsResponse") +} + +func init() { proto.RegisterFile("terp/feeshare/v1/tx.proto", fileDescriptor_1e1ba58fd1f48d8c) } + +var fileDescriptor_1e1ba58fd1f48d8c = []byte{ + // 560 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x94, 0x4f, 0x6b, 0x13, 0x41, + 0x18, 0x87, 0x33, 0x6d, 0x29, 0x74, 0x94, 0x36, 0x5d, 0x0b, 0x4d, 0x52, 0xdd, 0xea, 0xaa, 0xa5, + 0x55, 0xb3, 0x43, 0x2a, 0xf4, 0xd0, 0x9b, 0x11, 0xbc, 0x48, 0x40, 0x52, 0xbc, 0x88, 0x10, 0xa6, + 0x9b, 0xd7, 0xc9, 0x62, 0xb2, 0xb3, 0xcc, 0x4c, 0x9a, 0xe6, 0xda, 0x4f, 0x50, 0xf1, 0xe2, 0x49, + 0x7a, 0xf0, 0x03, 0x78, 0xf0, 0x43, 0xf4, 0x58, 0xf4, 0xe2, 0x49, 0x24, 0x11, 0xf4, 0x63, 0xc8, + 0xce, 0xfe, 0x73, 0x93, 0x6d, 0xed, 0x45, 0xf0, 0x36, 0x3b, 0xbf, 0x67, 0xde, 0xf7, 0xd9, 0xe5, + 0x9d, 0xc5, 0x65, 0x05, 0xc2, 0x27, 0xaf, 0x00, 0x64, 0x87, 0x0a, 0x20, 0x07, 0x35, 0xa2, 0x0e, + 0x6d, 0x5f, 0x70, 0xc5, 0x8d, 0x62, 0x10, 0xd9, 0x71, 0x64, 0x1f, 0xd4, 0x2a, 0x2b, 0x8c, 0x33, + 0xae, 0x43, 0x12, 0xac, 0x42, 0xae, 0x72, 0x9d, 0x71, 0xce, 0xba, 0x40, 0xa8, 0xef, 0x12, 0xea, + 0x79, 0x5c, 0x51, 0xe5, 0x72, 0x4f, 0x46, 0xe9, 0xaa, 0xc3, 0x65, 0x8f, 0x4b, 0xd2, 0x93, 0x2c, + 0xa8, 0xde, 0x93, 0x2c, 0x0a, 0xca, 0x61, 0xd0, 0x0a, 0xeb, 0x85, 0x0f, 0x51, 0x64, 0x4e, 0x49, + 0x31, 0xf0, 0x40, 0xba, 0x51, 0x6e, 0x9d, 0x20, 0x7c, 0xad, 0x21, 0x59, 0x13, 0x98, 0x2b, 0x15, + 0x88, 0x27, 0x00, 0x7b, 0x01, 0x68, 0x6c, 0xe1, 0xa2, 0xc3, 0x3d, 0x25, 0xa8, 0xa3, 0x5a, 0xb4, + 0xdd, 0x16, 0x20, 0x65, 0x09, 0xdd, 0x44, 0x9b, 0x0b, 0xcd, 0xa5, 0x78, 0xff, 0x51, 0xb8, 0x1d, + 0xa0, 0x6d, 0xf0, 0xbb, 0x7c, 0x08, 0x22, 0x41, 0x67, 0x42, 0x34, 0xde, 0x8f, 0xd1, 0x2a, 0x36, + 0x06, 0xae, 0xea, 0xb4, 0x05, 0x1d, 0xfc, 0x01, 0xcf, 0x6a, 0x78, 0x39, 0x4d, 0x22, 0x7c, 0x77, + 0xee, 0xd7, 0xc9, 0x7a, 0xc1, 0xba, 0x81, 0xd7, 0x72, 0x0c, 0x9b, 0x20, 0x7d, 0xee, 0x49, 0xb0, + 0xde, 0x23, 0xbc, 0xdc, 0x90, 0xec, 0xb9, 0xdf, 0xa6, 0x0a, 0xfe, 0x47, 0xff, 0x35, 0x5c, 0x9e, + 0xf2, 0x4b, 0xec, 0xb9, 0x96, 0x7f, 0x4c, 0x3d, 0x07, 0xba, 0xff, 0x56, 0x3e, 0x63, 0x93, 0x6d, + 0x98, 0xd8, 0xbc, 0x41, 0x78, 0x29, 0x71, 0x7d, 0x46, 0x05, 0xed, 0x49, 0x63, 0x07, 0x2f, 0xd0, + 0xbe, 0xea, 0x70, 0xe1, 0xaa, 0x61, 0x68, 0x51, 0x2f, 0x7d, 0xfe, 0x54, 0x5d, 0x89, 0xc6, 0x2c, + 0xaa, 0xbe, 0xa7, 0x84, 0xeb, 0xb1, 0x66, 0x8a, 0x1a, 0x3b, 0x78, 0xde, 0xd7, 0x15, 0xb4, 0xcf, + 0x95, 0xed, 0x92, 0x3d, 0x79, 0x09, 0xec, 0xb0, 0x43, 0x7d, 0xee, 0xf4, 0xdb, 0x7a, 0xa1, 0x19, + 0xd1, 0xbb, 0x8b, 0x47, 0x3f, 0x3f, 0xde, 0x4b, 0xeb, 0x58, 0x65, 0xbc, 0x3a, 0xa1, 0x14, 0xeb, + 0x6e, 0x7f, 0x98, 0xc3, 0xb3, 0x0d, 0xc9, 0x8c, 0x77, 0x08, 0x17, 0xa7, 0x26, 0xf8, 0xee, 0x74, + 0xbf, 0x9c, 0x31, 0xaa, 0x54, 0x2f, 0x85, 0x25, 0x5f, 0xc8, 0x3e, 0xfa, 0xf2, 0xe3, 0xed, 0xcc, + 0xa6, 0xb5, 0x41, 0x72, 0x6e, 0x3b, 0x11, 0xd1, 0xb1, 0x56, 0x62, 0x71, 0x8c, 0xf0, 0xe2, 0xc4, + 0x68, 0xde, 0xce, 0xed, 0x98, 0x85, 0x2a, 0xf7, 0x2f, 0x01, 0x25, 0x52, 0x0f, 0xb4, 0xd4, 0x86, + 0x75, 0x27, 0x57, 0xaa, 0xaf, 0x0f, 0x65, 0x95, 0x26, 0x06, 0x2e, 0x5f, 0x29, 0x0b, 0x9d, 0xa3, + 0x74, 0xce, 0x24, 0x5d, 0xac, 0xe4, 0xe8, 0x43, 0xa9, 0xd2, 0x4b, 0x7c, 0x35, 0x33, 0x73, 0xb7, + 0x2e, 0x78, 0xfb, 0x10, 0xa9, 0x6c, 0xfd, 0x15, 0x89, 0x5d, 0xea, 0x4f, 0x4f, 0x47, 0x26, 0x3a, + 0x1b, 0x99, 0xe8, 0xfb, 0xc8, 0x44, 0xc7, 0x63, 0xb3, 0x70, 0x36, 0x36, 0x0b, 0x5f, 0xc7, 0x66, + 0xe1, 0x45, 0x8d, 0xb9, 0xaa, 0xd3, 0xdf, 0xb7, 0x1d, 0xde, 0xd3, 0x9e, 0x1e, 0xa8, 0x01, 0x17, + 0xaf, 0xf5, 0xba, 0xea, 0x70, 0x01, 0xe4, 0x30, 0x55, 0x57, 0x43, 0x1f, 0xe4, 0xfe, 0xbc, 0xfe, + 0x6f, 0x3e, 0xfc, 0x1d, 0x00, 0x00, 0xff, 0xff, 0x91, 0xb5, 0xe7, 0x28, 0xee, 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 { + // RegisterFeeShare registers a new contract for receiving transaction fees + RegisterFeeShare(ctx context.Context, in *MsgRegisterFeeShare, opts ...grpc.CallOption) (*MsgRegisterFeeShareResponse, error) + // UpdateFeeShare updates the withdrawer address of a FeeShare + UpdateFeeShare(ctx context.Context, in *MsgUpdateFeeShare, opts ...grpc.CallOption) (*MsgUpdateFeeShareResponse, error) + // CancelFeeShare cancels a contract's fee registration and further receival + // of transaction fees + CancelFeeShare(ctx context.Context, in *MsgCancelFeeShare, opts ...grpc.CallOption) (*MsgCancelFeeShareResponse, error) + // Update the params of the module through gov v1 type. + UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) RegisterFeeShare(ctx context.Context, in *MsgRegisterFeeShare, opts ...grpc.CallOption) (*MsgRegisterFeeShareResponse, error) { + out := new(MsgRegisterFeeShareResponse) + err := c.cc.Invoke(ctx, "/terp.feeshare.v1.Msg/RegisterFeeShare", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) UpdateFeeShare(ctx context.Context, in *MsgUpdateFeeShare, opts ...grpc.CallOption) (*MsgUpdateFeeShareResponse, error) { + out := new(MsgUpdateFeeShareResponse) + err := c.cc.Invoke(ctx, "/terp.feeshare.v1.Msg/UpdateFeeShare", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) CancelFeeShare(ctx context.Context, in *MsgCancelFeeShare, opts ...grpc.CallOption) (*MsgCancelFeeShareResponse, error) { + out := new(MsgCancelFeeShareResponse) + err := c.cc.Invoke(ctx, "/terp.feeshare.v1.Msg/CancelFeeShare", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { + out := new(MsgUpdateParamsResponse) + err := c.cc.Invoke(ctx, "/terp.feeshare.v1.Msg/UpdateParams", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + // RegisterFeeShare registers a new contract for receiving transaction fees + RegisterFeeShare(context.Context, *MsgRegisterFeeShare) (*MsgRegisterFeeShareResponse, error) + // UpdateFeeShare updates the withdrawer address of a FeeShare + UpdateFeeShare(context.Context, *MsgUpdateFeeShare) (*MsgUpdateFeeShareResponse, error) + // CancelFeeShare cancels a contract's fee registration and further receival + // of transaction fees + CancelFeeShare(context.Context, *MsgCancelFeeShare) (*MsgCancelFeeShareResponse, error) + // Update the params of the module through gov v1 type. + UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) RegisterFeeShare(ctx context.Context, req *MsgRegisterFeeShare) (*MsgRegisterFeeShareResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RegisterFeeShare not implemented") +} +func (*UnimplementedMsgServer) UpdateFeeShare(ctx context.Context, req *MsgUpdateFeeShare) (*MsgUpdateFeeShareResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateFeeShare not implemented") +} +func (*UnimplementedMsgServer) CancelFeeShare(ctx context.Context, req *MsgCancelFeeShare) (*MsgCancelFeeShareResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CancelFeeShare not implemented") +} +func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_RegisterFeeShare_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgRegisterFeeShare) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).RegisterFeeShare(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/terp.feeshare.v1.Msg/RegisterFeeShare", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).RegisterFeeShare(ctx, req.(*MsgRegisterFeeShare)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_UpdateFeeShare_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateFeeShare) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdateFeeShare(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/terp.feeshare.v1.Msg/UpdateFeeShare", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateFeeShare(ctx, req.(*MsgUpdateFeeShare)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_CancelFeeShare_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgCancelFeeShare) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).CancelFeeShare(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/terp.feeshare.v1.Msg/CancelFeeShare", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).CancelFeeShare(ctx, req.(*MsgCancelFeeShare)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateParams) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdateParams(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/terp.feeshare.v1.Msg/UpdateParams", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "terp.feeshare.v1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "RegisterFeeShare", + Handler: _Msg_RegisterFeeShare_Handler, + }, + { + MethodName: "UpdateFeeShare", + Handler: _Msg_UpdateFeeShare_Handler, + }, + { + MethodName: "CancelFeeShare", + Handler: _Msg_CancelFeeShare_Handler, + }, + { + MethodName: "UpdateParams", + Handler: _Msg_UpdateParams_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "terp/feeshare/v1/tx.proto", +} + +func (m *MsgRegisterFeeShare) 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 *MsgRegisterFeeShare) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgRegisterFeeShare) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.WithdrawerAddress) > 0 { + i -= len(m.WithdrawerAddress) + copy(dAtA[i:], m.WithdrawerAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.WithdrawerAddress))) + i-- + dAtA[i] = 0x1a + } + if len(m.DeployerAddress) > 0 { + i -= len(m.DeployerAddress) + copy(dAtA[i:], m.DeployerAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.DeployerAddress))) + i-- + dAtA[i] = 0x12 + } + if len(m.ContractAddress) > 0 { + i -= len(m.ContractAddress) + copy(dAtA[i:], m.ContractAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.ContractAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgRegisterFeeShareResponse) 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 *MsgRegisterFeeShareResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgRegisterFeeShareResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgUpdateFeeShare) 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 *MsgUpdateFeeShare) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateFeeShare) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.WithdrawerAddress) > 0 { + i -= len(m.WithdrawerAddress) + copy(dAtA[i:], m.WithdrawerAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.WithdrawerAddress))) + i-- + dAtA[i] = 0x1a + } + if len(m.DeployerAddress) > 0 { + i -= len(m.DeployerAddress) + copy(dAtA[i:], m.DeployerAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.DeployerAddress))) + i-- + dAtA[i] = 0x12 + } + if len(m.ContractAddress) > 0 { + i -= len(m.ContractAddress) + copy(dAtA[i:], m.ContractAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.ContractAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateFeeShareResponse) 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 *MsgUpdateFeeShareResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateFeeShareResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgCancelFeeShare) 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 *MsgCancelFeeShare) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCancelFeeShare) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.DeployerAddress) > 0 { + i -= len(m.DeployerAddress) + copy(dAtA[i:], m.DeployerAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.DeployerAddress))) + i-- + dAtA[i] = 0x12 + } + if len(m.ContractAddress) > 0 { + i -= len(m.ContractAddress) + copy(dAtA[i:], m.ContractAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.ContractAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgCancelFeeShareResponse) 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 *MsgCancelFeeShareResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCancelFeeShareResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgUpdateParams) 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 *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParams) 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 = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateParamsResponse) 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 *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgRegisterFeeShare) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ContractAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.DeployerAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.WithdrawerAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgRegisterFeeShareResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgUpdateFeeShare) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ContractAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.DeployerAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.WithdrawerAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgUpdateFeeShareResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgCancelFeeShare) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ContractAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.DeployerAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgCancelFeeShareResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgUpdateParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Params.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgUpdateParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovTx(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTx(x uint64) (n int) { + return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgRegisterFeeShare) 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: MsgRegisterFeeShare: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgRegisterFeeShare: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", 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.ContractAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DeployerAddress", 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.DeployerAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WithdrawerAddress", 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.WithdrawerAddress = 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 *MsgRegisterFeeShareResponse) 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: MsgRegisterFeeShareResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgRegisterFeeShareResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdateFeeShare) 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: MsgUpdateFeeShare: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateFeeShare: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", 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.ContractAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DeployerAddress", 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.DeployerAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WithdrawerAddress", 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.WithdrawerAddress = 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 *MsgUpdateFeeShareResponse) 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: MsgUpdateFeeShareResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateFeeShareResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgCancelFeeShare) 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: MsgCancelFeeShare: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgCancelFeeShare: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", 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.ContractAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DeployerAddress", 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.DeployerAddress = 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 *MsgCancelFeeShareResponse) 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: MsgCancelFeeShareResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgCancelFeeShareResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdateParams) 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: MsgUpdateParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", 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.Authority = 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 err := m.Params.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 *MsgUpdateParamsResponse) 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: MsgUpdateParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTx(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTx + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTx + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTx + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/feeshare/types/tx.pb.gw.go b/x/feeshare/types/tx.pb.gw.go new file mode 100644 index 0000000..55822b3 --- /dev/null +++ b/x/feeshare/types/tx.pb.gw.go @@ -0,0 +1,337 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: terp/feeshare/v1/tx.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +var ( + filter_Msg_RegisterFeeShare_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Msg_RegisterFeeShare_0(ctx context.Context, marshaler runtime.Marshaler, client MsgClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq MsgRegisterFeeShare + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_RegisterFeeShare_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.RegisterFeeShare(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Msg_RegisterFeeShare_0(ctx context.Context, marshaler runtime.Marshaler, server MsgServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq MsgRegisterFeeShare + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_RegisterFeeShare_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.RegisterFeeShare(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_Msg_UpdateFeeShare_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Msg_UpdateFeeShare_0(ctx context.Context, marshaler runtime.Marshaler, client MsgClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq MsgUpdateFeeShare + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_UpdateFeeShare_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.UpdateFeeShare(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Msg_UpdateFeeShare_0(ctx context.Context, marshaler runtime.Marshaler, server MsgServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq MsgUpdateFeeShare + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_UpdateFeeShare_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.UpdateFeeShare(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_Msg_CancelFeeShare_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Msg_CancelFeeShare_0(ctx context.Context, marshaler runtime.Marshaler, client MsgClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq MsgCancelFeeShare + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_CancelFeeShare_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.CancelFeeShare(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Msg_CancelFeeShare_0(ctx context.Context, marshaler runtime.Marshaler, server MsgServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq MsgCancelFeeShare + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Msg_CancelFeeShare_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.CancelFeeShare(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterMsgHandlerServer registers the http handlers for service Msg to "mux". +// UnaryRPC :call MsgServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterMsgHandlerFromEndpoint instead. +func RegisterMsgHandlerServer(ctx context.Context, mux *runtime.ServeMux, server MsgServer) error { + + mux.Handle("POST", pattern_Msg_RegisterFeeShare_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Msg_RegisterFeeShare_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Msg_RegisterFeeShare_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_Msg_UpdateFeeShare_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Msg_UpdateFeeShare_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Msg_UpdateFeeShare_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_Msg_CancelFeeShare_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Msg_CancelFeeShare_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Msg_CancelFeeShare_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterMsgHandlerFromEndpoint is same as RegisterMsgHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterMsgHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterMsgHandler(ctx, mux, conn) +} + +// RegisterMsgHandler registers the http handlers for service Msg to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterMsgHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterMsgHandlerClient(ctx, mux, NewMsgClient(conn)) +} + +// RegisterMsgHandlerClient registers the http handlers for service Msg +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "MsgClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "MsgClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "MsgClient" to call the correct interceptors. +func RegisterMsgHandlerClient(ctx context.Context, mux *runtime.ServeMux, client MsgClient) error { + + mux.Handle("POST", pattern_Msg_RegisterFeeShare_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Msg_RegisterFeeShare_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Msg_RegisterFeeShare_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_Msg_UpdateFeeShare_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Msg_UpdateFeeShare_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Msg_UpdateFeeShare_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("POST", pattern_Msg_CancelFeeShare_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Msg_CancelFeeShare_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Msg_CancelFeeShare_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Msg_RegisterFeeShare_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"terp", "feeshare", "v1", "tx", "register_FeeShare"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Msg_UpdateFeeShare_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"terp", "feeshare", "v1", "tx", "update_FeeShare"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Msg_CancelFeeShare_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"terp", "feeshare", "v1", "tx", "cancel_FeeShare"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Msg_RegisterFeeShare_0 = runtime.ForwardResponseMessage + + forward_Msg_UpdateFeeShare_0 = runtime.ForwardResponseMessage + + forward_Msg_CancelFeeShare_0 = runtime.ForwardResponseMessage +) diff --git a/x/globalfee/README.md b/x/globalfee/README.md new file mode 100644 index 0000000..746d5c1 --- /dev/null +++ b/x/globalfee/README.md @@ -0,0 +1,5 @@ +# Global fee module + +The Global fee module was supplied by the great folks at [TGrade](https://github.com/confio/tgrade) 👋, with minor modifications. All credits and big thanks go to the original authors. + +More information about Cosmoshub fee system please check [here](../../docs/modules/globalfee.md). diff --git a/x/globalfee/alias.go b/x/globalfee/alias.go new file mode 100644 index 0000000..3a16d3a --- /dev/null +++ b/x/globalfee/alias.go @@ -0,0 +1,9 @@ +package globalfee + +import ( + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +const ( + ModuleName = types.ModuleName +) diff --git a/x/globalfee/ante/antetest/fee_test_setup.go.archive b/x/globalfee/ante/antetest/fee_test_setup.go.archive new file mode 100644 index 0000000..b504011 --- /dev/null +++ b/x/globalfee/ante/antetest/fee_test_setup.go.archive @@ -0,0 +1,122 @@ +package antetest + +import ( + "github.com/stretchr/testify/suite" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + xauthsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + "github.com/cosmos/cosmos-sdk/x/params/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + "github.com/terpnetwork/terp-core/app" + appparams "github.com/terpnetwork/terp-core/app/params" + "github.com/terpnetwork/terp-core/v2/x/globalfee" + gaiafeeante "github.com/terpnetwork/terp-core/v2/x/globalfee/ante" + globfeetypes "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +type IntegrationTestSuite struct { + suite.Suite + + app *app.App + ctx sdk.Context + clientCtx client.Context + txBuilder client.TxBuilder +} + +func (s *IntegrationTestSuite) SetupTest() { + app := app.Setup(s.T()) + ctx := app.BaseApp.NewContext(false, tmproto.Header{ + ChainID: "testing", + Height: 1, + }) + + encodingConfig := appparams.MakeEncodingConfig() + encodingConfig.Amino.RegisterConcrete(&testdata.TestMsg{}, "testdata.TestMsg", nil) + testdata.RegisterInterfaces(encodingConfig.InterfaceRegistry) + + s.app = app + s.ctx = ctx + s.clientCtx = client.Context{}.WithTxConfig(encodingConfig.TxConfig) +} + +func (s *IntegrationTestSuite) SetupTestGlobalFeeStoreAndMinGasPrice(minGasPrice []sdk.DecCoin, globalFeeParams *globfeetypes.Params) (gaiafeeante.FeeDecorator, sdk.AnteHandler) { + subspace := s.app.GetSubspace(globalfee.ModuleName) + subspace.SetParamSet(s.ctx, globalFeeParams) + s.ctx = s.ctx.WithMinGasPrices(minGasPrice).WithIsCheckTx(true) + + // set staking params + stakingParam := stakingtypes.DefaultParams() + stakingParam.BondDenom = "uatom" + stakingSubspace := s.SetupTestStakingSubspace(stakingParam) + + // TODO: We use keepers here. + // build fee decorator + feeDecorator := gaiafeeante.NewFeeDecorator(app.GetDefaultBypassFeeMessages(), subspace, stakingSubspace, uint64(1_000_000)) + + // chain fee decorator to antehandler + antehandler := sdk.ChainAnteDecorators(feeDecorator) + + return feeDecorator, antehandler +} + +// SetupTestStakingSubspace sets uatom as bond denom for the fee tests. +func (s *IntegrationTestSuite) SetupTestStakingSubspace(params stakingtypes.Params) types.Subspace { + s.app.GetSubspace(stakingtypes.ModuleName).SetParamSet(s.ctx, ¶ms) + return s.app.GetSubspace(stakingtypes.ModuleName) +} + +func (s *IntegrationTestSuite) CreateTestTx(privs []cryptotypes.PrivKey, accNums []uint64, accSeqs []uint64, chainID string) (xauthsigning.Tx, error) { + var sigsV2 []signing.SignatureV2 + for i, priv := range privs { + sigV2 := signing.SignatureV2{ + PubKey: priv.PubKey(), + Data: &signing.SingleSignatureData{ + SignMode: s.clientCtx.TxConfig.SignModeHandler().DefaultMode(), + Signature: nil, + }, + Sequence: accSeqs[i], + } + + sigsV2 = append(sigsV2, sigV2) + } + + if err := s.txBuilder.SetSignatures(sigsV2...); err != nil { + return nil, err + } + + sigsV2 = []signing.SignatureV2{} + for i, priv := range privs { + signerData := xauthsigning.SignerData{ + ChainID: chainID, + AccountNumber: accNums[i], + Sequence: accSeqs[i], + } + sigV2, err := tx.SignWithPrivKey( + s.clientCtx.TxConfig.SignModeHandler().DefaultMode(), + signerData, + s.txBuilder, + priv, + s.clientCtx.TxConfig, + accSeqs[i], + ) + if err != nil { + return nil, err + } + + sigsV2 = append(sigsV2, sigV2) + } + + if err := s.txBuilder.SetSignatures(sigsV2...); err != nil { + return nil, err + } + + return s.txBuilder.GetTx(), nil +} diff --git a/x/globalfee/ante/fee.go b/x/globalfee/ante/fee.go new file mode 100644 index 0000000..0f03279 --- /dev/null +++ b/x/globalfee/ante/fee.go @@ -0,0 +1,211 @@ +package ante + +import ( + "errors" + + tmstrings "github.com/cometbft/cometbft/libs/strings" + + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + + globalfeekeeper "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" +) + +// FeeWithBypassDecorator checks if the transaction's fee is at least as large +// as the local validator's minimum gasFee (defined in validator config) and global fee, and the fee denom should be in the global fees' denoms. +// +// If fee is too low, decorator returns error and tx is rejected from mempool. +// Note this only applies when ctx.CheckTx = true. If fee is high enough or not +// CheckTx, then call next AnteHandler. +// +// CONTRACT: Tx must implement FeeTx to use FeeDecorator +// If the tx msg type is one of the bypass msg types, the tx is valid even if the min fee is lower than normally required. +// If the bypass tx still carries fees, the fee denom should be the same as global fee required. + +var _ sdk.AnteDecorator = FeeDecorator{} + +type FeeDecorator struct { + BypassMinFeeMsgTypes []string + GlobalFeeKeeper globalfeekeeper.Keeper + StakingKeeper stakingkeeper.Keeper + MaxTotalBypassMinFeeMsgGasUsage uint64 +} + +func NewFeeDecorator(bypassMsgTypes []string, gfk globalfeekeeper.Keeper, sk stakingkeeper.Keeper, maxTotalBypassMinFeeMsgGasUsage uint64) FeeDecorator { + return FeeDecorator{ + BypassMinFeeMsgTypes: bypassMsgTypes, + GlobalFeeKeeper: gfk, + StakingKeeper: sk, + MaxTotalBypassMinFeeMsgGasUsage: maxTotalBypassMinFeeMsgGasUsage, + } +} + +// AnteHandle implements the AnteDecorator interface +func (mfd FeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { + feeTx, ok := tx.(sdk.FeeTx) + if !ok { + return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "Tx must implement the sdk.FeeTx interface") + } + + // Only check for minimum fees and global fee if the execution mode is CheckTx + if !ctx.IsCheckTx() || simulate { + return next(ctx, tx, simulate) + } + + // Sort fee tx's coins, zero coins in feeCoins are already removed + feeCoins := feeTx.GetFee().Sort() + gas := feeTx.GetGas() + msgs := feeTx.GetMsgs() + + // Get required Global Fee + requiredGlobalFees, err := mfd.GetGlobalFee(ctx, feeTx) + if err != nil { + return ctx, err + } + + // Get local minimum-gas-prices + localFees := GetMinGasPrice(ctx, int64(feeTx.GetGas())) + + // CombinedFeeRequirement should never be empty since + // global fee is set to its default value, i.e. 0uatom, if empty + combinedFeeRequirement := CombinedFeeRequirement(requiredGlobalFees, localFees) + if len(combinedFeeRequirement) == 0 { + return ctx, errorsmod.Wrapf(sdkerrors.ErrNotFound, "required fees are not setup.") + } + + nonZeroCoinFeesReq, zeroCoinFeesDenomReq := getNonZeroFees(combinedFeeRequirement) + + // feeCoinsNonZeroDenom contains non-zero denominations from the combinedFeeRequirement + // + // feeCoinsNoZeroDenom is used to check if the fees meets the requirement imposed by nonZeroCoinFeesReq + // when feeCoins does not contain zero coins' denoms in combinedFeeRequirement + feeCoinsNonZeroDenom, feeCoinsZeroDenom := splitCoinsByDenoms(feeCoins, zeroCoinFeesDenomReq) + + // Check that the fees are in expected denominations. + // if feeCoinsNoZeroDenom=[], DenomsSubsetOf returns true + // if feeCoinsNoZeroDenom is not empty, but nonZeroCoinFeesReq empty, return false + if !feeCoinsNonZeroDenom.DenomsSubsetOf(nonZeroCoinFeesReq) { + return ctx, errorsmod.Wrapf(sdkerrors.ErrInsufficientFee, "fee is not a subset of required fees; got %s, required: %s", feeCoins, combinedFeeRequirement) + } + + // Accept zero fee transactions only if both of the following statements are true: + // + // - the tx contains only message types that can bypass the minimum fee, + // see BypassMinFeeMsgTypes; + // - the total gas limit per message does not exceed MaxTotalBypassMinFeeMsgGasUsage, + // i.e., totalGas <= MaxTotalBypassMinFeeMsgGasUsage + // + // Otherwise, minimum fees and global fees are checked to prevent spam. + doesNotExceedMaxGasUsage := gas <= mfd.MaxTotalBypassMinFeeMsgGasUsage + allowedToBypassMinFee := mfd.ContainsOnlyBypassMinFeeMsgs(msgs) && doesNotExceedMaxGasUsage + + // Either the transaction contains at least one message of a type + // that cannot bypass the minimum fee or the total gas limit exceeds + // the imposed threshold. As a result, besides check the fees are in + // expected denominations, check the amounts are greater or equal than + // the expected amounts. + + // only check feeCoinsNoZeroDenom has coins IsAnyGTE than nonZeroCoinFeesReq + // when feeCoins does not contain denoms of zero denoms in combinedFeeRequirement + if !allowedToBypassMinFee && len(feeCoinsZeroDenom) == 0 { + // special case: when feeCoins=[] and there is zero coin in fee requirement + if len(feeCoins) == 0 && len(zeroCoinFeesDenomReq) != 0 { + return next(ctx, tx, simulate) + } + + // Check that the amounts of the fees are greater or equal than + // the expected amounts, i.e., at least one feeCoin amount must + // be greater or equal to one of the combined required fees. + + // if feeCoinsNoZeroDenom=[], return false + // if nonZeroCoinFeesReq=[], return false (this situation should not happen + // because when nonZeroCoinFeesReq empty, and DenomsSubsetOf check passed, + // the tx should already passed before) + if !feeCoinsNonZeroDenom.IsAnyGTE(nonZeroCoinFeesReq) { + return ctx, errorsmod.Wrapf(sdkerrors.ErrInsufficientFee, "insufficient fees; got: %s required: %s", feeCoins, combinedFeeRequirement) + } + } + + return next(ctx, tx, simulate) +} + +// GetGlobalFee returns the global fees for a given fee tx's gas +// (might also return 0denom if globalMinGasPrice is 0) +// sorted in ascending order. +// Note that ParamStoreKeyMinGasPrices type requires coins sorted. +func (mfd FeeDecorator) GetGlobalFee(ctx sdk.Context, feeTx sdk.FeeTx) (sdk.Coins, error) { + var ( + globalMinGasPrices sdk.DecCoins + err error + ) + + globalMinGasPrices = mfd.GlobalFeeKeeper.GetParams(ctx).MinimumGasPrices + + // global fee is empty set, set global fee to 0uatom + if len(globalMinGasPrices) == 0 { + globalMinGasPrices, err = mfd.DefaultZeroGlobalFee(ctx) + if err != nil { + return sdk.Coins{}, err + } + } + requiredGlobalFees := make(sdk.Coins, len(globalMinGasPrices)) + // Determine the required fees by multiplying each required minimum gas + // price by the gas limit, where fee = ceil(minGasPrice * gasLimit). + glDec := sdk.NewDec(int64(feeTx.GetGas())) + for i, gp := range globalMinGasPrices { + fee := gp.Amount.Mul(glDec) + requiredGlobalFees[i] = sdk.NewCoin(gp.Denom, fee.Ceil().RoundInt()) + } + + return requiredGlobalFees.Sort(), nil +} + +func (mfd FeeDecorator) DefaultZeroGlobalFee(ctx sdk.Context) ([]sdk.DecCoin, error) { + bondDenom := mfd.getBondDenom(ctx) + if bondDenom == "" { + return nil, errors.New("empty staking bond denomination") + } + + return []sdk.DecCoin{sdk.NewDecCoinFromDec(bondDenom, sdk.NewDec(0))}, nil +} + +func (mfd FeeDecorator) getBondDenom(ctx sdk.Context) string { + return mfd.StakingKeeper.BondDenom(ctx) +} + +// ContainsOnlyBypassMinFeeMsgs returns true if all the given msgs type are listed +// in the BypassMinFeeMsgTypes of the FeeDecorator. +func (mfd FeeDecorator) ContainsOnlyBypassMinFeeMsgs(msgs []sdk.Msg) bool { + for _, msg := range msgs { + if tmstrings.StringInSlice(sdk.MsgTypeURL(msg), mfd.BypassMinFeeMsgTypes) { + continue + } + return false + } + + return true +} + +// GetMinGasPrice returns the validator's minimum gas prices +// fees given a gas limit +func GetMinGasPrice(ctx sdk.Context, gasLimit int64) sdk.Coins { + minGasPrices := ctx.MinGasPrices() + // special case: if minGasPrices=[], requiredFees=[] + if minGasPrices.IsZero() { + return sdk.Coins{} + } + + requiredFees := make(sdk.Coins, len(minGasPrices)) + // Determine the required fees by multiplying each required minimum gas + // price by the gas limit, where fee = ceil(minGasPrice * gasLimit). + glDec := sdk.NewDec(gasLimit) + for i, gp := range minGasPrices { + fee := gp.Amount.Mul(glDec) + requiredFees[i] = sdk.NewCoin(gp.Denom, fee.Ceil().RoundInt()) + } + + return requiredFees.Sort() +} diff --git a/x/globalfee/ante/fee_utils.go b/x/globalfee/ante/fee_utils.go new file mode 100644 index 0000000..b3d5e2c --- /dev/null +++ b/x/globalfee/ante/fee_utils.go @@ -0,0 +1,110 @@ +package ante + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// ContainZeroCoins returns true if the given coins are empty or contain zero coins, +// Note that the coins denoms must be validated, see sdk.ValidateDenom +func ContainZeroCoins(coins sdk.Coins) bool { + if len(coins) == 0 { + return true + } + for _, coin := range coins { + if coin.IsZero() { + return true + } + } + + return false +} + +// CombinedFeeRequirement returns the global fee and min_gas_price combined and sorted. +// Both globalFees and minGasPrices must be valid, but CombinedFeeRequirement +// does not validate them, so it may return 0denom. +// if globalfee is empty, CombinedFeeRequirement return sdk.Coins{} +func CombinedFeeRequirement(globalFees, minGasPrices sdk.Coins) sdk.Coins { + // empty min_gas_price + if len(minGasPrices) == 0 { + return globalFees + } + // empty global fee is not possible if we set default global fee + if len(globalFees) == 0 && len(minGasPrices) != 0 { + return sdk.Coins{} + } + + // if min_gas_price denom is in globalfee, and the amount is higher than globalfee, add min_gas_price to allFees + var allFees sdk.Coins + for _, fee := range globalFees { + // min_gas_price denom in global fee + ok, c := Find(minGasPrices, fee.Denom) + if ok && c.Amount.GT(fee.Amount) { + allFees = append(allFees, c) + } else { + allFees = append(allFees, fee) + } + } + + return allFees.Sort() +} + +// Find replaces the functionality of Coins.Find from SDK v0.46.x +func Find(coins sdk.Coins, denom string) (bool, sdk.Coin) { + switch len(coins) { + case 0: + return false, sdk.Coin{} + + case 1: + coin := coins[0] + if coin.Denom == denom { + return true, coin + } + return false, sdk.Coin{} + + default: + midIdx := len(coins) / 2 // 2:1, 3:1, 4:2 + coin := coins[midIdx] + switch { + case denom < coin.Denom: + return Find(coins[:midIdx], denom) + case denom == coin.Denom: + return true, coin + default: + return Find(coins[midIdx+1:], denom) + } + } +} + +// splitCoinsByDenoms returns the given coins split in two whether +// their demon is or isn't found in the given denom map. +func splitCoinsByDenoms(feeCoins sdk.Coins, denomMap map[string]bool) (sdk.Coins, sdk.Coins) { + feeCoinsNonZeroDenom, feeCoinsZeroDenom := sdk.Coins{}, sdk.Coins{} + + for _, fc := range feeCoins { + _, found := denomMap[fc.Denom] + if found { + feeCoinsZeroDenom = append(feeCoinsZeroDenom, fc) + } else { + feeCoinsNonZeroDenom = append(feeCoinsNonZeroDenom, fc) + } + } + + return feeCoinsNonZeroDenom.Sort(), feeCoinsZeroDenom.Sort() +} + +// getNonZeroFees returns the given fees nonzero coins +// and a map storing the zero coins's denoms +func getNonZeroFees(fees sdk.Coins) (sdk.Coins, map[string]bool) { + requiredFeesNonZero := sdk.Coins{} + requiredFeesZeroDenom := map[string]bool{} + + for _, gf := range fees { + if gf.IsZero() { + requiredFeesZeroDenom[gf.Denom] = true + } else { + requiredFeesNonZero = append(requiredFeesNonZero, gf) + } + } + + return requiredFeesNonZero.Sort(), requiredFeesZeroDenom +} diff --git a/x/globalfee/ante/fee_utils_test.go b/x/globalfee/ante/fee_utils_test.go new file mode 100644 index 0000000..f3af633 --- /dev/null +++ b/x/globalfee/ante/fee_utils_test.go @@ -0,0 +1,299 @@ +package ante + +import ( + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func TestContainZeroCoins(t *testing.T) { + zeroCoin1 := sdk.NewCoin("photon", sdk.ZeroInt()) + zeroCoin2 := sdk.NewCoin("stake", sdk.ZeroInt()) + coin1 := sdk.NewCoin("photon", sdk.NewInt(1)) + coin2 := sdk.NewCoin("stake", sdk.NewInt(2)) + coin3 := sdk.NewCoin("quark", sdk.NewInt(3)) + // coins must be valid !!! + coinsEmpty := sdk.Coins{} + coinsNonEmpty := sdk.Coins{coin1, coin2} + coinsCointainZero := sdk.Coins{coin1, zeroCoin2} + coinsCointainTwoZero := sdk.Coins{zeroCoin1, zeroCoin2, coin3} + coinsAllZero := sdk.Coins{zeroCoin1, zeroCoin2} + + tests := []struct { + c sdk.Coins + ok bool + }{ + { + coinsEmpty, + true, + }, + { + coinsNonEmpty, + false, + }, + { + coinsCointainZero, + true, + }, + { + coinsCointainTwoZero, + true, + }, + { + coinsAllZero, + true, + }, + } + + for _, test := range tests { + ok := ContainZeroCoins(test.c) + require.Equal(t, test.ok, ok) + } +} + +// Note that in a real Gaia deployment all zero coins can be removed from minGasPrice. +// This sanitizing happens when the minGasPrice is set into the context. +// (see baseapp.SetMinGasPrices in gaia/cmd/root.go line 221) +func TestCombinedFeeRequirement(t *testing.T) { + zeroCoin1 := sdk.NewCoin("photon", sdk.ZeroInt()) + zeroCoin2 := sdk.NewCoin("stake", sdk.ZeroInt()) + zeroCoin3 := sdk.NewCoin("quark", sdk.ZeroInt()) + coin1 := sdk.NewCoin("photon", sdk.NewInt(1)) + coin2 := sdk.NewCoin("stake", sdk.NewInt(2)) + coin1High := sdk.NewCoin("photon", sdk.NewInt(10)) + coin2High := sdk.NewCoin("stake", sdk.NewInt(20)) + coinNewDenom1 := sdk.NewCoin("Newphoton", sdk.NewInt(1)) + coinNewDenom2 := sdk.NewCoin("Newstake", sdk.NewInt(1)) + // coins must be valid !!! and sorted!!! + coinsEmpty := sdk.Coins{} + coinsNonEmpty := sdk.Coins{coin1, coin2}.Sort() + coinsNonEmptyHigh := sdk.Coins{coin1High, coin2High}.Sort() + coinsNonEmptyOneHigh := sdk.Coins{coin1High, coin2}.Sort() + coinsNewDenom := sdk.Coins{coinNewDenom1, coinNewDenom2}.Sort() + coinsNewOldDenom := sdk.Coins{coin1, coinNewDenom1}.Sort() + coinsNewOldDenomHigh := sdk.Coins{coin1High, coinNewDenom1}.Sort() + coinsCointainZero := sdk.Coins{coin1, zeroCoin2}.Sort() + coinsCointainZeroNewDenom := sdk.Coins{coin1, zeroCoin3}.Sort() + coinsAllZero := sdk.Coins{zeroCoin1, zeroCoin2}.Sort() + tests := map[string]struct { + cGlobal sdk.Coins + c sdk.Coins + combined sdk.Coins + }{ + "global fee empty, min fee empty, combined fee empty": { + cGlobal: coinsEmpty, + c: coinsEmpty, + combined: coinsEmpty, + }, + "global fee empty, min fee nonempty, combined fee empty": { + cGlobal: coinsEmpty, + c: coinsNonEmpty, + combined: coinsEmpty, + }, + "global fee nonempty, min fee empty, combined fee = global fee": { + cGlobal: coinsNonEmpty, + c: coinsNonEmpty, + combined: coinsNonEmpty, + }, + "global fee and min fee have overlapping denom, min fees amounts are all higher": { + cGlobal: coinsNonEmpty, + c: coinsNonEmptyHigh, + combined: coinsNonEmptyHigh, + }, + "global fee and min fee have overlapping denom, one of min fees amounts is higher": { + cGlobal: coinsNonEmpty, + c: coinsNonEmptyOneHigh, + combined: coinsNonEmptyOneHigh, + }, + "global fee and min fee have no overlapping denom, combined fee = global fee": { + cGlobal: coinsNonEmpty, + c: coinsNewDenom, + combined: coinsNonEmpty, + }, + "global fees and min fees have partial overlapping denom, min fee amount <= global fee amount, combined fees = global fees": { + cGlobal: coinsNonEmpty, + c: coinsNewOldDenom, + combined: coinsNonEmpty, + }, + "global fees and min fees have partial overlapping denom, one min fee amount > global fee amount, combined fee = overlapping highest": { + cGlobal: coinsNonEmpty, + c: coinsNewOldDenomHigh, + combined: sdk.Coins{coin1High, coin2}, + }, + "global fees have zero fees, min fees have overlapping non-zero fees, combined fees = overlapping highest": { + cGlobal: coinsCointainZero, + c: coinsNonEmpty, + combined: sdk.Coins{coin1, coin2}, + }, + "global fees have zero fees, min fees have overlapping zero fees": { + cGlobal: coinsCointainZero, + c: coinsCointainZero, + combined: coinsCointainZero, + }, + "global fees have zero fees, min fees have non-overlapping zero fees": { + cGlobal: coinsCointainZero, + c: coinsCointainZeroNewDenom, + combined: coinsCointainZero, + }, + "global fees are all zero fees, min fees have overlapping zero fees": { + cGlobal: coinsAllZero, + c: coinsAllZero, + combined: coinsAllZero, + }, + "global fees are all zero fees, min fees have overlapping non-zero fees, combined fee = overlapping highest": { + cGlobal: coinsAllZero, + c: coinsCointainZeroNewDenom, + combined: sdk.Coins{coin1, zeroCoin2}, + }, + "global fees are all zero fees, fees have one overlapping non-zero fee": { + cGlobal: coinsAllZero, + c: coinsCointainZero, + combined: coinsCointainZero, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + allFees := CombinedFeeRequirement(test.cGlobal, test.c) + require.Equal(t, test.combined, allFees) + }) + } +} + +func TestSplitCoinsByDenoms(t *testing.T) { + zeroGlobalFeesDenom0 := map[string]bool{} + zeroGlobalFeesDenom1 := map[string]bool{ + "uatom": true, + "photon": true, + } + zeroGlobalFeesDenom2 := map[string]bool{ + "uatom": true, + } + zeroGlobalFeesDenom3 := map[string]bool{ + "stake": true, + } + + photon := sdk.NewCoin("photon", sdk.OneInt()) + uatom := sdk.NewCoin("uatom", sdk.OneInt()) + feeCoins := sdk.NewCoins(photon, uatom) + + tests := map[string]struct { + feeCoins sdk.Coins + zeroGlobalFeesDenom map[string]bool + expectedNonZeroCoins sdk.Coins + expectedZeroCoins sdk.Coins + }{ + "no zero coins in global fees": { + feeCoins: feeCoins, + zeroGlobalFeesDenom: zeroGlobalFeesDenom0, + expectedNonZeroCoins: feeCoins, + expectedZeroCoins: sdk.Coins{}, + }, + "no split of fee coins": { + feeCoins: feeCoins, + zeroGlobalFeesDenom: zeroGlobalFeesDenom3, + expectedNonZeroCoins: feeCoins, + expectedZeroCoins: sdk.Coins{}, + }, + "split the fee coins": { + feeCoins: feeCoins, + zeroGlobalFeesDenom: zeroGlobalFeesDenom2, + expectedNonZeroCoins: sdk.NewCoins(photon), + expectedZeroCoins: sdk.NewCoins(uatom), + }, + "remove all of the fee coins": { + feeCoins: feeCoins, + zeroGlobalFeesDenom: zeroGlobalFeesDenom1, + expectedNonZeroCoins: sdk.Coins{}, + expectedZeroCoins: feeCoins, + }, + "fee coins are empty": { + feeCoins: sdk.Coins{}, + zeroGlobalFeesDenom: zeroGlobalFeesDenom1, + expectedNonZeroCoins: sdk.Coins{}, + expectedZeroCoins: sdk.Coins{}, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + feeCoinsNoZeroDenoms, feeCoinsZeroDenoms := splitCoinsByDenoms(test.feeCoins, test.zeroGlobalFeesDenom) + require.Equal(t, test.expectedNonZeroCoins, feeCoinsNoZeroDenoms) + require.Equal(t, test.expectedZeroCoins, feeCoinsZeroDenoms) + }) + } +} + +func TestSplitGlobalFees(t *testing.T) { + photon0 := sdk.NewCoin("photon", sdk.ZeroInt()) + uatom0 := sdk.NewCoin("uatom", sdk.ZeroInt()) + photon1 := sdk.NewCoin("photon", sdk.OneInt()) + uatom1 := sdk.NewCoin("uatom", sdk.OneInt()) + + globalFeesEmpty := sdk.Coins{} + globalFees := sdk.Coins{photon1, uatom1}.Sort() + globalFeesZeroCoins := sdk.Coins{photon0, uatom0}.Sort() + globalFeesMix := sdk.Coins{photon0, uatom1}.Sort() + + tests := map[string]struct { + globalfees sdk.Coins + zeroGlobalFeesDenom map[string]bool + globalfeesNonZero sdk.Coins + }{ + "empty global fees": { + globalfees: globalFeesEmpty, + zeroGlobalFeesDenom: map[string]bool{}, + globalfeesNonZero: sdk.Coins{}, + }, + "nonzero coins global fees": { + globalfees: globalFees, + zeroGlobalFeesDenom: map[string]bool{}, + globalfeesNonZero: globalFees, + }, + "zero coins global fees": { + globalfees: globalFeesZeroCoins, + zeroGlobalFeesDenom: map[string]bool{ + "photon": true, + "uatom": true, + }, + globalfeesNonZero: sdk.Coins{}, + }, + "mix zero, nonzero coins global fees": { + globalfees: globalFeesMix, + zeroGlobalFeesDenom: map[string]bool{ + "photon": true, + }, + globalfeesNonZero: sdk.NewCoins(uatom1), + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + nonZeroCoins, zeroCoinsMap := getNonZeroFees(test.globalfees) + require.True(t, nonZeroCoins.IsEqual(test.globalfeesNonZero)) + require.True(t, equalMap(zeroCoinsMap, test.zeroGlobalFeesDenom)) + }) + } +} + +func equalMap(a, b map[string]bool) bool { + if len(a) != len(b) { + return false + } + if len(a) == 0 && len(b) == 0 { + return true + } + if len(a) == 0 { + return false + } + + for k := range a { + if _, ok := b[k]; !ok { + return false + } + } + + return true +} diff --git a/x/globalfee/client/cli/query.go b/x/globalfee/client/cli/query.go new file mode 100644 index 0000000..415a1cb --- /dev/null +++ b/x/globalfee/client/cli/query.go @@ -0,0 +1,49 @@ +package cli + +import ( + "github.com/spf13/cobra" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +func GetQueryCmd() *cobra.Command { + queryCmd := &cobra.Command{ + Use: types.ModuleName, + Short: "Querying commands for the global fee module", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + queryCmd.AddCommand( + GetCmdShowMinimumGasPrices(), + ) + return queryCmd +} + +func GetCmdShowMinimumGasPrices() *cobra.Command { + cmd := &cobra.Command{ + Use: "minimum-gas-prices", + Short: "Show minimum gas prices", + Long: "Show all minimum gas prices", + Aliases: []string{"min"}, + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + + queryClient := types.NewQueryClient(clientCtx) + res, err := queryClient.MinimumGasPrices(cmd.Context(), &types.QueryMinimumGasPricesRequest{}) + if err != nil { + return err + } + return clientCtx.PrintProto(res) + }, + } + flags.AddQueryFlagsToCmd(cmd) + return cmd +} diff --git a/x/globalfee/genesis_test.go b/x/globalfee/genesis_test.go new file mode 100644 index 0000000..79e4ce1 --- /dev/null +++ b/x/globalfee/genesis_test.go @@ -0,0 +1,131 @@ +package globalfee + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + dbm "github.com/cometbft/cometbft-db" + "github.com/cometbft/cometbft/libs/log" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + + "github.com/cosmos/cosmos-sdk/store" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + + appparams "github.com/terpnetwork/terp-core/v2/app/params" + globalfeekeeper "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +func TestDefaultGenesis(t *testing.T) { + encCfg := appparams.MakeEncodingConfig() + gotJSON := AppModuleBasic{}.DefaultGenesis(encCfg.Marshaler) + assert.JSONEq(t, `{"params":{"minimum_gas_prices":[]}}`, string(gotJSON), string(gotJSON)) +} + +func TestValidateGenesis(t *testing.T) { + encCfg := appparams.MakeEncodingConfig() + specs := map[string]struct { + src string + expErr bool + }{ + "all good": { + src: `{"params":{"minimum_gas_prices":[{"denom":"ALX", "amount":"1"}]}}`, + }, + "empty minimum": { + src: `{"params":{"minimum_gas_prices":[]}}`, + }, + "minimum not set": { + src: `{"params":{}}`, + }, + "zero amount allowed": { + src: `{"params":{"minimum_gas_prices":[{"denom":"ALX", "amount":"0"}]}}`, + expErr: false, + }, + "duplicate denoms not allowed": { + src: `{"params":{"minimum_gas_prices":[{"denom":"ALX", "amount":"1"},{"denom":"ALX", "amount":"2"}]}}`, + expErr: true, + }, + "negative amounts not allowed": { + src: `{"params":{"minimum_gas_prices":[{"denom":"ALX", "amount":"-1"}]}}`, + expErr: true, + }, + "denom must be sorted": { + src: `{"params":{"minimum_gas_prices":[{"denom":"ZLX", "amount":"1"},{"denom":"ALX", "amount":"2"}]}}`, + expErr: true, + }, + "sorted denoms is allowed": { + src: `{"params":{"minimum_gas_prices":[{"denom":"ALX", "amount":"1"},{"denom":"ZLX", "amount":"2"}]}}`, + expErr: false, + }, + } + for name, spec := range specs { + t.Run(name, func(t *testing.T) { + gotErr := AppModuleBasic{}.ValidateGenesis(encCfg.Marshaler, nil, []byte(spec.src)) + if spec.expErr { + require.Error(t, gotErr) + return + } + require.NoError(t, gotErr) + }) + } +} + +func TestInitExportGenesis(t *testing.T) { + specs := map[string]struct { + src string + exp types.GenesisState + }{ + "single fee": { + src: `{"params":{"minimum_gas_prices":[{"denom":"ALX", "amount":"1"}]}}`, + exp: types.GenesisState{Params: types.Params{MinimumGasPrices: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.NewInt(1)))}}, + }, + "multiple fee options": { + src: `{"params":{"minimum_gas_prices":[{"denom":"ALX", "amount":"1"}, {"denom":"BLX", "amount":"0.001"}]}}`, + exp: types.GenesisState{Params: types.Params{MinimumGasPrices: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.NewInt(1)), + sdk.NewDecCoinFromDec("BLX", sdk.NewDecWithPrec(1, 3)))}}, + }, + "no fee set": { + src: `{"params":{}}`, + exp: types.GenesisState{Params: types.Params{MinimumGasPrices: sdk.DecCoins{}}}, + }, + } + for name, spec := range specs { + t.Run(name, func(t *testing.T) { + ctx, encCfg, keeper := setupTestStore(t) + m := NewAppModule(encCfg.Marshaler, keeper, "stake") + m.InitGenesis(ctx, encCfg.Marshaler, []byte(spec.src)) + gotJSON := m.ExportGenesis(ctx, encCfg.Marshaler) + var got types.GenesisState + t.Log(got) + require.NoError(t, encCfg.Marshaler.UnmarshalJSON(gotJSON, &got)) + assert.Equal(t, spec.exp, got, string(gotJSON)) + }) + } +} + +func setupTestStore(t *testing.T) (sdk.Context, appparams.EncodingConfig, globalfeekeeper.Keeper) { + t.Helper() + db := dbm.NewMemDB() + ms := store.NewCommitMultiStore(db) + encCfg := appparams.MakeEncodingConfig() + keyParams := sdk.NewKVStoreKey(types.StoreKey) + // globalfeeParams := sdk.NewKVStoreKey(types.StoreKey) + // tkeyParams := sdk.NewTransientStoreKey(paramstypes.TStoreKey) + ms.MountStoreWithDB(keyParams, storetypes.StoreTypeIAVL, db) + // ms.MountStoreWithDB(tkeyParams, storetypes.StoreTypeTransient, db) + require.NoError(t, ms.LoadLatestVersion()) + + globalfeeKeeper := globalfeekeeper.NewKeeper(encCfg.Marshaler, keyParams, "terp1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8q4dsrv") + + ctx := sdk.NewContext(ms, tmproto.Header{ + Height: 1234567, + Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC), + ChainID: "testing", + }, false, log.NewNopLogger()) + + return ctx, encCfg, globalfeeKeeper +} diff --git a/x/globalfee/keeper/exported/exported.go b/x/globalfee/keeper/exported/exported.go new file mode 100644 index 0000000..000114e --- /dev/null +++ b/x/globalfee/keeper/exported/exported.go @@ -0,0 +1,18 @@ +package exported + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +type ( + ParamSet = paramtypes.ParamSet + + // Subspace defines an interface that implements the legacy x/params Subspace + // type. + // + // NOTE: This is used solely for migration of x/params managed parameters. + Subspace interface { + GetParamSet(ctx sdk.Context, ps ParamSet) + } +) diff --git a/x/globalfee/keeper/keeper.go b/x/globalfee/keeper/keeper.go new file mode 100644 index 0000000..6919f83 --- /dev/null +++ b/x/globalfee/keeper/keeper.go @@ -0,0 +1,61 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +// Keeper of the globalfee store +type Keeper struct { + cdc codec.BinaryCodec + storeKey storetypes.StoreKey + + // the address capable of executing a MsgUpdateParams message. Typically, this + // should be the x/gov module account. + authority string +} + +func NewKeeper( + cdc codec.BinaryCodec, + key storetypes.StoreKey, + authority string, +) Keeper { + return Keeper{ + cdc: cdc, + storeKey: key, + authority: authority, + } +} + +// GetAuthority returns the x/globalfee module's authority. +func (k Keeper) GetAuthority() string { + return k.authority +} + +// SetParams sets the x/globalfee module parameters. +func (k Keeper) SetParams(ctx sdk.Context, p types.Params) error { + if err := p.Validate(); err != nil { + return err + } + + store := ctx.KVStore(k.storeKey) + bz := k.cdc.MustMarshal(&p) + store.Set(types.ParamsKey, bz) + + return nil +} + +// GetParams returns the current x/globalfee module parameters. +func (k Keeper) GetParams(ctx sdk.Context) (p types.Params) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ParamsKey) + if bz == nil { + return p + } + + k.cdc.MustUnmarshal(bz, &p) + return p +} diff --git a/x/globalfee/keeper/migrator.go b/x/globalfee/keeper/migrator.go new file mode 100644 index 0000000..747b1be --- /dev/null +++ b/x/globalfee/keeper/migrator.go @@ -0,0 +1,28 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + v2 "github.com/terpnetwork/terp-core/v2/x/globalfee/migrations/v2" +) + +// Migrator is a struct for handling in-place state migrations. +type Migrator struct { + keeper Keeper + bondDenom string +} + +func NewMigrator(k Keeper, bondDenom string) Migrator { + return Migrator{ + keeper: k, + bondDenom: bondDenom, + } +} + +// Migrate1to2 migrates the x/mint module state from the consensus version 1 to +// version 2. Specifically, it takes the parameters that are currently stored +// and managed by the x/params modules and stores them directly into the x/mint +// module state. +func (m Migrator) Migrate1to2(ctx sdk.Context) error { + return v2.Migrate(ctx, ctx.KVStore(m.keeper.storeKey), m.keeper.cdc, m.bondDenom) +} diff --git a/x/globalfee/keeper/msg_server.go b/x/globalfee/keeper/msg_server.go new file mode 100644 index 0000000..cef1608 --- /dev/null +++ b/x/globalfee/keeper/msg_server.go @@ -0,0 +1,38 @@ +package keeper + +import ( + "context" + + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +var _ types.MsgServer = msgServer{} + +type msgServer struct { + Keeper +} + +// NewMsgServerImpl returns an implementation of the x/mint MsgServer interface. +func NewMsgServerImpl(k Keeper) types.MsgServer { + return &msgServer{ + Keeper: k, + } +} + +func (ms msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if ms.authority != req.Authority { + return nil, errorsmod.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", ms.authority, req.Authority) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + if err := ms.SetParams(ctx, req.Params); err != nil { + return nil, err + } + + return &types.MsgUpdateParamsResponse{}, nil +} diff --git a/x/globalfee/migrations/v2/migrate.go b/x/globalfee/migrations/v2/migrate.go new file mode 100644 index 0000000..aa0a219 --- /dev/null +++ b/x/globalfee/migrations/v2/migrate.go @@ -0,0 +1,45 @@ +package v2 + +import ( + "fmt" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +const ( + ModuleName = "globalfee" +) + +var ParamsKey = []byte{0x00} + +// Migrate migrates the x/globalfee module state from the consensus version 1 to +// version 2. Specifically, it takes the parameters that are currently stored +// and managed by the x/params modules and stores them directly into the x/globalfee +// module state. +func Migrate( + _ sdk.Context, + store sdk.KVStore, + cdc codec.BinaryCodec, + bondDenom string, +) error { + // https://api.terp.network/gaia/globalfee/v1beta1/minimum_gas_prices + currParams := types.Params{ + MinimumGasPrices: sdk.DecCoins{ + // 0.075000000000000000 / uterpx + sdk.NewDecCoinFromDec(bondDenom, sdk.NewDecWithPrec(75, 3)), + }, + } + + fmt.Printf("migrating %s params: %+v\n", ModuleName, currParams) + + if err := currParams.Validate(); err != nil { + return err + } + bz := cdc.MustMarshal(&currParams) + store.Set(ParamsKey, bz) + + return nil +} diff --git a/x/globalfee/migrations/v2/migrator_test.go b/x/globalfee/migrations/v2/migrator_test.go new file mode 100644 index 0000000..f2a9ed6 --- /dev/null +++ b/x/globalfee/migrations/v2/migrator_test.go @@ -0,0 +1,76 @@ +package v2_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/testutil" + sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + + "github.com/terpnetwork/terp-core/v2/x/globalfee" + "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper/exported" + v2 "github.com/terpnetwork/terp-core/v2/x/globalfee/migrations/v2" + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +//lint:ignore U1000 disregard lint check +type mockSubspace struct { + ps types.Params +} + +//lint:ignore U1000 disregard lint check +func newMockSubspace(ps types.Params) mockSubspace { + return mockSubspace{ps: ps} +} + +func (ms mockSubspace) GetParamSet(_ sdk.Context, ps exported.ParamSet) { + *ps.(*types.Params) = ms.ps +} + +func TestMigrateMainnet(t *testing.T) { + encCfg := moduletestutil.MakeTestEncodingConfig(globalfee.AppModuleBasic{}) + cdc := encCfg.Codec + + storeKey := sdk.NewKVStoreKey(v2.ModuleName) + tKey := sdk.NewTransientStoreKey("transient_test") + ctx := testutil.DefaultContext(storeKey, tKey) + store := ctx.KVStore(storeKey) + + params := types.Params{ + MinimumGasPrices: sdk.DecCoins{ + sdk.NewDecCoinFromDec("uthiol", sdk.NewDecWithPrec(75, 3)), + }, + } + + require.NoError(t, v2.Migrate(ctx, store, cdc, "uthiol")) + + var res types.Params + bz := store.Get(v2.ParamsKey) + require.NoError(t, cdc.Unmarshal(bz, &res)) + require.Equal(t, params, res) +} + +func TestMigrateTestnet(t *testing.T) { + encCfg := moduletestutil.MakeTestEncodingConfig(globalfee.AppModuleBasic{}) + cdc := encCfg.Codec + + storeKey := sdk.NewKVStoreKey(v2.ModuleName) + tKey := sdk.NewTransientStoreKey("transient_test") + ctx := testutil.DefaultContext(storeKey, tKey) + store := ctx.KVStore(storeKey) + + params := types.Params{ + MinimumGasPrices: sdk.DecCoins{ + sdk.NewDecCoinFromDec("uthiolx", sdk.NewDecWithPrec(75, 3)), + }, + } + + require.NoError(t, v2.Migrate(ctx, store, cdc, "uthiolx")) + + var res types.Params + bz := store.Get(v2.ParamsKey) + require.NoError(t, cdc.Unmarshal(bz, &res)) + require.Equal(t, params, res) +} diff --git a/x/globalfee/module.go b/x/globalfee/module.go new file mode 100644 index 0000000..e54b45f --- /dev/null +++ b/x/globalfee/module.go @@ -0,0 +1,155 @@ +package globalfee + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + + abci "github.com/cometbft/cometbft/abci/types" + + errorsmod "cosmossdk.io/errors" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + + "github.com/terpnetwork/terp-core/v2/x/globalfee/client/cli" + "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +var ( + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleGenesis = AppModule{} + _ module.AppModule = AppModule{} +) + +// ConsensusVersion defines the current x/globalfee module consensus version. +const ConsensusVersion = 2 + +// AppModuleBasic defines the basic application module used by the wasm module. +type AppModuleBasic struct { + cdc codec.Codec +} + +func (a AppModuleBasic) Name() string { + return types.ModuleName +} + +func (a AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(&types.GenesisState{ + Params: types.DefaultParams(), + }) +} + +func (a AppModuleBasic) ValidateGenesis(marshaler codec.JSONCodec, _ client.TxEncodingConfig, message json.RawMessage) error { + var data types.GenesisState + err := marshaler.UnmarshalJSON(message, &data) + if err != nil { + return err + } + if err := data.Params.Validate(); err != nil { + return errorsmod.Wrap(err, "params") + } + return nil +} + +func (a AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) { +} + +func (a AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) + if err != nil { + // same behavior as in cosmos-sdk + panic(err) + } +} + +func (a AppModuleBasic) GetTxCmd() *cobra.Command { + return nil +} + +func (a AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterLegacyAminoCodec(cdc) +} + +func (a AppModuleBasic) RegisterInterfaces(r codectypes.InterfaceRegistry) { + types.RegisterInterfaces(r) +} + +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper + + // bondDenom is used solely for migration off of x/params + bondDenom string +} + +// NewAppModule constructor +func NewAppModule( + cdc codec.Codec, + keeper keeper.Keeper, + debondDenom string, +) *AppModule { + return &AppModule{ + AppModuleBasic: AppModuleBasic{cdc: cdc}, + keeper: keeper, + bondDenom: debondDenom, + } +} + +func (a AppModule) InitGenesis(ctx sdk.Context, marshaler codec.JSONCodec, message json.RawMessage) []abci.ValidatorUpdate { + var genesisState types.GenesisState + marshaler.MustUnmarshalJSON(message, &genesisState) + // a.paramSpace.SetParamSet(ctx, &genesisState.Params) + _ = a.keeper.SetParams(ctx, genesisState.Params) // note: we may want to have this function return an error in the future. + return nil +} + +func (a AppModule) ExportGenesis(ctx sdk.Context, marshaler codec.JSONCodec) json.RawMessage { + params := a.keeper.GetParams(ctx) + genState := types.NewGenesisState(params) + return marshaler.MustMarshalJSON(genState) +} + +func (a AppModule) RegisterInvariants(_ sdk.InvariantRegistry) { +} + +func (a AppModule) QuerierRoute() string { + return types.QuerierRoute +} + +func (a AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterQueryServer(cfg.QueryServer(), NewGrpcQuerier(a.keeper)) + + m := keeper.NewMigrator(a.keeper, a.bondDenom) + if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { + panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err)) + } +} + +func (a AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) { +} + +func (a AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return nil +} + +// 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 (a AppModule) ConsensusVersion() uint64 { + return ConsensusVersion +} diff --git a/x/globalfee/querier.go b/x/globalfee/querier.go new file mode 100644 index 0000000..90e36a5 --- /dev/null +++ b/x/globalfee/querier.go @@ -0,0 +1,35 @@ +package globalfee + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +var _ types.QueryServer = &GrpcQuerier{} + +type GrpcQuerier struct { + keeper keeper.Keeper +} + +func NewGrpcQuerier(k keeper.Keeper) GrpcQuerier { + return GrpcQuerier{ + keeper: k, + } +} + +// MinimumGasPrices return minimum gas prices +func (g GrpcQuerier) MinimumGasPrices(stdCtx context.Context, _ *types.QueryMinimumGasPricesRequest) (*types.QueryMinimumGasPricesResponse, error) { + var minGasPrices sdk.DecCoins + ctx := sdk.UnwrapSDKContext(stdCtx) + + p := g.keeper.GetParams(ctx) + minGasPrices = p.MinimumGasPrices + + return &types.QueryMinimumGasPricesResponse{ + MinimumGasPrices: minGasPrices, + }, nil +} diff --git a/x/globalfee/querier_test.go b/x/globalfee/querier_test.go new file mode 100644 index 0000000..e0d0ff8 --- /dev/null +++ b/x/globalfee/querier_test.go @@ -0,0 +1,60 @@ +package globalfee + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" + + globalfeekeeper "github.com/terpnetwork/terp-core/v2/x/globalfee/keeper" + "github.com/terpnetwork/terp-core/v2/x/globalfee/types" +) + +func TestQueryMinimumGasPrices(t *testing.T) { + specs := map[string]struct { + setupStore func(ctx sdk.Context, k globalfeekeeper.Keeper) + expMin sdk.DecCoins + }{ + "one coin": { + setupStore: func(ctx sdk.Context, k globalfeekeeper.Keeper) { + err := k.SetParams(ctx, types.Params{ + MinimumGasPrices: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.OneInt())), + }) + require.NoError(t, err) + }, + expMin: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.OneInt())), + }, + "multiple coins": { + setupStore: func(ctx sdk.Context, k globalfeekeeper.Keeper) { + err := k.SetParams(ctx, types.Params{ + MinimumGasPrices: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.OneInt()), sdk.NewDecCoin("BLX", sdk.NewInt(2))), + }) + require.NoError(t, err) + }, + expMin: sdk.NewDecCoins(sdk.NewDecCoin("ALX", sdk.OneInt()), sdk.NewDecCoin("BLX", sdk.NewInt(2))), + }, + "no min gas price set": { + setupStore: func(ctx sdk.Context, k globalfeekeeper.Keeper) { + err := k.SetParams(ctx, types.Params{}) + require.NoError(t, err) + }, + }, + "no param set": { + setupStore: func(ctx sdk.Context, k globalfeekeeper.Keeper) { + }, + }, + } + for name, spec := range specs { + t.Run(name, func(t *testing.T) { + ctx, _, keeper := setupTestStore(t) + spec.setupStore(ctx, keeper) + q := NewGrpcQuerier(keeper) + gotResp, gotErr := q.MinimumGasPrices(sdk.WrapSDKContext(ctx), nil) + require.NoError(t, gotErr) + require.NotNil(t, gotResp) + assert.Equal(t, spec.expMin, gotResp.MinimumGasPrices) + }) + } +} diff --git a/x/globalfee/types/codec.go b/x/globalfee/types/codec.go new file mode 100644 index 0000000..5eb8d3d --- /dev/null +++ b/x/globalfee/types/codec.go @@ -0,0 +1,42 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/legacy" + "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" +) + +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) + +func init() { + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + sdk.RegisterLegacyAminoCodec(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec + // so that this can later be used to properly serialize MsgGrant and MsgExec + // instances. + RegisterLegacyAminoCodec(authzcodec.Amino) +} + +// RegisterLegacyAminoCodec registers concrete types on the LegacyAmino codec +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(Params{}, "gaia/x/globalfee/Params", nil) + legacy.RegisterAminoMsg(cdc, &MsgUpdateParams{}, "gaia/x/globalfee/MsgUpdateParams") +} + +func RegisterInterfaces(registry types.InterfaceRegistry) { + registry.RegisterImplementations( + (*sdk.Msg)(nil), + &MsgUpdateParams{}, + ) + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} diff --git a/x/globalfee/types/genesis.go b/x/globalfee/types/genesis.go new file mode 100644 index 0000000..8ca6907 --- /dev/null +++ b/x/globalfee/types/genesis.go @@ -0,0 +1,41 @@ +package types + +import ( + "encoding/json" + + errorsmod "cosmossdk.io/errors" + + "github.com/cosmos/cosmos-sdk/codec" +) + +// NewGenesisState - Create a new genesis state +func NewGenesisState(params Params) *GenesisState { + return &GenesisState{ + Params: params, + } +} + +// DefaultGenesisState - Return a default genesis state +func DefaultGenesisState() *GenesisState { + return NewGenesisState(DefaultParams()) +} + +// GetGenesisStateFromAppState returns x/auth GenesisState given raw application +// genesis state. +func GetGenesisStateFromAppState(cdc codec.Codec, appState map[string]json.RawMessage) *GenesisState { + var genesisState GenesisState + + if appState[ModuleName] != nil { + cdc.MustUnmarshalJSON(appState[ModuleName], &genesisState) + } + + return &genesisState +} + +func ValidateGenesis(data GenesisState) error { + if err := data.Params.Validate(); err != nil { + return errorsmod.Wrap(err, "globalfee params") + } + + return nil +} diff --git a/x/globalfee/types/genesis.pb.go b/x/globalfee/types/genesis.pb.go new file mode 100644 index 0000000..9c91da8 --- /dev/null +++ b/x/globalfee/types/genesis.pb.go @@ -0,0 +1,521 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: gaia/globalfee/v1beta1/genesis.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 + +// GenesisState - initial state of module +type GenesisState struct { + // Params of this module + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params,omitempty"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_015b3e8b7a7c65c5, []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{} +} + +// Params defines the set of module parameters. +type Params struct { + // Minimum stores the minimum gas price(s) for all TX on the chain. + // When multiple coins are defined then they are accepted alternatively. + // The list must be sorted by denoms asc. No duplicate denoms or zero amount + // values allowed. For more information see + // https://docs.cosmos.network/main/modules/auth#concepts + MinimumGasPrices github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=minimum_gas_prices,json=minimumGasPrices,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"minimum_gas_prices,omitempty" yaml:"minimum_gas_prices"` +} + +func (m *Params) Reset() { *m = Params{} } +func (m *Params) String() string { return proto.CompactTextString(m) } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_015b3e8b7a7c65c5, []int{1} +} +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) GetMinimumGasPrices() github_com_cosmos_cosmos_sdk_types.DecCoins { + if m != nil { + return m.MinimumGasPrices + } + return nil +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "gaia.globalfee.v1beta1.GenesisState") + proto.RegisterType((*Params)(nil), "gaia.globalfee.v1beta1.Params") +} + +func init() { + proto.RegisterFile("gaia/globalfee/v1beta1/genesis.proto", fileDescriptor_015b3e8b7a7c65c5) +} + +var fileDescriptor_015b3e8b7a7c65c5 = []byte{ + // 325 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x91, 0x31, 0x4b, 0x03, 0x31, + 0x14, 0xc7, 0x2f, 0x08, 0x1d, 0xae, 0x0e, 0xe5, 0x10, 0xa9, 0xa5, 0xe4, 0xe4, 0x70, 0x28, 0xa8, + 0x09, 0xad, 0x9b, 0xe3, 0x29, 0x74, 0x2d, 0x75, 0x73, 0xa9, 0xb9, 0x33, 0xc6, 0x60, 0x73, 0x09, + 0x4d, 0x2a, 0xf6, 0x5b, 0xf8, 0x39, 0xfc, 0x0c, 0xee, 0x76, 0xec, 0xe8, 0x54, 0xe5, 0x6e, 0x73, + 0xf4, 0x13, 0xc8, 0x25, 0x67, 0x2b, 0x9c, 0x53, 0x02, 0xef, 0xf7, 0x7e, 0xff, 0xc7, 0x7b, 0xfe, + 0x11, 0x23, 0x9c, 0x60, 0x36, 0x95, 0x09, 0x99, 0xde, 0x51, 0x8a, 0x1f, 0xfb, 0x09, 0x35, 0xa4, + 0x8f, 0x19, 0xcd, 0xa8, 0xe6, 0x1a, 0xa9, 0x99, 0x34, 0x32, 0xd8, 0x2f, 0x29, 0xb4, 0xa1, 0x50, + 0x45, 0x75, 0xf6, 0x98, 0x64, 0xd2, 0x22, 0xb8, 0xfc, 0x39, 0xba, 0x03, 0x53, 0xa9, 0x85, 0xd4, + 0x38, 0x21, 0x7a, 0x2b, 0x4c, 0x25, 0xcf, 0x5c, 0x3d, 0xba, 0xf1, 0x77, 0x87, 0x4e, 0x7f, 0x65, + 0x88, 0xa1, 0xc1, 0xc8, 0x6f, 0x28, 0x32, 0x23, 0x42, 0xb7, 0xc1, 0x21, 0xe8, 0x35, 0x07, 0x10, + 0xfd, 0x1f, 0x87, 0x46, 0x96, 0x8a, 0xdb, 0xcb, 0x75, 0xe8, 0x7d, 0xad, 0xc3, 0x96, 0xeb, 0x3a, + 0x91, 0x82, 0x1b, 0x2a, 0x94, 0x59, 0x8c, 0x2b, 0x4f, 0xf4, 0x06, 0xfc, 0x86, 0x83, 0x83, 0x57, + 0xe0, 0x07, 0x82, 0x67, 0x5c, 0xcc, 0xc5, 0x84, 0x11, 0x3d, 0x51, 0x33, 0x9e, 0xd2, 0x32, 0x69, + 0xa7, 0xd7, 0x1c, 0x74, 0x91, 0x1b, 0x15, 0x95, 0xa3, 0x6e, 0x62, 0x2e, 0x69, 0x7a, 0x21, 0x79, + 0x16, 0xab, 0x2a, 0xa7, 0x5b, 0xef, 0xdf, 0x66, 0x7e, 0xaf, 0xc3, 0x83, 0x05, 0x11, 0xd3, 0xf3, + 0xa8, 0x4e, 0x45, 0x2f, 0x1f, 0xe1, 0x31, 0xe3, 0xe6, 0x7e, 0x9e, 0xa0, 0x54, 0x0a, 0x5c, 0xed, + 0xc5, 0x3d, 0xa7, 0xfa, 0xf6, 0x01, 0x9b, 0x85, 0xa2, 0xfa, 0x37, 0x50, 0x8f, 0x5b, 0x95, 0x63, + 0x48, 0xf4, 0xc8, 0x1a, 0xe2, 0x78, 0x99, 0x43, 0xb0, 0xca, 0x21, 0xf8, 0xcc, 0x21, 0x78, 0x2e, + 0xa0, 0xb7, 0x2a, 0xa0, 0xf7, 0x5e, 0x40, 0xef, 0xba, 0x57, 0x17, 0xdb, 0x5b, 0x3e, 0xfd, 0xb9, + 0xa6, 0xd5, 0x27, 0x0d, 0xbb, 0xf6, 0xb3, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x48, 0x6d, 0x01, + 0xcd, 0xec, 0x01, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + 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 (m *Params) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.MinimumGasPrices) > 0 { + for iNdEx := len(m.MinimumGasPrices) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.MinimumGasPrices[iNdEx].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 (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.MinimumGasPrices) > 0 { + for _, e := range m.MinimumGasPrices { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *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 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: 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 != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MinimumGasPrices", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.MinimumGasPrices = append(m.MinimumGasPrices, types.DecCoin{}) + if err := m.MinimumGasPrices[len(m.MinimumGasPrices)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/globalfee/types/keys.go b/x/globalfee/types/keys.go new file mode 100644 index 0000000..c5de162 --- /dev/null +++ b/x/globalfee/types/keys.go @@ -0,0 +1,12 @@ +package types + +var ParamsKey = []byte{0x00} + +const ( + // ModuleName is the name of the this module + ModuleName = "globalfee" + + StoreKey = ModuleName + + QuerierRoute = ModuleName +) diff --git a/x/globalfee/types/msgs.go b/x/globalfee/types/msgs.go new file mode 100644 index 0000000..e0ce8a2 --- /dev/null +++ b/x/globalfee/types/msgs.go @@ -0,0 +1,29 @@ +package types + +import ( + "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +var _ sdk.Msg = &MsgUpdateParams{} + +// GetSignBytes implements the LegacyMsg interface. +func (m MsgUpdateParams) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +// GetSigners returns the expected signers for a MsgUpdateParams message. +func (m *MsgUpdateParams) GetSigners() []sdk.AccAddress { + addr, _ := sdk.AccAddressFromBech32(m.Authority) + return []sdk.AccAddress{addr} +} + +// ValidateBasic does a sanity check on the provided data. +func (m *MsgUpdateParams) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { + return errors.Wrap(err, "invalid authority address") + } + + return m.Params.Validate() +} diff --git a/x/globalfee/types/params.go b/x/globalfee/types/params.go new file mode 100644 index 0000000..6e6ded3 --- /dev/null +++ b/x/globalfee/types/params.go @@ -0,0 +1,66 @@ +package types + +import ( + "fmt" + + errorsmod "cosmossdk.io/errors" + + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// DefaultParams returns default parameters +func DefaultParams() Params { + return Params{MinimumGasPrices: sdk.DecCoins(nil)} +} + +// Validate performs basic validation. +func (p Params) Validate() error { + return validateMinimumGasPrices(p.MinimumGasPrices) +} + +// this requires the fee non-negative +func validateMinimumGasPrices(i interface{}) error { + v, ok := i.(sdk.DecCoins) + if !ok { + return errorsmod.Wrapf(sdkerrors.ErrInvalidType, "type: %T, expected sdk.DecCoins", i) + } + + dec := DecCoins(v) + return dec.Validate() +} + +type DecCoins sdk.DecCoins + +// Validate checks that the DecCoins are sorted, have nonnegtive amount, with a valid and unique +// denomination (i.e no duplicates). Otherwise, it returns an error. +func (coins DecCoins) Validate() error { + if len(coins) == 0 { + return nil + } + + lowDenom := "" + seenDenoms := make(map[string]bool) + + for i, coin := range coins { + if seenDenoms[coin.Denom] { + return fmt.Errorf("duplicate denomination %s", coin.Denom) + } + if err := sdk.ValidateDenom(coin.Denom); err != nil { + return err + } + // skip the denom order check for the first denom in the coins list + if i != 0 && coin.Denom <= lowDenom { + return fmt.Errorf("denomination %s is not sorted", coin.Denom) + } + if coin.IsNegative() { + return fmt.Errorf("coin %s amount is negative", coin.Amount) + } + + // we compare each coin against the last denom + lowDenom = coin.Denom + seenDenoms[coin.Denom] = true + } + + return nil +} diff --git a/x/globalfee/types/params_legacy.go b/x/globalfee/types/params_legacy.go new file mode 100644 index 0000000..07f5f37 --- /dev/null +++ b/x/globalfee/types/params_legacy.go @@ -0,0 +1,21 @@ +package types + +import ( + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +// ParamStoreKeyMinGasPrices store key +var ParamStoreKeyMinGasPrices = []byte("MinimumGasPricesParam") + +func ParamKeyTable() paramtypes.KeyTable { + return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) +} + +// ParamSetPairs returns the parameter set pairs. +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{ + paramtypes.NewParamSetPair( + ParamStoreKeyMinGasPrices, &p.MinimumGasPrices, validateMinimumGasPrices, + ), + } +} diff --git a/x/globalfee/types/params_test.go b/x/globalfee/types/params_test.go new file mode 100644 index 0000000..f03b3bf --- /dev/null +++ b/x/globalfee/types/params_test.go @@ -0,0 +1,74 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func TestDefaultParams(t *testing.T) { + p := DefaultParams() + require.EqualValues(t, p.MinimumGasPrices, sdk.DecCoins(nil)) +} + +func Test_validateParams(t *testing.T) { + tests := map[string]struct { + coins interface{} // not sdk.DeCoins, but Decoins defined in glboalfee + expectErr bool + }{ + "DefaultParams, pass": { + DefaultParams().MinimumGasPrices, + false, + }, + "DecCoins conversion fails, fail": { + sdk.Coins{sdk.NewCoin("photon", sdk.OneInt())}, + true, + }, + "coins amounts are zero, pass": { + sdk.DecCoins{ + sdk.NewDecCoin("atom", sdk.ZeroInt()), + sdk.NewDecCoin("photon", sdk.ZeroInt()), + }, + false, + }, + "duplicate coins denoms, fail": { + sdk.DecCoins{ + sdk.NewDecCoin("photon", sdk.OneInt()), + sdk.NewDecCoin("photon", sdk.OneInt()), + }, + true, + }, + "coins are not sorted by denom alphabetically, fail": { + sdk.DecCoins{ + sdk.NewDecCoin("photon", sdk.OneInt()), + sdk.NewDecCoin("atom", sdk.OneInt()), + }, + true, + }, + "negative amount, fail": { + sdk.DecCoins{ + sdk.DecCoin{Denom: "photon", Amount: sdk.OneDec().Neg()}, + }, + true, + }, + "invalid denom, fail": { + sdk.DecCoins{ + sdk.DecCoin{Denom: "photon!", Amount: sdk.OneDec().Neg()}, + }, + true, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + err := validateMinimumGasPrices(test.coins) + if test.expectErr { + require.Error(t, err) + return + } + require.NoError(t, err) + }) + } +} diff --git a/x/globalfee/types/query.pb.go b/x/globalfee/types/query.pb.go new file mode 100644 index 0000000..5b87eb6 --- /dev/null +++ b/x/globalfee/types/query.pb.go @@ -0,0 +1,555 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: gaia/globalfee/v1beta1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types" + _ "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 + +// QueryMinimumGasPricesRequest is the request type for the +// Query/MinimumGasPrices RPC method. +type QueryMinimumGasPricesRequest struct { +} + +func (m *QueryMinimumGasPricesRequest) Reset() { *m = QueryMinimumGasPricesRequest{} } +func (m *QueryMinimumGasPricesRequest) String() string { return proto.CompactTextString(m) } +func (*QueryMinimumGasPricesRequest) ProtoMessage() {} +func (*QueryMinimumGasPricesRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_12a736cede25d10a, []int{0} +} +func (m *QueryMinimumGasPricesRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryMinimumGasPricesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryMinimumGasPricesRequest.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 *QueryMinimumGasPricesRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryMinimumGasPricesRequest.Merge(m, src) +} +func (m *QueryMinimumGasPricesRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryMinimumGasPricesRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryMinimumGasPricesRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryMinimumGasPricesRequest proto.InternalMessageInfo + +// QueryMinimumGasPricesResponse is the response type for the +// Query/MinimumGasPrices RPC method. +type QueryMinimumGasPricesResponse struct { + MinimumGasPrices github_com_cosmos_cosmos_sdk_types.DecCoins `protobuf:"bytes,1,rep,name=minimum_gas_prices,json=minimumGasPrices,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.DecCoins" json:"minimum_gas_prices,omitempty" yaml:"minimum_gas_prices"` +} + +func (m *QueryMinimumGasPricesResponse) Reset() { *m = QueryMinimumGasPricesResponse{} } +func (m *QueryMinimumGasPricesResponse) String() string { return proto.CompactTextString(m) } +func (*QueryMinimumGasPricesResponse) ProtoMessage() {} +func (*QueryMinimumGasPricesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_12a736cede25d10a, []int{1} +} +func (m *QueryMinimumGasPricesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryMinimumGasPricesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryMinimumGasPricesResponse.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 *QueryMinimumGasPricesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryMinimumGasPricesResponse.Merge(m, src) +} +func (m *QueryMinimumGasPricesResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryMinimumGasPricesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryMinimumGasPricesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryMinimumGasPricesResponse proto.InternalMessageInfo + +func (m *QueryMinimumGasPricesResponse) GetMinimumGasPrices() github_com_cosmos_cosmos_sdk_types.DecCoins { + if m != nil { + return m.MinimumGasPrices + } + return nil +} + +func init() { + proto.RegisterType((*QueryMinimumGasPricesRequest)(nil), "gaia.globalfee.v1beta1.QueryMinimumGasPricesRequest") + proto.RegisterType((*QueryMinimumGasPricesResponse)(nil), "gaia.globalfee.v1beta1.QueryMinimumGasPricesResponse") +} + +func init() { + proto.RegisterFile("gaia/globalfee/v1beta1/query.proto", fileDescriptor_12a736cede25d10a) +} + +var fileDescriptor_12a736cede25d10a = []byte{ + // 377 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x92, 0xb1, 0x4f, 0xdb, 0x40, + 0x14, 0xc6, 0x7d, 0xad, 0xda, 0xc1, 0x5d, 0x22, 0xab, 0xaa, 0xda, 0xc8, 0x3d, 0x57, 0x9e, 0xa2, + 0x36, 0xbd, 0x53, 0xd2, 0x76, 0xe9, 0x98, 0x56, 0x62, 0x42, 0x82, 0x8c, 0x2c, 0xd1, 0xd9, 0x1c, + 0xc7, 0x09, 0x9f, 0x9f, 0x93, 0x3b, 0x23, 0xbc, 0xf2, 0x17, 0x20, 0xf1, 0x5f, 0xb0, 0xb2, 0xc2, + 0x9e, 0x31, 0x12, 0x0b, 0x93, 0x41, 0x09, 0x13, 0x23, 0x7f, 0x01, 0xb2, 0x9d, 0x00, 0x8a, 0x09, + 0x12, 0x93, 0x2d, 0x7d, 0xbf, 0xf7, 0x3e, 0x7d, 0xdf, 0x3d, 0xdb, 0x17, 0x4c, 0x32, 0x2a, 0x22, + 0x08, 0x58, 0xb4, 0xc3, 0x39, 0xdd, 0xef, 0x04, 0xdc, 0xb0, 0x0e, 0x1d, 0xa6, 0x7c, 0x94, 0x91, + 0x64, 0x04, 0x06, 0x9c, 0x4f, 0x05, 0x43, 0x1e, 0x18, 0x32, 0x67, 0x9a, 0x1f, 0x05, 0x08, 0x28, + 0x11, 0x5a, 0xfc, 0x55, 0x74, 0xd3, 0x15, 0x00, 0x22, 0xe2, 0x94, 0x25, 0x92, 0xb2, 0x38, 0x06, + 0xc3, 0x8c, 0x84, 0x58, 0xcf, 0x55, 0x1c, 0x82, 0x56, 0xa0, 0x69, 0xc0, 0xf4, 0xa3, 0x59, 0x08, + 0x32, 0xae, 0x74, 0x1f, 0xdb, 0xee, 0x66, 0x61, 0xbd, 0x2e, 0x63, 0xa9, 0x52, 0xb5, 0xc6, 0xf4, + 0xc6, 0x48, 0x86, 0x5c, 0xf7, 0xf9, 0x30, 0xe5, 0xda, 0xf8, 0x39, 0xb2, 0xbf, 0xae, 0x00, 0x74, + 0x02, 0xb1, 0xe6, 0xce, 0x19, 0xb2, 0x1d, 0x55, 0x89, 0x03, 0xc1, 0xf4, 0x20, 0x29, 0xe5, 0xcf, + 0xe8, 0xdb, 0xdb, 0xd6, 0x87, 0xae, 0x4b, 0x2a, 0x7f, 0x52, 0xf8, 0x2f, 0x82, 0x90, 0xff, 0x3c, + 0xfc, 0x07, 0x32, 0xee, 0x25, 0xe3, 0xdc, 0xb3, 0x6e, 0x73, 0xcf, 0xad, 0xcf, 0xb7, 0x41, 0x49, + 0xc3, 0x55, 0x62, 0xb2, 0xbb, 0xdc, 0xfb, 0x92, 0x31, 0x15, 0xfd, 0xf5, 0xeb, 0x94, 0x7f, 0x72, + 0xe5, 0xfd, 0x10, 0xd2, 0xec, 0xa6, 0x01, 0x09, 0x41, 0xd1, 0x79, 0xd8, 0xea, 0xf3, 0x53, 0x6f, + 0xef, 0x51, 0x93, 0x25, 0x5c, 0x2f, 0x0c, 0x75, 0xbf, 0xa1, 0x96, 0x62, 0x74, 0xcf, 0x91, 0xfd, + 0xae, 0x0c, 0xe8, 0x9c, 0x22, 0xbb, 0xb1, 0x9c, 0xd2, 0xf9, 0x4d, 0x9e, 0x7f, 0x0c, 0xf2, 0x52, + 0x6b, 0xcd, 0x3f, 0xaf, 0x9c, 0xaa, 0xaa, 0xf4, 0xbb, 0x87, 0x17, 0x37, 0xc7, 0x6f, 0xda, 0xce, + 0x77, 0xba, 0xe2, 0x4a, 0xea, 0x0d, 0xf4, 0x7a, 0xe3, 0x29, 0x46, 0x93, 0x29, 0x46, 0xd7, 0x53, + 0x8c, 0x8e, 0x66, 0xd8, 0x9a, 0xcc, 0xb0, 0x75, 0x39, 0xc3, 0xd6, 0x56, 0xab, 0x5e, 0x4c, 0xb9, + 0xf6, 0xe0, 0xc9, 0xe2, 0xb2, 0x9e, 0xe0, 0x7d, 0x79, 0x0b, 0xbf, 0xee, 0x03, 0x00, 0x00, 0xff, + 0xff, 0x73, 0x0d, 0xf8, 0x43, 0x9d, 0x02, 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 { + // MinimumGasPrices returns the minimum gas prices. + MinimumGasPrices(ctx context.Context, in *QueryMinimumGasPricesRequest, opts ...grpc.CallOption) (*QueryMinimumGasPricesResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) MinimumGasPrices(ctx context.Context, in *QueryMinimumGasPricesRequest, opts ...grpc.CallOption) (*QueryMinimumGasPricesResponse, error) { + out := new(QueryMinimumGasPricesResponse) + err := c.cc.Invoke(ctx, "/gaia.globalfee.v1beta1.Query/MinimumGasPrices", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // MinimumGasPrices returns the minimum gas prices. + MinimumGasPrices(context.Context, *QueryMinimumGasPricesRequest) (*QueryMinimumGasPricesResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) MinimumGasPrices(ctx context.Context, req *QueryMinimumGasPricesRequest) (*QueryMinimumGasPricesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method MinimumGasPrices not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_MinimumGasPrices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryMinimumGasPricesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).MinimumGasPrices(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/gaia.globalfee.v1beta1.Query/MinimumGasPrices", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).MinimumGasPrices(ctx, req.(*QueryMinimumGasPricesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "gaia.globalfee.v1beta1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "MinimumGasPrices", + Handler: _Query_MinimumGasPrices_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "gaia/globalfee/v1beta1/query.proto", +} + +func (m *QueryMinimumGasPricesRequest) 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 *QueryMinimumGasPricesRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryMinimumGasPricesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryMinimumGasPricesResponse) 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 *QueryMinimumGasPricesResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryMinimumGasPricesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.MinimumGasPrices) > 0 { + for iNdEx := len(m.MinimumGasPrices) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.MinimumGasPrices[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 *QueryMinimumGasPricesRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryMinimumGasPricesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.MinimumGasPrices) > 0 { + for _, e := range m.MinimumGasPrices { + l = e.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 *QueryMinimumGasPricesRequest) 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: QueryMinimumGasPricesRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryMinimumGasPricesRequest: 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 *QueryMinimumGasPricesResponse) 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: QueryMinimumGasPricesResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryMinimumGasPricesResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MinimumGasPrices", 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.MinimumGasPrices = append(m.MinimumGasPrices, types.DecCoin{}) + if err := m.MinimumGasPrices[len(m.MinimumGasPrices)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func 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/globalfee/types/query.pb.gw.go b/x/globalfee/types/query.pb.gw.go new file mode 100644 index 0000000..a7b2956 --- /dev/null +++ b/x/globalfee/types/query.pb.gw.go @@ -0,0 +1,153 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: gaia/globalfee/v1beta1/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_MinimumGasPrices_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryMinimumGasPricesRequest + var metadata runtime.ServerMetadata + + msg, err := client.MinimumGasPrices(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_MinimumGasPrices_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryMinimumGasPricesRequest + var metadata runtime.ServerMetadata + + msg, err := server.MinimumGasPrices(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_MinimumGasPrices_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_MinimumGasPrices_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_MinimumGasPrices_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_MinimumGasPrices_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_MinimumGasPrices_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_MinimumGasPrices_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_MinimumGasPrices_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"gaia", "globalfee", "v1beta1", "minimum_gas_prices"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_MinimumGasPrices_0 = runtime.ForwardResponseMessage +) diff --git a/x/globalfee/types/tx.pb.go b/x/globalfee/types/tx.pb.go new file mode 100644 index 0000000..5438344 --- /dev/null +++ b/x/globalfee/types/tx.pb.go @@ -0,0 +1,604 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: gaia/globalfee/v1beta1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" + _ "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 + +// MsgUpdateParams is the Msg/UpdateParams request type. +// +// Since: cosmos-sdk 0.47 +type MsgUpdateParams struct { + // authority is the address of the governance account. + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` + // params defines the x/mint parameters to update. + // + // NOTE: All parameters must be supplied. + Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` +} + +func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } +func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParams) ProtoMessage() {} +func (*MsgUpdateParams) Descriptor() ([]byte, []int) { + return fileDescriptor_1b7ff262ac5784d9, []int{0} +} +func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParams.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 *MsgUpdateParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParams.Merge(m, src) +} +func (m *MsgUpdateParams) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParams) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo + +func (m *MsgUpdateParams) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func (m *MsgUpdateParams) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +// +// Since: cosmos-sdk 0.47 +type MsgUpdateParamsResponse struct { +} + +func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } +func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParamsResponse) ProtoMessage() {} +func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_1b7ff262ac5784d9, []int{1} +} +func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParamsResponse.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 *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) +} +func (m *MsgUpdateParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgUpdateParams)(nil), "gaia.globalfee.v1beta1.MsgUpdateParams") + proto.RegisterType((*MsgUpdateParamsResponse)(nil), "gaia.globalfee.v1beta1.MsgUpdateParamsResponse") +} + +func init() { proto.RegisterFile("gaia/globalfee/v1beta1/tx.proto", fileDescriptor_1b7ff262ac5784d9) } + +var fileDescriptor_1b7ff262ac5784d9 = []byte{ + // 322 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0x4f, 0xcc, 0x4c, + 0xd4, 0x4f, 0xcf, 0xc9, 0x4f, 0x4a, 0xcc, 0x49, 0x4b, 0x4d, 0xd5, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, + 0x49, 0x34, 0xd4, 0x2f, 0xa9, 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x03, 0x29, 0xd0, + 0x83, 0x2b, 0xd0, 0x83, 0x2a, 0x90, 0x12, 0x4f, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0xcf, 0x2d, + 0x4e, 0xd7, 0x2f, 0x33, 0x04, 0x51, 0x10, 0x0d, 0x52, 0x2a, 0x38, 0x4c, 0x4c, 0x4f, 0xcd, 0x4b, + 0x2d, 0xce, 0x2c, 0x86, 0xaa, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x33, 0xf5, 0x41, 0x2c, 0xa8, + 0xa8, 0x24, 0xc4, 0xd0, 0x78, 0x88, 0x04, 0x84, 0x03, 0x91, 0x52, 0x9a, 0xce, 0xc8, 0xc5, 0xef, + 0x5b, 0x9c, 0x1e, 0x5a, 0x90, 0x92, 0x58, 0x92, 0x1a, 0x90, 0x58, 0x94, 0x98, 0x5b, 0x2c, 0x64, + 0xc6, 0xc5, 0x99, 0x58, 0x5a, 0x92, 0x91, 0x5f, 0x94, 0x59, 0x52, 0x29, 0xc1, 0xa8, 0xc0, 0xa8, + 0xc1, 0xe9, 0x24, 0x71, 0x69, 0x8b, 0xae, 0x08, 0x54, 0xa3, 0x63, 0x4a, 0x4a, 0x51, 0x6a, 0x71, + 0x71, 0x70, 0x49, 0x51, 0x66, 0x5e, 0x7a, 0x10, 0x42, 0xa9, 0x90, 0x0d, 0x17, 0x5b, 0x01, 0xd8, + 0x04, 0x09, 0x26, 0x05, 0x46, 0x0d, 0x6e, 0x23, 0x39, 0x3d, 0xec, 0x9e, 0xd4, 0x83, 0xd8, 0xe3, + 0xc4, 0x72, 0xe2, 0x9e, 0x3c, 0x43, 0x10, 0x54, 0x8f, 0x15, 0x5f, 0xd3, 0xf3, 0x0d, 0x5a, 0x08, + 0xd3, 0x94, 0x24, 0xb9, 0xc4, 0xd1, 0x1c, 0x16, 0x94, 0x5a, 0x5c, 0x90, 0x9f, 0x57, 0x9c, 0x6a, + 0x94, 0xcf, 0xc5, 0xec, 0x5b, 0x9c, 0x2e, 0x94, 0xc1, 0xc5, 0x83, 0xe2, 0x6e, 0x75, 0x5c, 0xf6, + 0xa1, 0x99, 0x23, 0xa5, 0x4f, 0xa4, 0x42, 0x98, 0x85, 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, + 0x0b, 0x0d, 0x58, 0x7d, 0x70, 0x44, 0x55, 0x20, 0x45, 0x55, 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, + 0x1b, 0x38, 0xc0, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x6e, 0x7f, 0x56, 0x6e, 0x1b, 0x02, + 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 { + // UpdateParams defines a governance operation for updating the x/mint module + // parameters. The authority is hard-coded to the x/gov module account. + // + // Since: cosmos-sdk 0.47 + UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { + out := new(MsgUpdateParamsResponse) + err := c.cc.Invoke(ctx, "/gaia.globalfee.v1beta1.Msg/UpdateParams", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + // UpdateParams defines a governance operation for updating the x/mint module + // parameters. The authority is hard-coded to the x/gov module account. + // + // Since: cosmos-sdk 0.47 + UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateParams) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdateParams(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/gaia.globalfee.v1beta1.Msg/UpdateParams", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "gaia.globalfee.v1beta1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "UpdateParams", + Handler: _Msg_UpdateParams_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "gaia/globalfee/v1beta1/tx.proto", +} + +func (m *MsgUpdateParams) 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 *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParams) 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 = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateParamsResponse) 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 *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgUpdateParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Params.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgUpdateParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovTx(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTx(x uint64) (n int) { + return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgUpdateParams) 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: MsgUpdateParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", 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.Authority = 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 err := m.Params.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 *MsgUpdateParamsResponse) 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: MsgUpdateParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTx(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTx + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTx + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTx + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTx + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/tokenfactory/bindings/custom_msg_test.go b/x/tokenfactory/bindings/custom_msg_test.go index a21bc45..22d56d7 100644 --- a/x/tokenfactory/bindings/custom_msg_test.go +++ b/x/tokenfactory/bindings/custom_msg_test.go @@ -5,34 +5,33 @@ import ( "fmt" "testing" + "github.com/CosmWasm/wasmd/x/wasm/keeper" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" "github.com/stretchr/testify/require" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/wasm/keeper" - - "github.com/terpnetwork/terp-core/app" - bindings "github.com/terpnetwork/terp-core/x/tokenfactory/bindings/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/app" + bindings "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) func TestCreateDenomMsg(t *testing.T) { creator := RandomAccountAddress() - terp, ctx := SetupCustomApp(t, creator) + terpapp, ctx := SetupCustomApp(t, creator) lucky := RandomAccountAddress() - reflect := instantiateReflectContract(t, ctx, terp, lucky) + reflect := instantiateReflectContract(t, ctx, terpapp, lucky) require.NotEmpty(t, reflect) // Fund reflect contract with 100 base denom creation fees reflectAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100))) - fundAccount(t, ctx, terp, reflect, reflectAmount) + fundAccount(t, ctx, terpapp, reflect, reflectAmount) msg := bindings.TokenMsg{CreateDenom: &bindings.CreateDenom{ Subdenom: "SUN", }} - err := executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + err := executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) // query the denom and see if it matches @@ -43,32 +42,32 @@ func TestCreateDenomMsg(t *testing.T) { }, } resp := bindings.FullDenomResponse{} - queryCustom(t, ctx, terp, reflect, query, &resp) + queryCustom(t, ctx, terpapp, reflect, query, &resp) require.Equal(t, resp.Denom, fmt.Sprintf("factory/%s/SUN", reflect.String())) } func TestMintMsg(t *testing.T) { creator := RandomAccountAddress() - terp, ctx := SetupCustomApp(t, creator) + terpapp, ctx := SetupCustomApp(t, creator) lucky := RandomAccountAddress() - reflect := instantiateReflectContract(t, ctx, terp, lucky) + reflect := instantiateReflectContract(t, ctx, terpapp, lucky) require.NotEmpty(t, reflect) // Fund reflect contract with 100 base denom creation fees reflectAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100))) - fundAccount(t, ctx, terp, reflect, reflectAmount) + fundAccount(t, ctx, terpapp, reflect, reflectAmount) // lucky was broke - balances := terp.BankKeeper.GetAllBalances(ctx, lucky) + balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) require.Empty(t, balances) // Create denom for minting msg := bindings.TokenMsg{CreateDenom: &bindings.CreateDenom{ Subdenom: "SUN", }} - err := executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + err := executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) sunDenom := fmt.Sprintf("factory/%s/%s", reflect.String(), msg.CreateDenom.Subdenom) @@ -79,10 +78,10 @@ func TestMintMsg(t *testing.T) { Amount: amount, MintToAddress: lucky.String(), }} - err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) - balances = terp.BankKeeper.GetAllBalances(ctx, lucky) + balances = terpapp.BankKeeper.GetAllBalances(ctx, lucky) require.Len(t, balances, 1) coin := balances[0] require.Equal(t, amount, coin.Amount) @@ -96,15 +95,15 @@ func TestMintMsg(t *testing.T) { }, } resp := bindings.FullDenomResponse{} - queryCustom(t, ctx, terp, reflect, query, &resp) + queryCustom(t, ctx, terpapp, reflect, query, &resp) require.Equal(t, resp.Denom, coin.Denom) // mint the same denom again - err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) - balances = terp.BankKeeper.GetAllBalances(ctx, lucky) + balances = terpapp.BankKeeper.GetAllBalances(ctx, lucky) require.Len(t, balances, 1) coin = balances[0] require.Equal(t, amount.MulRaw(2), coin.Amount) @@ -118,7 +117,7 @@ func TestMintMsg(t *testing.T) { }, } resp = bindings.FullDenomResponse{} - queryCustom(t, ctx, terp, reflect, query, &resp) + queryCustom(t, ctx, terpapp, reflect, query, &resp) require.Equal(t, resp.Denom, coin.Denom) @@ -127,7 +126,7 @@ func TestMintMsg(t *testing.T) { msg = bindings.TokenMsg{CreateDenom: &bindings.CreateDenom{ Subdenom: "MOON", }} - err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) moonDenom := fmt.Sprintf("factory/%s/%s", reflect.String(), msg.CreateDenom.Subdenom) @@ -137,10 +136,10 @@ func TestMintMsg(t *testing.T) { Amount: amount, MintToAddress: lucky.String(), }} - err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) - balances = terp.BankKeeper.GetAllBalances(ctx, lucky) + balances = terpapp.BankKeeper.GetAllBalances(ctx, lucky) require.Len(t, balances, 2) coin = balances[0] require.Equal(t, amount, coin.Amount) @@ -154,7 +153,7 @@ func TestMintMsg(t *testing.T) { }, } resp = bindings.FullDenomResponse{} - queryCustom(t, ctx, terp, reflect, query, &resp) + queryCustom(t, ctx, terpapp, reflect, query, &resp) require.Equal(t, resp.Denom, coin.Denom) @@ -171,66 +170,122 @@ func TestMintMsg(t *testing.T) { }, } resp = bindings.FullDenomResponse{} - queryCustom(t, ctx, terp, reflect, query, &resp) + queryCustom(t, ctx, terpapp, reflect, query, &resp) require.Equal(t, resp.Denom, coin.Denom) } -func TestBurnMsg(t *testing.T) { +func TestForceTransfer(t *testing.T) { creator := RandomAccountAddress() - terp, ctx := SetupCustomApp(t, creator) + terpapp, ctx := SetupCustomApp(t, creator) lucky := RandomAccountAddress() - reflect := instantiateReflectContract(t, ctx, terp, lucky) + rcpt := RandomAccountAddress() + reflect := instantiateReflectContract(t, ctx, terpapp, lucky) require.NotEmpty(t, reflect) // Fund reflect contract with 100 base denom creation fees reflectAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100))) - fundAccount(t, ctx, terp, reflect, reflectAmount) + fundAccount(t, ctx, terpapp, reflect, reflectAmount) // lucky was broke - balances := terp.BankKeeper.GetAllBalances(ctx, lucky) + balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) require.Empty(t, balances) // Create denom for minting msg := bindings.TokenMsg{CreateDenom: &bindings.CreateDenom{ Subdenom: "SUN", }} - err := executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + err := executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) sunDenom := fmt.Sprintf("factory/%s/%s", reflect.String(), msg.CreateDenom.Subdenom) amount, ok := sdk.NewIntFromString("808010808") require.True(t, ok) + // Mint new tokens to lucky msg = bindings.TokenMsg{MintTokens: &bindings.MintTokens{ Denom: sunDenom, Amount: amount, MintToAddress: lucky.String(), }} - err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) - // can't burn from different address + // Force move 100 tokens from lucky to rcpt + msg = bindings.TokenMsg{ForceTransfer: &bindings.ForceTransfer{ + Denom: sunDenom, + Amount: sdk.NewInt(100), + FromAddress: lucky.String(), + ToAddress: rcpt.String(), + }} + err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) + + // check the balance of rcpt + balances = terpapp.BankKeeper.GetAllBalances(ctx, rcpt) + require.Len(t, balances, 1) + coin := balances[0] + require.Equal(t, sdk.NewInt(100), coin.Amount) +} + +func TestBurnMsg(t *testing.T) { + creator := RandomAccountAddress() + terpapp, ctx := SetupCustomApp(t, creator) + + lucky := RandomAccountAddress() + reflect := instantiateReflectContract(t, ctx, terpapp, lucky) + require.NotEmpty(t, reflect) + + // Fund reflect contract with 100 base denom creation fees + reflectAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100))) + fundAccount(t, ctx, terpapp, reflect, reflectAmount) + + // lucky was broke + balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) + require.Empty(t, balances) + + // Create denom for minting + msg := bindings.TokenMsg{CreateDenom: &bindings.CreateDenom{ + Subdenom: "SUN", + }} + err := executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) + sunDenom := fmt.Sprintf("factory/%s/%s", reflect.String(), msg.CreateDenom.Subdenom) + + amount, ok := sdk.NewIntFromString("808010809") + require.True(t, ok) + + msg = bindings.TokenMsg{MintTokens: &bindings.MintTokens{ + Denom: sunDenom, + Amount: amount, + MintToAddress: lucky.String(), + }} + err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) + + // can burn from different address with burnFrom + amt, ok := sdk.NewIntFromString("1") + require.True(t, ok) msg = bindings.TokenMsg{BurnTokens: &bindings.BurnTokens{ Denom: sunDenom, - Amount: amount, + Amount: amt, BurnFromAddress: lucky.String(), }} - err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) - require.Error(t, err) + err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) // lucky needs to send balance to reflect contract to burn it - luckyBalance := terp.BankKeeper.GetAllBalances(ctx, lucky) - err = terp.BankKeeper.SendCoins(ctx, lucky, reflect, luckyBalance) + luckyBalance := terpapp.BankKeeper.GetAllBalances(ctx, lucky) + err = terpapp.BankKeeper.SendCoins(ctx, lucky, reflect, luckyBalance) require.NoError(t, err) msg = bindings.TokenMsg{BurnTokens: &bindings.BurnTokens{ Denom: sunDenom, - Amount: amount, + Amount: amount.Abs().Sub(sdk.NewInt(1)), BurnFromAddress: reflect.String(), }} - err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + err = executeCustom(t, ctx, terpapp, reflect, lucky, msg, sdk.Coin{}) require.NoError(t, err) } @@ -247,8 +302,7 @@ type ReflectSubMsgs struct { Msgs []wasmvmtypes.SubMsg `json:"msgs"` } -func executeCustom(t *testing.T, ctx sdk.Context, terp *app.TerpApp, contract sdk.AccAddress, sender sdk.AccAddress, msg bindings.TokenMsg, funds sdk.Coin) error { //nolint:unparam // funds currently always receives nil, but it may receive something else in the future - t.Helper() +func executeCustom(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, contract sdk.AccAddress, sender sdk.AccAddress, msg bindings.TokenMsg, funds sdk.Coin) error { //nolint:unparam // funds is always nil but could change in the future. wrapped := bindings.TokenFactoryMsg{ Token: &msg, } @@ -271,7 +325,7 @@ func executeCustom(t *testing.T, ctx sdk.Context, terp *app.TerpApp, contract sd coins = sdk.Coins{funds} } - contractKeeper := keeper.NewDefaultPermissionKeeper(terp.WasmKeeper) + contractKeeper := keeper.NewDefaultPermissionKeeper(terpapp.WasmKeeper) _, err = contractKeeper.Execute(ctx, contract, sender, reflectBz, coins) return err } diff --git a/x/tokenfactory/bindings/custom_query_test.go b/x/tokenfactory/bindings/custom_query_test.go index 67e3491..e603a7c 100644 --- a/x/tokenfactory/bindings/custom_query_test.go +++ b/x/tokenfactory/bindings/custom_query_test.go @@ -5,20 +5,20 @@ import ( "fmt" "testing" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" "github.com/stretchr/testify/require" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/app" - bindings "github.com/terpnetwork/terp-core/x/tokenfactory/bindings/types" + "github.com/terpnetwork/terp-core/v2/app" + bindings "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings/types" ) func TestQueryFullDenom(t *testing.T) { actor := RandomAccountAddress() - tokenz, ctx := SetupCustomApp(t, actor) + terpapp, ctx := SetupCustomApp(t, actor) - reflect := instantiateReflectContract(t, ctx, tokenz, actor) + reflect := instantiateReflectContract(t, ctx, terpapp, actor) require.NotEmpty(t, reflect) // query full denom @@ -29,7 +29,7 @@ func TestQueryFullDenom(t *testing.T) { }, } resp := bindings.FullDenomResponse{} - queryCustom(t, ctx, tokenz, reflect, query, &resp) + queryCustom(t, ctx, terpapp, reflect, query, &resp) expected := fmt.Sprintf("factory/%s/ustart", reflect.String()) require.EqualValues(t, expected, resp.Denom) @@ -47,14 +47,13 @@ type ChainResponse struct { Data []byte `json:"data"` } -func queryCustom(t *testing.T, ctx sdk.Context, tokenz *app.TerpApp, contract sdk.AccAddress, request bindings.TokenQuery, response interface{}) { - t.Helper() +func queryCustom(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, contract sdk.AccAddress, request bindings.TokenQuery, response interface{}) { wrapped := bindings.TokenFactoryQuery{ Token: &request, } msgBz, err := json.Marshal(wrapped) require.NoError(t, err) - fmt.Println(string(msgBz)) + fmt.Println("queryCustom1", string(msgBz)) query := ReflectQuery{ Chain: &ChainRequest{ @@ -63,9 +62,9 @@ func queryCustom(t *testing.T, ctx sdk.Context, tokenz *app.TerpApp, contract sd } queryBz, err := json.Marshal(query) require.NoError(t, err) - fmt.Println(string(queryBz)) + fmt.Println("queryCustom2", string(queryBz)) - resBz, err := tokenz.WasmKeeper.QuerySmart(ctx, contract, queryBz) + resBz, err := terpapp.WasmKeeper.QuerySmart(ctx, contract, queryBz) require.NoError(t, err) var resp ChainResponse err = json.Unmarshal(resBz, &resp) diff --git a/x/tokenfactory/bindings/helpers_test.go b/x/tokenfactory/bindings/helpers_test.go index 6857249..6b4f840 100644 --- a/x/tokenfactory/bindings/helpers_test.go +++ b/x/tokenfactory/bindings/helpers_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "github.com/CosmWasm/wasmd/x/wasm/keeper" "github.com/stretchr/testify/require" "github.com/cometbft/cometbft/crypto" @@ -12,29 +13,22 @@ import ( tmproto "github.com/cometbft/cometbft/proto/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" + banktestutil "github.com/cosmos/cosmos-sdk/x/bank/testutil" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm" - "github.com/terpnetwork/terp-core/x/wasm/keeper" + "github.com/terpnetwork/terp-core/v2/app" ) -func CreateTestInput() (*app.TerpApp, sdk.Context) { - var emptyWasmOpts []wasm.Option - - terp := app.Setup(&testing.T{}, emptyWasmOpts...) - ctx := terp.BaseApp.NewContext(false, tmproto.Header{Height: 1, ChainID: "terp-1", Time: time.Now().UTC()}) - return terp, ctx +func CreateTestInput(t *testing.T) (*app.TerpApp, sdk.Context) { + osmosis := app.Setup(t) + ctx := osmosis.BaseApp.NewContext(false, tmproto.Header{Height: 1, ChainID: "testing", Time: time.Now().UTC()}) + return osmosis, ctx } -func FundAccount(t *testing.T, ctx sdk.Context, terp *app.TerpApp, acct sdk.AccAddress) { - t.Helper() - // TODO: - // err := simapp.FundAccount(terp.BankKeeper, ctx, acct, sdk.NewCoins( - // sdk.NewCoin("uosmo", sdk.NewInt(10000000000)), - // )) - // require.NoError(t, err) +func FundAccount(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, acct sdk.AccAddress) { + err := banktestutil.FundAccount(terpapp.BankKeeper, ctx, acct, sdk.NewCoins( + sdk.NewCoin("uosmo", sdk.NewInt(10000000000)), + )) + require.NoError(t, err) } // we need to make this deterministic (same every test run), as content might affect gas costs @@ -54,22 +48,20 @@ func RandomBech32AccountAddress() string { return RandomAccountAddress().String() } -func storeReflectCode(t *testing.T, ctx sdk.Context, tokenz *app.TerpApp, addr sdk.AccAddress) uint64 { - t.Helper() +func storeReflectCode(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, addr sdk.AccAddress) uint64 { wasmCode, err := os.ReadFile("./testdata/token_reflect.wasm") require.NoError(t, err) - contractKeeper := keeper.NewDefaultPermissionKeeper(tokenz.WasmKeeper) + contractKeeper := keeper.NewDefaultPermissionKeeper(terpapp.WasmKeeper) codeID, _, err := contractKeeper.Create(ctx, addr, wasmCode, nil) require.NoError(t, err) return codeID } -func instantiateReflectContract(t *testing.T, ctx sdk.Context, tokenz *app.TerpApp, funder sdk.AccAddress) sdk.AccAddress { - t.Helper() +func instantiateReflectContract(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, funder sdk.AccAddress) sdk.AccAddress { initMsgBz := []byte("{}") - contractKeeper := keeper.NewDefaultPermissionKeeper(tokenz.WasmKeeper) + contractKeeper := keeper.NewDefaultPermissionKeeper(terpapp.WasmKeeper) codeID := uint64(1) addr, _, err := contractKeeper.Instantiate(ctx, codeID, funder, funder, initMsgBz, "demo contract", nil) require.NoError(t, err) @@ -77,32 +69,24 @@ func instantiateReflectContract(t *testing.T, ctx sdk.Context, tokenz *app.TerpA return addr } -func fundAccount(t *testing.T, ctx sdk.Context, tokenz *app.TerpApp, addr sdk.AccAddress, coins sdk.Coins) { - t.Helper() - // TODO: - // err := simapp.FundAccount( - // tokenz.BankKeeper, - // ctx, - // addr, - // coins, - // ) - - // require.NoError(t, err) - err := tokenz.BankKeeper.MintCoins(ctx, minttypes.ModuleName, coins) - require.NoError(t, err) - err = tokenz.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, coins) +func fundAccount(t *testing.T, ctx sdk.Context, terpapp *app.TerpApp, addr sdk.AccAddress, coins sdk.Coins) { + err := banktestutil.FundAccount( + terpapp.BankKeeper, + ctx, + addr, + coins, + ) require.NoError(t, err) } func SetupCustomApp(t *testing.T, addr sdk.AccAddress) (*app.TerpApp, sdk.Context) { - t.Helper() - tokenz, ctx := CreateTestInput() - wasmKeeper := tokenz.WasmKeeper + terpapp, ctx := CreateTestInput(t) + wasmKeeper := terpapp.WasmKeeper - storeReflectCode(t, ctx, tokenz, addr) + storeReflectCode(t, ctx, terpapp, addr) cInfo := wasmKeeper.GetCodeInfo(ctx, 1) require.NotNil(t, cInfo) - return tokenz, ctx + return terpapp, ctx } diff --git a/x/tokenfactory/bindings/message_plugin.go b/x/tokenfactory/bindings/message_plugin.go index 0e67ca2..78d7f2c 100644 --- a/x/tokenfactory/bindings/message_plugin.go +++ b/x/tokenfactory/bindings/message_plugin.go @@ -3,18 +3,19 @@ package bindings import ( "encoding/json" - errorsmod "cosmossdk.io/errors" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" wasmvmtypes "github.com/CosmWasm/wasmvm/types" + + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - - bindingstypes "github.com/terpnetwork/terp-core/x/tokenfactory/bindings/types" - tokenfactorykeeper "github.com/terpnetwork/terp-core/x/tokenfactory/keeper" - tokenfactorytypes "github.com/terpnetwork/terp-core/x/tokenfactory/types" + bindingstypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings/types" + tokenfactorykeeper "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" + tokenfactorytypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) // CustomMessageDecorator returns decorator for custom CosmWasm bindings messages @@ -65,6 +66,9 @@ func (m *CustomMessenger) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddre if tokenMsg.SetMetadata != nil { return m.setMetadata(ctx, contractAddr, tokenMsg.SetMetadata) } + if tokenMsg.ForceTransfer != nil { + return m.forceTransfer(ctx, contractAddr, tokenMsg.ForceTransfer) + } } return m.wrapped.DispatchMsg(ctx, contractAddr, contractIBCPortID, msg) } @@ -134,6 +138,7 @@ func PerformMint(f *tokenfactorykeeper.Keeper, b *bankkeeper.BaseKeeper, ctx sdk coin := sdk.Coin{Denom: mint.Denom, Amount: mint.Amount} sdkMsg := tokenfactorytypes.NewMsgMint(contractAddr.String(), coin) + if err = sdkMsg.ValidateBasic(); err != nil { return err } @@ -144,6 +149,11 @@ func PerformMint(f *tokenfactorykeeper.Keeper, b *bankkeeper.BaseKeeper, ctx sdk if err != nil { return errorsmod.Wrap(err, "minting coins from message") } + + if b.BlockedAddr(rcpt) { + return errorsmod.Wrapf(err, "minting coins to blocked address %s", rcpt.String()) + } + err = b.SendCoins(ctx, contractAddr, rcpt, sdk.NewCoins(coin)) if err != nil { return errorsmod.Wrap(err, "sending newly minted coins from message") @@ -197,12 +207,13 @@ func PerformBurn(f *tokenfactorykeeper.Keeper, ctx sdk.Context, contractAddr sdk if burn == nil { return wasmvmtypes.InvalidRequest{Err: "burn token null mint"} } - if burn.BurnFromAddress != "" && burn.BurnFromAddress != contractAddr.String() { - return wasmvmtypes.InvalidRequest{Err: "BurnFromAddress must be \"\""} - } coin := sdk.Coin{Denom: burn.Denom, Amount: burn.Amount} sdkMsg := tokenfactorytypes.NewMsgBurn(contractAddr.String(), coin) + if burn.BurnFromAddress != "" { + sdkMsg = tokenfactorytypes.NewMsgBurnFrom(contractAddr.String(), coin, burn.BurnFromAddress) + } + if err := sdkMsg.ValidateBasic(); err != nil { return err } @@ -216,6 +227,47 @@ func PerformBurn(f *tokenfactorykeeper.Keeper, ctx sdk.Context, contractAddr sdk return nil } +// forceTransfer moves tokens. +func (m *CustomMessenger) forceTransfer(ctx sdk.Context, contractAddr sdk.AccAddress, forcetransfer *bindingstypes.ForceTransfer) ([]sdk.Event, [][]byte, error) { + err := PerformForceTransfer(m.tokenFactory, ctx, contractAddr, forcetransfer) + if err != nil { + return nil, nil, errorsmod.Wrap(err, "perform force transfer") + } + return nil, nil, nil +} + +// PerformForceTransfer performs token moving after validating tokenForceTransfer message. +func PerformForceTransfer(f *tokenfactorykeeper.Keeper, ctx sdk.Context, contractAddr sdk.AccAddress, forcetransfer *bindingstypes.ForceTransfer) error { + if forcetransfer == nil { + return wasmvmtypes.InvalidRequest{Err: "force transfer null"} + } + + _, err := parseAddress(forcetransfer.FromAddress) + if err != nil { + return err + } + + _, err = parseAddress(forcetransfer.ToAddress) + if err != nil { + return err + } + + coin := sdk.Coin{Denom: forcetransfer.Denom, Amount: forcetransfer.Amount} + sdkMsg := tokenfactorytypes.NewMsgForceTransfer(contractAddr.String(), coin, forcetransfer.FromAddress, forcetransfer.ToAddress) + + if err := sdkMsg.ValidateBasic(); err != nil { + return err + } + + // Transfer through token factory / message server + msgServer := tokenfactorykeeper.NewMsgServerImpl(*f) + _, err = msgServer.ForceTransfer(sdk.WrapSDKContext(ctx), sdkMsg) + if err != nil { + return errorsmod.Wrap(err, "force transferring from message") + } + return nil +} + // createDenom creates a new token denom func (m *CustomMessenger) setMetadata(ctx sdk.Context, contractAddr sdk.AccAddress, setMetadata *bindingstypes.SetMetadata) ([]sdk.Event, [][]byte, error) { err := PerformSetMetadata(m.tokenFactory, m.bank, ctx, contractAddr, setMetadata.Denom, setMetadata.Metadata) diff --git a/x/tokenfactory/bindings/queries.go b/x/tokenfactory/bindings/queries.go index 15dd308..75a21d1 100644 --- a/x/tokenfactory/bindings/queries.go +++ b/x/tokenfactory/bindings/queries.go @@ -6,8 +6,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - bindingstypes "github.com/terpnetwork/terp-core/x/tokenfactory/bindings/types" - tokenfactorykeeper "github.com/terpnetwork/terp-core/x/tokenfactory/keeper" + bindingstypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings/types" + tokenfactorykeeper "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" ) type QueryPlugin struct { diff --git a/x/tokenfactory/bindings/query_plugin.go b/x/tokenfactory/bindings/query_plugin.go index 0dfbfeb..f934663 100644 --- a/x/tokenfactory/bindings/query_plugin.go +++ b/x/tokenfactory/bindings/query_plugin.go @@ -4,12 +4,14 @@ import ( "encoding/json" "fmt" - errorsmod "cosmossdk.io/errors" wasmvmtypes "github.com/CosmWasm/wasmvm/types" + + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - bindingstypes "github.com/terpnetwork/terp-core/x/tokenfactory/bindings/types" + bindingstypes "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings/types" ) // CustomQuerier dispatches custom CosmWasm bindings queries. @@ -17,7 +19,7 @@ func CustomQuerier(qp *QueryPlugin) func(ctx sdk.Context, request json.RawMessag return func(ctx sdk.Context, request json.RawMessage) ([]byte, error) { var contractQuery bindingstypes.TokenFactoryQuery if err := json.Unmarshal(request, &contractQuery); err != nil { - return nil, errorsmod.Wrap(err, "terp query") + return nil, errorsmod.Wrap(err, "osmosis query") } if contractQuery.Token == nil { return nil, errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "nil token field") @@ -31,7 +33,7 @@ func CustomQuerier(qp *QueryPlugin) func(ctx sdk.Context, request json.RawMessag fullDenom, err := GetFullDenom(creator, subdenom) if err != nil { - return nil, errorsmod.Wrap(err, "terp full denom query") + return nil, errorsmod.Wrap(err, "osmo full denom query") } res := bindingstypes.FullDenomResponse{ @@ -117,7 +119,7 @@ func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins { func ConvertSdkCoinToWasmCoin(coin sdk.Coin) wasmvmtypes.Coin { return wasmvmtypes.Coin{ Denom: coin.Denom, - // Note: gamm tokens have 18 decimal places, so 10^22 is common, no longer in u64 range + // Note: tokenfactory tokens have 18 decimal places, so 10^22 is common, no longer in u64 range Amount: coin.Amount.String(), } } diff --git a/x/tokenfactory/bindings/testdata/download_releases.sh b/x/tokenfactory/bindings/testdata/download_releases.sh old mode 100755 new mode 100644 index 161a33f..5413f3b --- a/x/tokenfactory/bindings/testdata/download_releases.sh +++ b/x/tokenfactory/bindings/testdata/download_releases.sh @@ -8,6 +8,9 @@ if [ $# -ne 1 ]; then fi tag="$1" + +# From CosmosContracts/token-bindings + url="https://github.com/CosmWasm/token-bindings/releases/download/$tag/token_reflect.wasm" echo "Downloading $url ..." wget -O "token_reflect.wasm" "$url" diff --git a/x/tokenfactory/bindings/testdata/token_reflect.wasm b/x/tokenfactory/bindings/testdata/token_reflect.wasm index 0d742e1..c27ec80 100644 Binary files a/x/tokenfactory/bindings/testdata/token_reflect.wasm and b/x/tokenfactory/bindings/testdata/token_reflect.wasm differ diff --git a/x/tokenfactory/bindings/testdata/version.txt b/x/tokenfactory/bindings/testdata/version.txt index b19b521..f979ade 100644 --- a/x/tokenfactory/bindings/testdata/version.txt +++ b/x/tokenfactory/bindings/testdata/version.txt @@ -1 +1 @@ -v0.8.0 +v0.9.0 diff --git a/x/tokenfactory/bindings/types/msg.go b/x/tokenfactory/bindings/types/msg.go index 3c6cfa2..538d426 100644 --- a/x/tokenfactory/bindings/types/msg.go +++ b/x/tokenfactory/bindings/types/msg.go @@ -21,6 +21,8 @@ type TokenMsg struct { BurnTokens *BurnTokens `json:"burn_tokens,omitempty"` /// Sets the metadata on a denom which the contract controls SetMetadata *SetMetadata `json:"set_metadata,omitempty"` + /// Forces a transfer of tokens from one address to another. + ForceTransfer *ForceTransfer `json:"force_transfer,omitempty"` } // CreateDenom creates a new factory denom, of denomination: @@ -48,13 +50,19 @@ type MintTokens struct { } type BurnTokens struct { - Denom string `json:"denom"` - Amount math.Int `json:"amount"` - // BurnFromAddress must be set to "" for now. - BurnFromAddress string `json:"burn_from_address"` + Denom string `json:"denom"` + Amount math.Int `json:"amount"` + BurnFromAddress string `json:"burn_from_address"` } type SetMetadata struct { Denom string `json:"denom"` Metadata Metadata `json:"metadata"` } + +type ForceTransfer struct { + Denom string `json:"denom"` + Amount math.Int `json:"amount"` + FromAddress string `json:"from_address"` + ToAddress string `json:"to_address"` +} diff --git a/x/tokenfactory/bindings/validate_msg_test.go b/x/tokenfactory/bindings/validate_msg_test.go index e0a88ce..0d94920 100644 --- a/x/tokenfactory/bindings/validate_msg_test.go +++ b/x/tokenfactory/bindings/validate_msg_test.go @@ -4,27 +4,26 @@ import ( "fmt" "testing" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" - wasmbinding "github.com/terpnetwork/terp-core/x/tokenfactory/bindings" - bindings "github.com/terpnetwork/terp-core/x/tokenfactory/bindings/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" + wasmbinding "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings" + bindings "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) func TestCreateDenom(t *testing.T) { actor := RandomAccountAddress() - tokenz, ctx := SetupCustomApp(t, actor) + terpapp, ctx := SetupCustomApp(t, actor) // Fund actor with 100 base denom creation fees actorAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100))) - fundAccount(t, ctx, tokenz, actor, actorAmount) + fundAccount(t, ctx, terpapp, actor, actorAmount) specs := map[string]struct { createDenom *bindings.CreateDenom expErr bool - expPanic bool }{ "valid sub-denom": { createDenom: &bindings.CreateDenom{ @@ -35,13 +34,13 @@ func TestCreateDenom(t *testing.T) { createDenom: &bindings.CreateDenom{ Subdenom: "", }, - expPanic: true, + expErr: false, }, "invalid sub-denom": { createDenom: &bindings.CreateDenom{ - Subdenom: "sub-denom@2", + Subdenom: "sub-denom_2", }, - expErr: true, + expErr: false, }, "null create denom": { createDenom: nil, @@ -50,17 +49,11 @@ func TestCreateDenom(t *testing.T) { } for name, spec := range specs { t.Run(name, func(t *testing.T) { - if spec.expPanic { - require.Panics(t, func() { - _, err := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, actor, spec.createDenom) - require.Error(t, err) - }) - return - } // when - _, gotErr := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, actor, spec.createDenom) + _, gotErr := wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, actor, spec.createDenom) // then if spec.expErr { + t.Logf("validate_msg_test got error: %v", gotErr) require.Error(t, gotErr) return } @@ -150,18 +143,18 @@ func TestChangeAdmin(t *testing.T) { for name, spec := range specs { t.Run(name, func(t *testing.T) { // Setup - tokenz, ctx := SetupCustomApp(t, tokenCreator) + terpapp, ctx := SetupCustomApp(t, tokenCreator) // Fund actor with 100 base denom creation fees actorAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100))) - fundAccount(t, ctx, tokenz, tokenCreator, actorAmount) + fundAccount(t, ctx, terpapp, tokenCreator, actorAmount) - _, err := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, tokenCreator, &bindings.CreateDenom{ + _, err := wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, tokenCreator, &bindings.CreateDenom{ Subdenom: validDenom, }) require.NoError(t, err) - err = wasmbinding.ChangeAdmin(&tokenz.TokenFactoryKeeper, ctx, spec.actor, spec.changeAdmin) + err = wasmbinding.ChangeAdmin(&terpapp.TokenFactoryKeeper, ctx, spec.actor, spec.changeAdmin) if len(spec.expErrMsg) > 0 { require.Error(t, err) actualErrMsg := err.Error() @@ -175,29 +168,24 @@ func TestChangeAdmin(t *testing.T) { func TestMint(t *testing.T) { creator := RandomAccountAddress() - tokenz, ctx := SetupCustomApp(t, creator) + terpapp, ctx := SetupCustomApp(t, creator) // Fund actor with 100 base denom creation fees tokenCreationFeeAmt := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100))) - fundAccount(t, ctx, tokenz, creator, tokenCreationFeeAmt) + fundAccount(t, ctx, terpapp, creator, tokenCreationFeeAmt) // Create denoms for valid mint tests validDenom := bindings.CreateDenom{ Subdenom: "MOON", } - _, err := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, &validDenom) + _, err := wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, &validDenom) require.NoError(t, err) emptyDenom := bindings.CreateDenom{ Subdenom: "", } - - require.Panics(t, func() { - _, err := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, &emptyDenom) - require.Error(t, err) - }) - // _, err = wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, &emptyDenom) - // require.Error(t, err) + _, err = wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, &emptyDenom) + require.NoError(t, err) validDenomStr := fmt.Sprintf("factory/%s/%s", creator.String(), validDenom.Subdenom) emptyDenomStr := fmt.Sprintf("factory/%s/%s", creator.String(), emptyDenom.Subdenom) @@ -205,7 +193,7 @@ func TestMint(t *testing.T) { lucky := RandomAccountAddress() // lucky was broke - balances := tokenz.BankKeeper.GetAllBalances(ctx, lucky) + balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) require.Empty(t, balances) amount, ok := sdk.NewIntFromString("8080") @@ -228,7 +216,7 @@ func TestMint(t *testing.T) { Amount: amount, MintToAddress: lucky.String(), }, - expErr: true, + expErr: false, }, "nonexistent sub-denom": { mint: &bindings.MintTokens{ @@ -286,7 +274,7 @@ func TestMint(t *testing.T) { for name, spec := range specs { t.Run(name, func(t *testing.T) { // when - gotErr := wasmbinding.PerformMint(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, spec.mint) + gotErr := wasmbinding.PerformMint(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, spec.mint) // then if spec.expErr { require.Error(t, gotErr) @@ -299,31 +287,29 @@ func TestMint(t *testing.T) { func TestBurn(t *testing.T) { creator := RandomAccountAddress() - tokenz, ctx := SetupCustomApp(t, creator) + terpapp, ctx := SetupCustomApp(t, creator) // Fund actor with 100 base denom creation fees tokenCreationFeeAmt := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100))) - fundAccount(t, ctx, tokenz, creator, tokenCreationFeeAmt) + fundAccount(t, ctx, terpapp, creator, tokenCreationFeeAmt) // Create denoms for valid burn tests validDenom := bindings.CreateDenom{ Subdenom: "MOON", } - _, err := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, &validDenom) + _, err := wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, &validDenom) require.NoError(t, err) emptyDenom := bindings.CreateDenom{ Subdenom: "", } - require.Panics(t, func() { - _, err := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, &emptyDenom) - require.Error(t, err) - }) + _, err = wasmbinding.PerformCreateDenom(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, &emptyDenom) + require.NoError(t, err) lucky := RandomAccountAddress() // lucky was broke - balances := tokenz.BankKeeper.GetAllBalances(ctx, lucky) + balances := terpapp.BankKeeper.GetAllBalances(ctx, lucky) require.Empty(t, balances) validDenomStr := fmt.Sprintf("factory/%s/%s", creator.String(), validDenom.Subdenom) @@ -357,7 +343,7 @@ func TestBurn(t *testing.T) { Amount: mintAmount, BurnFromAddress: creator.String(), }, - expErr: true, + expErr: false, }, "invalid sub-denom": { burn: &bindings.BurnTokens{ @@ -405,7 +391,7 @@ func TestBurn(t *testing.T) { Amount: mintAmount, MintToAddress: creator.String(), } - err := wasmbinding.PerformMint(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, mintBinding) + err := wasmbinding.PerformMint(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, mintBinding) require.NoError(t, err) emptyDenomMintBinding := &bindings.MintTokens{ @@ -413,11 +399,11 @@ func TestBurn(t *testing.T) { Amount: mintAmount, MintToAddress: creator.String(), } - err = wasmbinding.PerformMint(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, emptyDenomMintBinding) - require.Error(t, err) + err = wasmbinding.PerformMint(&terpapp.TokenFactoryKeeper, &terpapp.BankKeeper, ctx, creator, emptyDenomMintBinding) + require.NoError(t, err) // when - gotErr := wasmbinding.PerformBurn(&tokenz.TokenFactoryKeeper, ctx, creator, spec.burn) + gotErr := wasmbinding.PerformBurn(&terpapp.TokenFactoryKeeper, ctx, creator, spec.burn) // then if spec.expErr { require.Error(t, gotErr) diff --git a/x/tokenfactory/bindings/validate_queries_test.go b/x/tokenfactory/bindings/validate_queries_test.go index c800103..d9095c8 100644 --- a/x/tokenfactory/bindings/validate_queries_test.go +++ b/x/tokenfactory/bindings/validate_queries_test.go @@ -9,7 +9,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - wasmbinding "github.com/terpnetwork/terp-core/x/tokenfactory/bindings" + wasmbinding "github.com/terpnetwork/terp-core/v2/x/tokenfactory/bindings" ) func TestFullDenom(t *testing.T) { @@ -41,10 +41,10 @@ func TestFullDenom(t *testing.T) { subdenom: "", expFullDenom: fmt.Sprintf("factory/%s/", actor.String()), }, - "invalid sub-denom (contains @)": { - addr: actor.String(), - subdenom: "sub@denom", - expErr: true, + "valid sub-denom (contains underscore)": { + addr: actor.String(), + subdenom: "sub_denom", + expFullDenom: fmt.Sprintf("factory/%s/sub_denom", actor.String()), }, } for name, spec := range specs { @@ -69,7 +69,9 @@ func TestDenomAdmin(t *testing.T) { // set token creation fee to zero to make testing easier tfParams := app.TokenFactoryKeeper.GetParams(ctx) tfParams.DenomCreationFee = sdk.NewCoins() - app.TokenFactoryKeeper.SetParams(ctx, tfParams) + if err := app.TokenFactoryKeeper.SetParams(ctx, tfParams); err != nil { + t.Fatal(err) + } // create a subdenom via the token factory admin := sdk.AccAddress([]byte("addr1_______________")) diff --git a/x/tokenfactory/bindings/wasm.go b/x/tokenfactory/bindings/wasm.go index 33ea401..fd77a21 100644 --- a/x/tokenfactory/bindings/wasm.go +++ b/x/tokenfactory/bindings/wasm.go @@ -1,13 +1,11 @@ package bindings import ( - "github.com/terpnetwork/terp-core/x/wasm" - - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" + wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - tokenfactorykeeper "github.com/terpnetwork/terp-core/x/tokenfactory/keeper" + tokenfactorykeeper "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" ) func RegisterCustomPlugins( @@ -23,7 +21,7 @@ func RegisterCustomPlugins( CustomMessageDecorator(bank, tokenFactory), ) - return []wasm.Option{ + return []wasmkeeper.Option{ queryPluginOpt, messengerDecoratorOpt, } diff --git a/x/tokenfactory/client/cli/query.go b/x/tokenfactory/client/cli/query.go index b23a7e2..d76648e 100644 --- a/x/tokenfactory/client/cli/query.go +++ b/x/tokenfactory/client/cli/query.go @@ -3,17 +3,12 @@ package cli import ( "fmt" - // "strings" - "github.com/spf13/cobra" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - // "github.com/cosmos/cosmos-sdk/client/flags" - // sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) // GetQueryCmd returns the cli query commands for this module diff --git a/x/tokenfactory/client/cli/tx.go b/x/tokenfactory/client/cli/tx.go index 9b0aeff..059dd24 100644 --- a/x/tokenfactory/client/cli/tx.go +++ b/x/tokenfactory/client/cli/tx.go @@ -2,6 +2,8 @@ package cli import ( "fmt" + "strconv" + "strings" "github.com/spf13/cobra" @@ -9,8 +11,9 @@ import ( "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) // GetTxCmd returns the transaction commands for this module @@ -26,9 +29,12 @@ func GetTxCmd() *cobra.Command { cmd.AddCommand( NewCreateDenomCmd(), NewMintCmd(), + NewMintToCmd(), NewBurnCmd(), - // NewForceTransferCmd(), + NewBurnFromCmd(), + NewForceTransferCmd(), NewChangeAdminCmd(), + NewModifyDenomMetadataCmd(), ) return cmd @@ -51,6 +57,8 @@ func NewCreateDenomCmd() *cobra.Command { return err } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) + msg := types.NewMsgCreateDenom( clientCtx.GetFromAddress().String(), args[0], @@ -68,7 +76,7 @@ func NewCreateDenomCmd() *cobra.Command { func NewMintCmd() *cobra.Command { cmd := &cobra.Command{ Use: "mint [amount] [flags]", - Short: "Mint a denom to an address. Must have admin authority to do so.", + Short: "Mint a denom to your address. Must have admin authority to do so.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { clientCtx, err := client.GetClientTxContext(cmd) @@ -81,6 +89,8 @@ func NewMintCmd() *cobra.Command { return err } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) + amount, err := sdk.ParseCoinNormalized(args[0]) if err != nil { return err @@ -99,6 +109,48 @@ func NewMintCmd() *cobra.Command { return cmd } +// NewMintToCmd broadcast MsgMintTo +func NewMintToCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "mint-to [address] [amount] [flags]", + Short: "Mint a denom to an address. Must have admin authority to do so.", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + txf, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) + if err != nil { + return err + } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) + + toAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } + + amount, err := sdk.ParseCoinNormalized(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgMintTo( + clientCtx.GetFromAddress().String(), + amount, + toAddr.String(), + ) + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} + // NewBurnCmd broadcast MsgBurn func NewBurnCmd() *cobra.Command { cmd := &cobra.Command{ @@ -115,6 +167,7 @@ func NewBurnCmd() *cobra.Command { if err != nil { return err } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) amount, err := sdk.ParseCoinNormalized(args[0]) if err != nil { @@ -134,39 +187,85 @@ func NewBurnCmd() *cobra.Command { return cmd } -// // NewForceTransferCmd broadcast MsgForceTransfer -// func NewForceTransferCmd() *cobra.Command { -// cmd := &cobra.Command{ -// Use: "force-transfer [amount] [transfer-from-address] [transfer-to-address] [flags]", -// Short: "Force transfer tokens from one address to another address. Must have admin authority to do so.", -// Args: cobra.ExactArgs(3), -// RunE: func(cmd *cobra.Command, args []string) error { -// clientCtx, err := client.GetClientTxContext(cmd) -// if err != nil { -// return err -// } - -// txf := tx.NewFactoryCLI(clientCtx, cmd.Flags()).WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) - -// amount, err := sdk.ParseCoinNormalized(args[0]) -// if err != nil { -// return err -// } - -// msg := types.NewMsgForceTransfer( -// clientCtx.GetFromAddress().String(), -// amount, -// args[1], -// args[2], -// ) - -// return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) -// }, -// } - -// flags.AddTxFlagsToCmd(cmd) -// return cmd -// } +// NewBurnFromCmd broadcast MsgBurnFrom +func NewBurnFromCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "burn-from [address] [amount] [flags]", + Short: "Burn tokens from an address. Must have admin authority to do so.", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + txf, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) + if err != nil { + return err + } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) + + fromAddr, err := sdk.AccAddressFromBech32(args[0]) + if err != nil { + return err + } + + amount, err := sdk.ParseCoinNormalized(args[1]) + if err != nil { + return err + } + + msg := types.NewMsgBurnFrom( + clientCtx.GetFromAddress().String(), + amount, + fromAddr.String(), + ) + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} + +// NewForceTransferCmd broadcast MsgForceTransfer +func NewForceTransferCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "force-transfer [amount] [transfer-from-address] [transfer-to-address] [flags]", + Short: "Force transfer tokens from one address to another address. Must have admin authority to do so.", + Args: cobra.ExactArgs(3), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + txf, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) + if err != nil { + return err + } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) + + amount, err := sdk.ParseCoinNormalized(args[0]) + if err != nil { + return err + } + + msg := types.NewMsgForceTransfer( + clientCtx.GetFromAddress().String(), + amount, + args[1], + args[2], + ) + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} // NewChangeAdminCmd broadcast MsgChangeAdmin func NewChangeAdminCmd() *cobra.Command { @@ -184,6 +283,7 @@ func NewChangeAdminCmd() *cobra.Command { if err != nil { return err } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) msg := types.NewMsgChangeAdmin( clientCtx.GetFromAddress().String(), @@ -198,3 +298,70 @@ func NewChangeAdminCmd() *cobra.Command { flags.AddTxFlagsToCmd(cmd) return cmd } + +// NewModifyDenomMetadataCmd broadcast a Bank Metadata modification transaction +func NewModifyDenomMetadataCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "modify-metadata [denom] [ticker-symbol] [description] [exponent] [flags]", + Short: "Changes the base data for frontends to query the data of.", + Args: cobra.ExactArgs(4), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + txf, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) + if err != nil { + return err + } + txf = txf.WithTxConfig(clientCtx.TxConfig).WithAccountRetriever(clientCtx.AccountRetriever) + + fullDenom, ticker, desc := args[0], strings.ToUpper(args[1]), args[2] + + if !strings.HasPrefix(fullDenom, "factory/") { + return fmt.Errorf("denom must start with factory/") + } + + if len(ticker) == 0 { + return fmt.Errorf("ticker cannot be empty") + } + + // Exponent Checks + exponent, err := strconv.ParseUint(args[3], 10, 32) + if err != nil { + return err + } + + bankMetadata := banktypes.Metadata{ + Description: desc, + Display: fullDenom, + Symbol: ticker, + Name: fullDenom, + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: fullDenom, + Exponent: 0, // must be 0 for the base denom + Aliases: []string{ticker}, + }, + { + Denom: ticker, + Exponent: uint32(exponent), + Aliases: []string{fullDenom}, + }, + }, + Base: fullDenom, + } + + msg := types.NewMsgSetDenomMetadata( + clientCtx.GetFromAddress().String(), + bankMetadata, + ) + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} diff --git a/x/tokenfactory/exported/exported.go b/x/tokenfactory/exported/exported.go new file mode 100644 index 0000000..000114e --- /dev/null +++ b/x/tokenfactory/exported/exported.go @@ -0,0 +1,18 @@ +package exported + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +type ( + ParamSet = paramtypes.ParamSet + + // Subspace defines an interface that implements the legacy x/params Subspace + // type. + // + // NOTE: This is used solely for migration of x/params managed parameters. + Subspace interface { + GetParamSet(ctx sdk.Context, ps ParamSet) + } +) diff --git a/x/tokenfactory/keeper/admins.go b/x/tokenfactory/keeper/admins.go index 665895b..ba4aa7c 100644 --- a/x/tokenfactory/keeper/admins.go +++ b/x/tokenfactory/keeper/admins.go @@ -1,10 +1,11 @@ package keeper import ( - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/gogoproto/proto" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) // GetAuthorityMetadata returns the authority metadata for a specific denom diff --git a/x/tokenfactory/keeper/admins_test.go b/x/tokenfactory/keeper/admins_test.go index 335320f..ac602a5 100644 --- a/x/tokenfactory/keeper/admins_test.go +++ b/x/tokenfactory/keeper/admins_test.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) func (suite *KeeperTestSuite) TestAdminMsgs() { @@ -29,11 +29,19 @@ func (suite *KeeperTestSuite) TestAdminMsgs() { suite.Require().NoError(err) suite.Require().True(bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom).Amount.Int64() == addr0bal, bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom)) - // // Test force transferring - // _, err = suite.msgServer.ForceTransfer(sdk.WrapSDKContext(suite.Ctx), types.NewMsgForceTransfer(suite.TestAccs[0].String(), sdk.NewInt64Coin(denom, 5), suite.TestAccs[1].String(), suite.TestAccs[0].String())) - // suite.Require().NoError(err) - // suite.Require().True(bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], denom).IsEqual(sdk.NewInt64Coin(denom, 15))) - // suite.Require().True(bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], denom).IsEqual(sdk.NewInt64Coin(denom, 5))) + // Test minting to a different account + _, err = suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMintTo(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 10), suite.TestAccs[1].String())) + addr1bal += 10 + suite.Require().NoError(err) + suite.Require().True(suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom).Amount.Int64() == addr1bal, suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom)) + + // Test force transferring + _, err = suite.msgServer.ForceTransfer(sdk.WrapSDKContext(suite.Ctx), types.NewMsgForceTransfer(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 5), suite.TestAccs[1].String(), suite.TestAccs[0].String())) + addr1bal -= 5 + addr0bal += 5 + suite.Require().NoError(err) + suite.Require().True(suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom).Amount.Int64() == addr0bal, suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom)) + suite.Require().True(suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom).Amount.Int64() == addr1bal, suite.App.BankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom)) // Test burning from own account _, err = suite.msgServer.Burn(sdk.WrapSDKContext(suite.Ctx), types.NewMsgBurn(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 5))) @@ -74,114 +82,227 @@ func (suite *KeeperTestSuite) TestAdminMsgs() { // * Only the admin of a denom can mint tokens for it // * The admin of a denom can mint tokens for it func (suite *KeeperTestSuite) TestMintDenom() { - var addr0bal int64 + balances := make(map[string]int64) + for _, acc := range suite.TestAccs { + balances[acc.String()] = 0 + } // Create a denom suite.CreateDefaultDenom() for _, tc := range []struct { - desc string - amount int64 - mintDenom string - admin string - valid bool + desc string + mintMsg types.MsgMint + expectPass bool }{ { - desc: "denom does not exist", - amount: 10, - mintDenom: "factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", - admin: suite.TestAccs[0].String(), - valid: false, + desc: "denom does not exist", + mintMsg: *types.NewMsgMint( + suite.TestAccs[0].String(), + sdk.NewInt64Coin("factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", 10), + ), + expectPass: false, + }, + { + desc: "mint is not by the admin", + mintMsg: *types.NewMsgMintTo( + suite.TestAccs[1].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10), + suite.TestAccs[0].String(), + ), + expectPass: false, }, { - desc: "mint is not by the admin", - amount: 10, - mintDenom: suite.defaultDenom, - admin: suite.TestAccs[1].String(), - valid: false, + desc: "success case - mint to self", + mintMsg: *types.NewMsgMint( + suite.TestAccs[0].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10), + ), + expectPass: true, }, { - desc: "success case", - amount: 10, - mintDenom: suite.defaultDenom, - admin: suite.TestAccs[0].String(), - valid: true, + desc: "success case - mint to another address", + mintMsg: *types.NewMsgMintTo( + suite.TestAccs[0].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10), + suite.TestAccs[1].String(), + ), + expectPass: true, }, } { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { - // Test minting to admins own account - bankKeeper := suite.App.BankKeeper - _, err := suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMint(tc.admin, sdk.NewInt64Coin(tc.mintDenom, 10))) - if tc.valid { - addr0bal += 10 + tc := tc + _, err := suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), &tc.mintMsg) + if tc.expectPass { suite.Require().NoError(err) - suite.Require().Equal(bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom).Amount.Int64(), addr0bal, bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom)) + balances[tc.mintMsg.MintToAddress] += tc.mintMsg.Amount.Amount.Int64() } else { suite.Require().Error(err) } + + mintToAddr, _ := sdk.AccAddressFromBech32(tc.mintMsg.MintToAddress) + bal := suite.App.BankKeeper.GetBalance(suite.Ctx, mintToAddr, suite.defaultDenom).Amount + suite.Require().Equal(bal.Int64(), balances[tc.mintMsg.MintToAddress]) }) } } func (suite *KeeperTestSuite) TestBurnDenom() { - var addr0bal int64 + // Create a denom. + suite.CreateDefaultDenom() + + // mint 1000 default token for all testAccs + balances := make(map[string]int64) + for _, acc := range suite.TestAccs { + _, err := suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMintTo(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 1000), acc.String())) + suite.Require().NoError(err) + balances[acc.String()] = 1000 + } + + for _, tc := range []struct { + desc string + burnMsg types.MsgBurn + expectPass bool + }{ + { + desc: "denom does not exist", + burnMsg: *types.NewMsgBurn( + suite.TestAccs[0].String(), + sdk.NewInt64Coin("factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", 10), + ), + expectPass: false, + }, + { + desc: "burn is not by the admin", + burnMsg: *types.NewMsgBurnFrom( + suite.TestAccs[1].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10), + suite.TestAccs[0].String(), + ), + expectPass: false, + }, + { + desc: "burn more than balance", + burnMsg: *types.NewMsgBurn( + suite.TestAccs[0].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10000), + ), + expectPass: false, + }, + { + desc: "success case - burn from self", + burnMsg: *types.NewMsgBurn( + suite.TestAccs[0].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10), + ), + expectPass: true, + }, + { + desc: "success case - burn from another address", + burnMsg: *types.NewMsgBurnFrom( + suite.TestAccs[0].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10), + suite.TestAccs[1].String(), + ), + expectPass: true, + }, + } { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + tc := tc + _, err := suite.msgServer.Burn(sdk.WrapSDKContext(suite.Ctx), &tc.burnMsg) + if tc.expectPass { + suite.Require().NoError(err) + balances[tc.burnMsg.BurnFromAddress] -= tc.burnMsg.Amount.Amount.Int64() + } else { + suite.Require().Error(err) + } + + burnFromAddr, _ := sdk.AccAddressFromBech32(tc.burnMsg.BurnFromAddress) + bal := suite.App.BankKeeper.GetBalance(suite.Ctx, burnFromAddr, suite.defaultDenom).Amount + suite.Require().Equal(bal.Int64(), balances[tc.burnMsg.BurnFromAddress]) + }) + } +} +func (suite *KeeperTestSuite) TestForceTransferDenom() { // Create a denom. suite.CreateDefaultDenom() - // mint 10 default token for testAcc[0] - _, err := suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMint(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 10))) - suite.Require().NoError(err) - addr0bal += 10 + // mint 1000 default token for all testAccs + balances := make(map[string]int64) + for _, acc := range suite.TestAccs { + _, err := suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMintTo(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 1000), acc.String())) + suite.Require().NoError(err) + balances[acc.String()] = 1000 + } for _, tc := range []struct { - desc string - amount int64 - burnDenom string - admin string - valid bool + desc string + forceTransferMsg types.MsgForceTransfer + expectPass bool }{ { - desc: "denom does not exist", - amount: 10, - burnDenom: "factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", - admin: suite.TestAccs[0].String(), - valid: false, + desc: "valid force transfer", + forceTransferMsg: *types.NewMsgForceTransfer( + suite.TestAccs[0].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10), + suite.TestAccs[1].String(), + suite.TestAccs[2].String(), + ), + expectPass: true, }, { - desc: "burn is not by the admin", - amount: 10, - burnDenom: suite.defaultDenom, - admin: suite.TestAccs[1].String(), - valid: false, + desc: "denom does not exist", + forceTransferMsg: *types.NewMsgForceTransfer( + suite.TestAccs[0].String(), + sdk.NewInt64Coin("factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", 10), + suite.TestAccs[1].String(), + suite.TestAccs[2].String(), + ), + expectPass: false, }, { - desc: "burn amount is bigger than minted amount", - amount: 1000, - burnDenom: suite.defaultDenom, - admin: suite.TestAccs[1].String(), - valid: false, + desc: "forceTransfer is not by the admin", + forceTransferMsg: *types.NewMsgForceTransfer( + suite.TestAccs[1].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10), + suite.TestAccs[1].String(), + suite.TestAccs[2].String(), + ), + expectPass: false, }, { - desc: "success case", - amount: 10, - burnDenom: suite.defaultDenom, - admin: suite.TestAccs[0].String(), - valid: true, + desc: "forceTransfer is greater than the balance of", + forceTransferMsg: *types.NewMsgForceTransfer( + suite.TestAccs[0].String(), + sdk.NewInt64Coin(suite.defaultDenom, 10000), + suite.TestAccs[1].String(), + suite.TestAccs[2].String(), + ), + expectPass: false, }, } { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { - // Test minting to admins own account - bankKeeper := suite.App.BankKeeper - _, err := suite.msgServer.Burn(sdk.WrapSDKContext(suite.Ctx), types.NewMsgBurn(tc.admin, sdk.NewInt64Coin(tc.burnDenom, 10))) - if tc.valid { - addr0bal -= 10 + tc := tc + _, err := suite.msgServer.ForceTransfer(sdk.WrapSDKContext(suite.Ctx), &tc.forceTransferMsg) + if tc.expectPass { suite.Require().NoError(err) - suite.Require().True(bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom).Amount.Int64() == addr0bal, bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom)) + + balances[tc.forceTransferMsg.TransferFromAddress] -= tc.forceTransferMsg.Amount.Amount.Int64() + balances[tc.forceTransferMsg.TransferToAddress] += tc.forceTransferMsg.Amount.Amount.Int64() } else { suite.Require().Error(err) - suite.Require().True(bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom).Amount.Int64() == addr0bal, bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], suite.defaultDenom)) } + + fromAddr, err := sdk.AccAddressFromBech32(tc.forceTransferMsg.TransferFromAddress) + suite.Require().NoError(err) + fromBal := suite.App.BankKeeper.GetBalance(suite.Ctx, fromAddr, suite.defaultDenom).Amount + suite.Require().True(fromBal.Int64() == balances[tc.forceTransferMsg.TransferFromAddress]) + + toAddr, err := sdk.AccAddressFromBech32(tc.forceTransferMsg.TransferToAddress) + suite.Require().NoError(err) + toBal := suite.App.BankKeeper.GetBalance(suite.Ctx, toAddr, suite.defaultDenom).Amount + suite.Require().True(toBal.Int64() == balances[tc.forceTransferMsg.TransferToAddress]) }) } } @@ -387,6 +508,7 @@ func (suite *KeeperTestSuite) TestSetDenomMetaData() { }, } { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + tc := tc bankKeeper := suite.App.BankKeeper res, err := suite.msgServer.SetDenomMetadata(sdk.WrapSDKContext(suite.Ctx), &tc.msgSetDenomMetadata) if tc.expectedPass { diff --git a/x/tokenfactory/keeper/bankactions.go b/x/tokenfactory/keeper/bankactions.go index 803c4c3..dbe92b5 100644 --- a/x/tokenfactory/keeper/bankactions.go +++ b/x/tokenfactory/keeper/bankactions.go @@ -1,9 +1,11 @@ package keeper import ( + "fmt" + sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) func (k Keeper) mintTo(ctx sdk.Context, amount sdk.Coin, mintTo string) error { @@ -23,6 +25,10 @@ func (k Keeper) mintTo(ctx sdk.Context, amount sdk.Coin, mintTo string) error { return err } + if k.bankKeeper.BlockedAddr(addr) { + return fmt.Errorf("failed to mint to blocked address: %s", addr) + } + return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, addr, sdk.NewCoins(amount)) @@ -40,6 +46,10 @@ func (k Keeper) burnFrom(ctx sdk.Context, amount sdk.Coin, burnFrom string) erro return err } + if k.bankKeeper.BlockedAddr(addr) { + return fmt.Errorf("failed to burn from blocked address: %s", addr) + } + err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, addr, types.ModuleName, @@ -51,8 +61,7 @@ func (k Keeper) burnFrom(ctx sdk.Context, amount sdk.Coin, burnFrom string) erro return k.bankKeeper.BurnCoins(ctx, types.ModuleName, sdk.NewCoins(amount)) } -// forceTransfer is a helper function to transfer coins from one account to another -func (k Keeper) forceTransfer(ctx sdk.Context, amount sdk.Coin, fromAddr string, toAddr string) error { //nolint:unused +func (k Keeper) forceTransfer(ctx sdk.Context, amount sdk.Coin, fromAddr string, toAddr string) error { // verify that denom is an x/tokenfactory denom _, _, err := types.DeconstructDenom(amount.Denom) if err != nil { @@ -69,5 +78,9 @@ func (k Keeper) forceTransfer(ctx sdk.Context, amount sdk.Coin, fromAddr string, return err } + if k.bankKeeper.BlockedAddr(toSdkAddr) { + return fmt.Errorf("failed to force transfer to blocked address: %s", toSdkAddr) + } + return k.bankKeeper.SendCoins(ctx, fromSdkAddr, toSdkAddr, sdk.NewCoins(amount)) } diff --git a/x/tokenfactory/keeper/createdenom.go b/x/tokenfactory/keeper/createdenom.go index 4c5fe3e..5411ca8 100644 --- a/x/tokenfactory/keeper/createdenom.go +++ b/x/tokenfactory/keeper/createdenom.go @@ -1,12 +1,10 @@ package keeper import ( - "fmt" - sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) // ConvertToBaseToken converts a fee amount in a whitelisted fee token to the base fee token amount @@ -34,6 +32,10 @@ func (k Keeper) createDenomAfterValidation(ctx sdk.Context, creatorAddr string, Exponent: 0, }}, Base: denom, + // The following is necessary for x/bank denom validation + Display: denom, + Name: denom, + Symbol: denom, } k.bankKeeper.SetDenomMetaData(ctx, denomMetaData) @@ -51,11 +53,12 @@ func (k Keeper) createDenomAfterValidation(ctx sdk.Context, creatorAddr string, } func (k Keeper) validateCreateDenom(ctx sdk.Context, creatorAddr string, subdenom string) (newTokenDenom string, err error) { + // TODO: This was a nil key on Store issue. Removed as we are upgrading IBC versions now // Temporary check until IBC bug is sorted out - if k.bankKeeper.HasSupply(ctx, subdenom) { - return "", fmt.Errorf("temporary error until IBC bug is sorted out, " + - "can't create subdenoms that are the same as a native denom") - } + // if k.bankKeeper.HasSupply(ctx, subdenom) { + // return "", fmt.Errorf("temporary error until IBC bug is sorted out, " + + // "can't create subdenoms that are the same as a native denom") + // } denom, err := types.GetTokenDenom(creatorAddr, subdenom) if err != nil { @@ -70,17 +73,26 @@ func (k Keeper) validateCreateDenom(ctx sdk.Context, creatorAddr string, subdeno return denom, nil } -func (k Keeper) chargeForCreateDenom(ctx sdk.Context, creatorAddr string, subdenom string) (err error) { //nolint:unparam - // Send creation fee to community pool - creationFee := k.GetParams(ctx).DenomCreationFee - accAddr, err := sdk.AccAddressFromBech32(creatorAddr) - if err != nil { - return err - } - if creationFee != nil { - if err := k.communityPoolKeeper.FundCommunityPool(ctx, creationFee, accAddr); err != nil { +func (k Keeper) chargeForCreateDenom(ctx sdk.Context, creatorAddr string, _ string) (err error) { + params := k.GetParams(ctx) + + // if DenomCreationFee is non-zero, transfer the tokens from the creator + // account to community pool + if params.DenomCreationFee != nil { + accAddr, err := sdk.AccAddressFromBech32(creatorAddr) + if err != nil { + return err + } + + if err := k.communityPoolKeeper.FundCommunityPool(ctx, params.DenomCreationFee, accAddr); err != nil { return err } } + + // if DenomCreationGasConsume is non-zero, consume the gas + if params.DenomCreationGasConsume != 0 { + ctx.GasMeter().ConsumeGas(params.DenomCreationGasConsume, "consume denom creation gas") + } + return nil } diff --git a/x/tokenfactory/keeper/createdenom_test.go b/x/tokenfactory/keeper/createdenom_test.go index 1900bbf..b64c50a 100644 --- a/x/tokenfactory/keeper/createdenom_test.go +++ b/x/tokenfactory/keeper/createdenom_test.go @@ -4,9 +4,10 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/testhelpers" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/app/apptesting" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) func (suite *KeeperTestSuite) TestMsgCreateDenom() { @@ -31,6 +32,13 @@ func (suite *KeeperTestSuite) TestMsgCreateDenom() { suite.Require().NoError(err) suite.Require().Equal(suite.TestAccs[0].String(), queryRes.AuthorityMetadata.Admin) + // Make sure that the denom is valid from the perspective of x/bank + bankQueryRes, err := suite.bankQueryClient.DenomMetadata(suite.Ctx.Context(), &banktypes.QueryDenomMetadataRequest{ + Denom: res.GetNewTokenDenom(), + }) + suite.Require().NoError(err) + suite.Require().NoError(bankQueryRes.Metadata.Validate()) + // Make sure that creation fee was deducted postCreateBalance := bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], tokenFactoryKeeper.GetParams(suite.Ctx).DenomCreationFee[0].Denom) suite.Require().True(preCreateBalance.Sub(postCreateBalance).IsEqual(denomCreationFee[0])) @@ -64,7 +72,7 @@ func (suite *KeeperTestSuite) TestMsgCreateDenom() { func (suite *KeeperTestSuite) TestCreateDenom() { var ( primaryDenom = types.DefaultParams().DenomCreationFee[0].Denom - secondaryDenom = testhelpers.SecondaryDenom + secondaryDenom = apptesting.SecondaryDenom defaultDenomCreationFee = types.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, sdk.NewInt(50000000)))} twoDenomCreationFee = types.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, sdk.NewInt(50000000)), sdk.NewCoin(secondaryDenom, sdk.NewInt(50000000)))} nilCreationFee = types.Params{DenomCreationFee: nil} @@ -133,17 +141,23 @@ func (suite *KeeperTestSuite) TestCreateDenom() { tokenFactoryKeeper := suite.App.TokenFactoryKeeper bankKeeper := suite.App.BankKeeper // Set denom creation fee in params - tokenFactoryKeeper.SetParams(suite.Ctx, tc.denomCreationFee) + if err := tokenFactoryKeeper.SetParams(suite.Ctx, tc.denomCreationFee); err != nil { + suite.Require().NoError(err) + } denomCreationFee := tokenFactoryKeeper.GetParams(suite.Ctx).DenomCreationFee suite.Require().Equal(tc.denomCreationFee.DenomCreationFee, denomCreationFee) // note balance, create a tokenfactory denom, then note balance again - preCreateBalance := bankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0]) + // preCreateBalance := bankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0]) + preCreateBalance := bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], "stake") res, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), tc.subdenom)) - postCreateBalance := bankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0]) + // postCreateBalance := bankKeeper.GetAllBalances(suite.Ctx, suite.TestAccs[0]) + postCreateBalance := bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], "stake") if tc.valid { suite.Require().NoError(err) - suite.Require().True(preCreateBalance.Sub(postCreateBalance...).IsEqual(denomCreationFee)) + if denomCreationFee != nil { + suite.Require().True(preCreateBalance.Sub(postCreateBalance).IsEqual(denomCreationFee[0])) + } // Make sure that the admin is set correctly queryRes, err := suite.queryClient.DenomAuthorityMetadata(suite.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{ diff --git a/x/tokenfactory/keeper/creators.go b/x/tokenfactory/keeper/creators.go index 570d54b..d200c06 100644 --- a/x/tokenfactory/keeper/creators.go +++ b/x/tokenfactory/keeper/creators.go @@ -25,3 +25,5 @@ func (k Keeper) GetDenomsFromCreator(ctx sdk.Context, creator string) []string { func (k Keeper) GetAllDenomsIterator(ctx sdk.Context) sdk.Iterator { return k.GetCreatorsPrefixStore(ctx).Iterator(nil, nil) } + +// TODO: Get all denoms a user is the admin of currently diff --git a/x/tokenfactory/keeper/genesis.go b/x/tokenfactory/keeper/genesis.go index 52577e8..dfd5875 100644 --- a/x/tokenfactory/keeper/genesis.go +++ b/x/tokenfactory/keeper/genesis.go @@ -3,7 +3,7 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) // InitGenesis initializes the tokenfactory module's state from a provided genesis @@ -14,7 +14,9 @@ func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { if genState.Params.DenomCreationFee == nil { genState.Params.DenomCreationFee = sdk.NewCoins() } - k.SetParams(ctx, genState.Params) + if err := k.SetParams(ctx, genState.Params); err != nil { + panic(err) + } for _, genDenom := range genState.GetFactoryDenoms() { creator, _, err := types.DeconstructDenom(genDenom.GetDenom()) diff --git a/x/tokenfactory/keeper/genesis_test.go b/x/tokenfactory/keeper/genesis_test.go index a04ef9b..71e8711 100644 --- a/x/tokenfactory/keeper/genesis_test.go +++ b/x/tokenfactory/keeper/genesis_test.go @@ -4,28 +4,28 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) func (suite *KeeperTestSuite) TestGenesis() { genesisState := types.GenesisState{ FactoryDenoms: []types.GenesisDenom{ { - Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + Denom: "factory/terp1t7egva48prqmzl59x5ngv4zx0dtrwewc22y7f5/bitcoin", AuthorityMetadata: types.DenomAuthorityMetadata{ - Admin: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + Admin: "terp1t7egva48prqmzl59x5ngv4zx0dtrwewc22y7f5", }, }, { - Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/diff-admin", + Denom: "factory/terp1t7egva48prqmzl59x5ngv4zx0dtrwewc22y7f5/diff-admin", AuthorityMetadata: types.DenomAuthorityMetadata{ - Admin: "cosmos15czt5nhlnvayqq37xun9s9yus0d6y26dx74r5p", + Admin: "terp15czt5nhlnvayqq37xun9s9yus0d6y26dp5u07j", }, }, { - Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/litecoin", + Denom: "factory/terp1t7egva48prqmzl59x5ngv4zx0dtrwewc22y7f5/litecoin", AuthorityMetadata: types.DenomAuthorityMetadata{ - Admin: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + Admin: "terp1t7egva48prqmzl59x5ngv4zx0dtrwewc22y7f5", }, }, }, @@ -42,15 +42,13 @@ func (suite *KeeperTestSuite) TestGenesis() { } } - // check before initGenesis that the module account is nil - tokenfactoryModuleAccount := app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName)) - suite.Require().Nil(tokenfactoryModuleAccount) - - app.TokenFactoryKeeper.SetParams(suite.Ctx, types.Params{DenomCreationFee: sdk.Coins{sdk.NewInt64Coin("uosmo", 100)}}) + if err := app.TokenFactoryKeeper.SetParams(suite.Ctx, types.Params{DenomCreationFee: sdk.Coins{sdk.NewInt64Coin("stake", 100)}}); err != nil { + panic(err) + } app.TokenFactoryKeeper.InitGenesis(suite.Ctx, genesisState) // check that the module account is now initialized - tokenfactoryModuleAccount = app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName)) + tokenfactoryModuleAccount := app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName)) suite.Require().NotNil(tokenfactoryModuleAccount) exportedGenesis := app.TokenFactoryKeeper.ExportGenesis(suite.Ctx) diff --git a/x/tokenfactory/keeper/grpc_query.go b/x/tokenfactory/keeper/grpc_query.go index 2ee7191..5ced656 100644 --- a/x/tokenfactory/keeper/grpc_query.go +++ b/x/tokenfactory/keeper/grpc_query.go @@ -5,12 +5,12 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) var _ types.QueryServer = Keeper{} -func (k Keeper) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { +func (k Keeper) Params(ctx context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { sdkCtx := sdk.UnwrapSDKContext(ctx) params := k.GetParams(sdkCtx) diff --git a/x/tokenfactory/keeper/keeper.go b/x/tokenfactory/keeper/keeper.go index 2ce23cd..2eb024d 100644 --- a/x/tokenfactory/keeper/keeper.go +++ b/x/tokenfactory/keeper/keeper.go @@ -5,50 +5,61 @@ import ( "github.com/cometbft/cometbft/libs/log" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store/prefix" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/tokenfactory/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) type ( Keeper struct { + cdc codec.BinaryCodec storeKey storetypes.StoreKey - paramSpace paramtypes.Subspace - accountKeeper types.AccountKeeper bankKeeper types.BankKeeper communityPoolKeeper types.CommunityPoolKeeper + + enabledCapabilities []string + + // the address capable of executing a MsgUpdateParams message. Typically, this + // should be the x/gov module account. + authority string } ) // NewKeeper returns a new instance of the x/tokenfactory keeper func NewKeeper( + cdc codec.BinaryCodec, storeKey storetypes.StoreKey, - paramSpace paramtypes.Subspace, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, communityPoolKeeper types.CommunityPoolKeeper, + enabledCapabilities []string, + authority string, ) Keeper { - if !paramSpace.HasKeyTable() { - paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) - } - return Keeper{ - storeKey: storeKey, - paramSpace: paramSpace, + cdc: cdc, + storeKey: storeKey, accountKeeper: accountKeeper, bankKeeper: bankKeeper, communityPoolKeeper: communityPoolKeeper, + + enabledCapabilities: enabledCapabilities, + + authority: authority, } } +// GetAuthority returns the x/mint module's authority. +func (k Keeper) GetAuthority() string { + return k.authority +} + // Logger returns a logger for the x/tokenfactory module func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) diff --git a/x/tokenfactory/keeper/keeper_test.go b/x/tokenfactory/keeper/keeper_test.go index 75581e3..ec06ea1 100644 --- a/x/tokenfactory/keeper/keeper_test.go +++ b/x/tokenfactory/keeper/keeper_test.go @@ -3,21 +3,24 @@ package keeper_test import ( "testing" + "github.com/stretchr/testify/suite" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/suite" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/terpnetwork/terp-core/app/apptesting" - "github.com/terpnetwork/terp-core/x/tokenfactory/keeper" - "github.com/terpnetwork/terp-core/x/tokenfactory/testhelpers" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/app/apptesting" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) type KeeperTestSuite struct { apptesting.KeeperTestHelper - queryClient types.QueryClient - msgServer types.MsgServer + queryClient types.QueryClient + bankQueryClient banktypes.QueryClient + msgServer types.MsgServer // defaultDenom is on the suite, as it depends on the creator test address. defaultDenom string } @@ -28,13 +31,15 @@ func TestKeeperTestSuite(t *testing.T) { func (suite *KeeperTestSuite) SetupTest() { suite.Setup() + // Fund every TestAcc with two denoms, one of which is the denom creation fee - fundAccsAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100)), sdk.NewCoin(testhelpers.SecondaryDenom, testhelpers.SecondaryAmount)) + fundAccsAmount := sdk.NewCoins(sdk.NewCoin(types.DefaultParams().DenomCreationFee[0].Denom, types.DefaultParams().DenomCreationFee[0].Amount.MulRaw(100)), sdk.NewCoin(apptesting.SecondaryDenom, apptesting.SecondaryAmount)) for _, acc := range suite.TestAccs { suite.FundAcc(acc, fundAccsAmount) } suite.queryClient = types.NewQueryClient(suite.QueryHelper) + suite.bankQueryClient = banktypes.NewQueryClient(suite.QueryHelper) suite.msgServer = keeper.NewMsgServerImpl(suite.App.TokenFactoryKeeper) } @@ -51,7 +56,7 @@ func (suite *KeeperTestSuite) TestCreateModuleAccount() { app.AccountKeeper.RemoveAccount(suite.Ctx, tokenfactoryModuleAccount) // ensure module account was removed - suite.Ctx = app.BaseApp.NewContext(false, tmproto.Header{}) + suite.Ctx = app.BaseApp.NewContext(false, tmproto.Header{ChainID: "testing"}) tokenfactoryModuleAccount = app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName)) suite.Require().Nil(tokenfactoryModuleAccount) diff --git a/x/tokenfactory/keeper/migrator.go b/x/tokenfactory/keeper/migrator.go new file mode 100644 index 0000000..0a5ac69 --- /dev/null +++ b/x/tokenfactory/keeper/migrator.go @@ -0,0 +1,61 @@ +package keeper + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/exported" + v2 "github.com/terpnetwork/terp-core/v2/x/tokenfactory/migrations/v2" +) + +// Migrator is a struct for handling in-place state migrations. +type Migrator struct { + keeper Keeper + legacySubspace exported.Subspace +} + +func NewMigrator(k Keeper, ss exported.Subspace) Migrator { + return Migrator{ + keeper: k, + legacySubspace: ss, + } +} + +// Migrate1to2 migrates the x/tokenfactory module state from the consensus version 1 to +// version 2. Specifically, it takes the parameters that are currently stored +// and managed by the x/params modules and stores them directly into the x/tokenfactory +// module state. +func (m Migrator) Migrate1to2(ctx sdk.Context) error { + // Fixes hard forking genesis being invalid. + // https://github.com/sei-protocol/sei-chain/pull/861 + iter := m.keeper.GetAllDenomsIterator(ctx) + defer iter.Close() + for ; iter.Valid(); iter.Next() { + denom := string(iter.Value()) + if denomMetadata, err := m.keeper.bankKeeper.GetDenomMetaData(ctx, denom); !err { + panic(fmt.Errorf("denom %s does not exist", denom)) + } else { + fmt.Printf("Migrating denom: %s\n", denom) + m.SetMetadata(&denomMetadata) + m.keeper.bankKeeper.SetDenomMetaData(ctx, denomMetadata) + } + + } + + return v2.Migrate(ctx, ctx.KVStore(m.keeper.storeKey), m.legacySubspace, m.keeper.cdc) +} + +func (m Migrator) SetMetadata(denomMetadata *banktypes.Metadata) { + if len(denomMetadata.Base) == 0 { + panic(fmt.Errorf("no base exists for denom %v", denomMetadata)) + } + if len(denomMetadata.Display) == 0 { + denomMetadata.Display = denomMetadata.Base + denomMetadata.Name = denomMetadata.Base + denomMetadata.Symbol = denomMetadata.Base + } else { + fmt.Printf("Denom %s already has denom set", denomMetadata.Base) + } +} diff --git a/x/tokenfactory/keeper/msg_server.go b/x/tokenfactory/keeper/msg_server.go index 9bd98ed..098db8e 100644 --- a/x/tokenfactory/keeper/msg_server.go +++ b/x/tokenfactory/keeper/msg_server.go @@ -3,9 +3,12 @@ package keeper import ( "context" + "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) type msgServer struct { @@ -21,6 +24,10 @@ func NewMsgServerImpl(keeper Keeper) types.MsgServer { var _ types.MsgServer = msgServer{} func (server msgServer) CreateDenom(goCtx context.Context, msg *types.MsgCreateDenom) (*types.MsgCreateDenomResponse, error) { + if err := msg.ValidateBasic(); err != nil { + return nil, err + } + ctx := sdk.UnwrapSDKContext(goCtx) denom, err := server.Keeper.CreateDenom(ctx, msg.Sender, msg.Subdenom) @@ -59,7 +66,11 @@ func (server msgServer) Mint(goCtx context.Context, msg *types.MsgMint) (*types. return nil, types.ErrUnauthorized } - err = server.Keeper.mintTo(ctx, msg.Amount, msg.Sender) + if msg.MintToAddress == "" { + msg.MintToAddress = msg.Sender + } + + err = server.Keeper.mintTo(ctx, msg.Amount, msg.MintToAddress) if err != nil { return nil, err } @@ -87,7 +98,13 @@ func (server msgServer) Burn(goCtx context.Context, msg *types.MsgBurn) (*types. return nil, types.ErrUnauthorized } - err = server.Keeper.burnFrom(ctx, msg.Amount, msg.Sender) + if msg.BurnFromAddress == "" { + msg.BurnFromAddress = msg.Sender + } else if !types.IsCapabilityEnabled(server.Keeper.enabledCapabilities, types.EnableBurnFrom) { + return nil, types.ErrCapabilityNotEnabled + } + + err = server.Keeper.burnFrom(ctx, msg.Amount, msg.BurnFromAddress) if err != nil { return nil, err } @@ -103,34 +120,38 @@ func (server msgServer) Burn(goCtx context.Context, msg *types.MsgBurn) (*types. return &types.MsgBurnResponse{}, nil } -// func (server msgServer) ForceTransfer(goCtx context.Context, msg *types.MsgForceTransfer) (*types.MsgForceTransferResponse, error) { -// ctx := sdk.UnwrapSDKContext(goCtx) +func (server msgServer) ForceTransfer(goCtx context.Context, msg *types.MsgForceTransfer) (*types.MsgForceTransferResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) -// authorityMetadata, err := server.Keeper.GetAuthorityMetadata(ctx, msg.Amount.GetDenom()) -// if err != nil { -// return nil, err -// } + if !types.IsCapabilityEnabled(server.Keeper.enabledCapabilities, types.EnableForceTransfer) { + return nil, types.ErrCapabilityNotEnabled + } -// if msg.Sender != authorityMetadata.GetAdmin() { -// return nil, types.ErrUnauthorized -// } + authorityMetadata, err := server.Keeper.GetAuthorityMetadata(ctx, msg.Amount.GetDenom()) + if err != nil { + return nil, err + } -// err = server.Keeper.forceTransfer(ctx, msg.Amount, msg.TransferFromAddress, msg.TransferToAddress) -// if err != nil { -// return nil, err -// } + if msg.Sender != authorityMetadata.GetAdmin() { + return nil, types.ErrUnauthorized + } -// ctx.EventManager().EmitEvents(sdk.Events{ -// sdk.NewEvent( -// types.TypeMsgForceTransfer, -// sdk.NewAttribute(types.AttributeTransferFromAddress, msg.TransferFromAddress), -// sdk.NewAttribute(types.AttributeTransferToAddress, msg.TransferToAddress), -// sdk.NewAttribute(types.AttributeAmount, msg.Amount.String()), -// ), -// }) + err = server.Keeper.forceTransfer(ctx, msg.Amount, msg.TransferFromAddress, msg.TransferToAddress) + if err != nil { + return nil, err + } -// return &types.MsgForceTransferResponse{}, nil -// } + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + types.TypeMsgForceTransfer, + sdk.NewAttribute(types.AttributeTransferFromAddress, msg.TransferFromAddress), + sdk.NewAttribute(types.AttributeTransferToAddress, msg.TransferToAddress), + sdk.NewAttribute(types.AttributeAmount, msg.Amount.String()), + ), + }) + + return &types.MsgForceTransferResponse{}, nil +} func (server msgServer) ChangeAdmin(goCtx context.Context, msg *types.MsgChangeAdmin) (*types.MsgChangeAdminResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) @@ -162,6 +183,10 @@ func (server msgServer) ChangeAdmin(goCtx context.Context, msg *types.MsgChangeA func (server msgServer) SetDenomMetadata(goCtx context.Context, msg *types.MsgSetDenomMetadata) (*types.MsgSetDenomMetadataResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) + if !types.IsCapabilityEnabled(server.Keeper.enabledCapabilities, types.EnableSetMetadata) { + return nil, types.ErrCapabilityNotEnabled + } + // Defense in depth validation of metadata err := msg.Metadata.Validate() if err != nil { @@ -189,3 +214,16 @@ func (server msgServer) SetDenomMetadata(goCtx context.Context, msg *types.MsgSe return &types.MsgSetDenomMetadataResponse{}, nil } + +func (server msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { + if server.authority != req.Authority { + return nil, errors.Wrapf(govtypes.ErrInvalidSigner, "invalid authority; expected %s, got %s", server.authority, req.Authority) + } + + ctx := sdk.UnwrapSDKContext(goCtx) + if err := server.SetParams(ctx, req.Params); err != nil { + return nil, err + } + + return &types.MsgUpdateParamsResponse{}, nil +} diff --git a/x/tokenfactory/keeper/msg_server_test.go b/x/tokenfactory/keeper/msg_server_test.go index 83f99a5..e341568 100644 --- a/x/tokenfactory/keeper/msg_server_test.go +++ b/x/tokenfactory/keeper/msg_server_test.go @@ -3,10 +3,10 @@ package keeper_test import ( "fmt" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" - sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) // TestMintDenomMsg tests TypeMsgMint message is emitted on a successful mint @@ -91,7 +91,7 @@ func (suite *KeeperTestSuite) TestBurnDenomMsg() { // TestCreateDenomMsg tests TypeMsgCreateDenom message is emitted on a successful denom creation func (suite *KeeperTestSuite) TestCreateDenomMsg() { - defaultDenomCreationFee := types.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(50000000)))} + defaultDenomCreationFee := types.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(50000000)))} for _, tc := range []struct { desc string denomCreationFee types.Params @@ -119,7 +119,9 @@ func (suite *KeeperTestSuite) TestCreateDenomMsg() { ctx := suite.Ctx.WithEventManager(sdk.NewEventManager()) suite.Require().Equal(0, len(ctx.EventManager().Events())) // Set denom creation fee in params - tokenFactoryKeeper.SetParams(suite.Ctx, tc.denomCreationFee) + if err := tokenFactoryKeeper.SetParams(suite.Ctx, tc.denomCreationFee); err != nil { + suite.Require().NoError(err) + } // Test create denom message suite.msgServer.CreateDenom(sdk.WrapSDKContext(ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), tc.subdenom)) //nolint:errcheck // Ensure current number and type of event is emitted @@ -236,6 +238,7 @@ func (suite *KeeperTestSuite) TestSetDenomMetaDataMsg() { }, } { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + tc := tc ctx := suite.Ctx.WithEventManager(sdk.NewEventManager()) suite.Require().Equal(0, len(ctx.EventManager().Events())) // Test set denom metadata message diff --git a/x/tokenfactory/keeper/params.go b/x/tokenfactory/keeper/params.go index 9c9caf4..5949338 100644 --- a/x/tokenfactory/keeper/params.go +++ b/x/tokenfactory/keeper/params.go @@ -1,18 +1,31 @@ package keeper import ( - "github.com/terpnetwork/terp-core/x/tokenfactory/types" - sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) // GetParams returns the total set params. -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramSpace.GetParamSet(ctx, ¶ms) - return params +func (k Keeper) GetParams(ctx sdk.Context) (p types.Params) { + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ParamsKey) + if bz == nil { + return p + } + k.cdc.MustUnmarshal(bz, &p) + return p } // SetParams sets the total set of params. -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramSpace.SetParamSet(ctx, ¶ms) +func (k Keeper) SetParams(ctx sdk.Context, p types.Params) error { + if err := p.Validate(); err != nil { + return err + } + + store := ctx.KVStore(k.storeKey) + bz := k.cdc.MustMarshal(&p) + store.Set(types.ParamsKey, bz) + + return nil } diff --git a/x/tokenfactory/migrations/v2/migrate.go b/x/tokenfactory/migrations/v2/migrate.go new file mode 100644 index 0000000..689486c --- /dev/null +++ b/x/tokenfactory/migrations/v2/migrate.go @@ -0,0 +1,39 @@ +package v2 + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/exported" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" +) + +const ModuleName = "tokenfactory" + +var ParamsKey = []byte{0x00} + +// Migrate migrates the x/tokenfactory module state from the consensus version 1 to +// version 2. Specifically, it takes the parameters that are currently stored +// and managed by the x/params modules and stores them directly into the x/tokenfactory +// module state. +func Migrate( + _ sdk.Context, + store sdk.KVStore, + _ exported.Subspace, + cdc codec.BinaryCodec, +) error { + // Migrates mainnet params -> the new keeper params storeKey (from x/params) + currParams := types.Params{ + DenomCreationFee: nil, + DenomCreationGasConsume: 2_000_000, + } + + if err := currParams.Validate(); err != nil { + return err + } + + bz := cdc.MustMarshal(&currParams) + store.Set(ParamsKey, bz) + + return nil +} diff --git a/x/tokenfactory/migrations/v2/migrate_test.go b/x/tokenfactory/migrations/v2/migrate_test.go new file mode 100644 index 0000000..0ed9fdd --- /dev/null +++ b/x/tokenfactory/migrations/v2/migrate_test.go @@ -0,0 +1,50 @@ +package v2_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/testutil" + sdk "github.com/cosmos/cosmos-sdk/types" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" + + "github.com/terpnetwork/terp-core/v2/x/tokenfactory" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/exported" + v2 "github.com/terpnetwork/terp-core/v2/x/tokenfactory/migrations/v2" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" +) + +type mockSubspace struct { + ps types.Params +} + +func newMockSubspace(ps types.Params) mockSubspace { + return mockSubspace{ps: ps} +} + +func (ms mockSubspace) GetParamSet(_ sdk.Context, ps exported.ParamSet) { + *ps.(*types.Params) = ms.ps +} + +func TestMigrate(t *testing.T) { + // x/param conversion + encCfg := moduletestutil.MakeTestEncodingConfig(tokenfactory.AppModuleBasic{}) + cdc := encCfg.Codec + + storeKey := sdk.NewKVStoreKey(v2.ModuleName) + tKey := sdk.NewTransientStoreKey("transient_test") + ctx := testutil.DefaultContext(storeKey, tKey) + store := ctx.KVStore(storeKey) + + legacySubspace := newMockSubspace(types.Params{ + DenomCreationFee: nil, + DenomCreationGasConsume: 2_000_000, + }) + require.NoError(t, v2.Migrate(ctx, store, legacySubspace, cdc)) + + var res types.Params + bz := store.Get(v2.ParamsKey) + require.NoError(t, cdc.Unmarshal(bz, &res)) + require.Equal(t, legacySubspace.ps, res) +} diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go index fdac9f1..9f93f1d 100644 --- a/x/tokenfactory/module.go +++ b/x/tokenfactory/module.go @@ -12,25 +12,25 @@ import ( "context" "encoding/json" "fmt" - "math/rand" + + "github.com/gorilla/mux" + "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/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - simulation "github.com/terpnetwork/terp-core/x/tokenfactory/simulation" - - "github.com/terpnetwork/terp-core/x/tokenfactory/client/cli" - "github.com/terpnetwork/terp-core/x/tokenfactory/keeper" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/client/cli" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/exported" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/keeper" + simulation "github.com/terpnetwork/terp-core/v2/x/tokenfactory/simulation" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) var ( @@ -38,6 +38,9 @@ var ( _ module.AppModuleBasic = AppModuleBasic{} ) +// ConsensusVersion defines the current x/tokenfactory module consensus version. +const ConsensusVersion = 2 + // ---------------------------------------------------------------------------- // AppModuleBasic // ---------------------------------------------------------------------------- @@ -55,7 +58,7 @@ func (AppModuleBasic) Name() string { } func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterCodec(cdc) + types.RegisterLegacyAminoCodec(cdc) } // RegisterInterfaces registers the module's interface types @@ -69,7 +72,7 @@ func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { } // ValidateGenesis performs genesis state validation for the x/tokenfactory module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingConfig, bz json.RawMessage) error { var genState types.GenesisState if err := cdc.UnmarshalJSON(bz, &genState); err != nil { return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) @@ -79,7 +82,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod } // RegisterRESTRoutes registers the capability module's REST service handlers. -func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { +func (AppModuleBasic) RegisterRESTRoutes(_ client.Context, _ *mux.Router) { } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. @@ -108,18 +111,24 @@ type AppModule struct { keeper keeper.Keeper accountKeeper types.AccountKeeper bankKeeper types.BankKeeper + + legacySubspace exported.Subspace } func NewAppModule( keeper keeper.Keeper, accountKeeper types.AccountKeeper, bankKeeper types.BankKeeper, + + // legacySubspace is used solely for migration of x/params managed parameters + legacySubspace exported.Subspace, ) AppModule { return AppModule{ AppModuleBasic: NewAppModuleBasic(), keeper: keeper, accountKeeper: accountKeeper, bankKeeper: bankKeeper, + legacySubspace: legacySubspace, } } @@ -136,6 +145,11 @@ func (AppModule) QuerierRoute() string { return types.QuerierRoute } func (am AppModule) RegisterServices(cfg module.Configurator) { types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), am.keeper) + + m := keeper.NewMigrator(am.keeper, am.legacySubspace) + if err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2); err != nil { + panic(fmt.Sprintf("failed to migrate x/%s from version 1 to 2: %v", types.ModuleName, err)) + } } // RegisterInvariants registers the x/tokenfactory module's invariants. @@ -160,7 +174,9 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw } // ConsensusVersion implements ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } +func (AppModule) ConsensusVersion() uint64 { + return ConsensusVersion +} // BeginBlock executes all ABCI BeginBlock logic respective to the tokenfactory module. func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} @@ -178,7 +194,7 @@ func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.Valid // // GenerateGenesisState creates a randomized GenState of the tokenfactory module. // func (am AppModule) SimulatorGenesisState(simState *module.SimulationState, s *simtypes.SimCtx) { // tfDefaultGen := types.DefaultGenesis() -// tfDefaultGen.Params.DenomCreationFee = sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(10000000))) +// tfDefaultGen.Params.DenomCreationFee = sdk.NewCoins(sdk.NewCoin(appparams.BondDenom, sdk.NewInt(10000000))) // tfDefaultGenJson := simState.Cdc.MustMarshalJSON(tfDefaultGen) // simState.GenState[types.ModuleName] = tfDefaultGenJson // } @@ -201,17 +217,12 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { } // GenerateGenesisState creates a randomized GenState of the bank module. -func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { +func (am AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalMsg { return nil } -// RandomizedParams creates randomized bank param changes for the simulator. -func (am AppModule) RandomizedParams(r *rand.Rand) []simtypes.LegacyParamChange { - return simulation.ParamChanges(r) -} - // RegisterStoreDecoder registers a decoder for supply module's types -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) { } // WeightedOperations returns the all the gov module operations with their respective weights. diff --git a/x/tokenfactory/simulation/genesis.go b/x/tokenfactory/simulation/genesis.go index f3e091b..3d2704e 100644 --- a/x/tokenfactory/simulation/genesis.go +++ b/x/tokenfactory/simulation/genesis.go @@ -6,12 +6,13 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + appparams "github.com/terpnetwork/terp-core/v2/app/params" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) func RandDenomCreationFeeParam(r *rand.Rand) sdk.Coins { amount := r.Int63n(10_000_000) - return sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(amount))) + return sdk.NewCoins(sdk.NewCoin(appparams.BondDenom, sdk.NewInt(amount))) } func RandomizedGenState(simstate *module.SimulationState) { diff --git a/x/tokenfactory/simulation/operations.go b/x/tokenfactory/simulation/operations.go index 46f9a16..4936439 100644 --- a/x/tokenfactory/simulation/operations.go +++ b/x/tokenfactory/simulation/operations.go @@ -10,8 +10,8 @@ import ( banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/simulation" - appparams "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + appparams "github.com/terpnetwork/terp-core/v2/app/params" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) // Simulation operation weights constants @@ -23,6 +23,7 @@ const ( OpWeightMsgBurn = "op_weight_msg_burn" OpWeightMsgChangeAdmin = "op_weight_msg_change_admin" OpWeightMsgSetDenomMetadata = "op_weight_msg_set_denom_metadata" + OpWeightMsgForceTransfer = "op_weight_msg_force_transfer" ) type TokenfactoryKeeper interface { @@ -50,6 +51,7 @@ func WeightedOperations( weightMsgBurn int weightMsgChangeAdmin int weightMsgSetDenomMetadata int + weightMsgForceTransfer int ) simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgCreateDenom, &weightMsgCreateDenom, nil, @@ -77,6 +79,11 @@ func WeightedOperations( weightMsgSetDenomMetadata = appparams.DefaultWeightMsgSetDenomMetadata }, ) + simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgForceTransfer, &weightMsgForceTransfer, nil, + func(_ *rand.Rand) { + weightMsgForceTransfer = appparams.DefaultWeightMsgForceTransfer + }, + ) return simulation.WeightedOperations{ simulation.NewWeightedOperation( @@ -357,7 +364,7 @@ func SimulateMsgCreateDenom(tfKeeper TokenfactoryKeeper, ak types.AccountKeeper, // Check if sims account enough create fee createFee := tfKeeper.GetParams(ctx).DenomCreationFee balances := bk.GetAllBalances(ctx, simAccount.Address) - _, hasNeg := balances.SafeSub(createFee...) + _, hasNeg := balances.SafeSub(createFee[0]) if hasNeg { return simtypes.NoOpMsg(types.ModuleName, types.MsgCreateDenom{}.Type(), "Creator not enough creation fee"), nil, nil } diff --git a/x/tokenfactory/simulation/params.go b/x/tokenfactory/simulation/params.go deleted file mode 100644 index 886bf06..0000000 --- a/x/tokenfactory/simulation/params.go +++ /dev/null @@ -1,24 +0,0 @@ -package simulation - -import ( - "fmt" - "math/rand" - - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/terpnetwork/terp-core/x/tokenfactory/types" -) - -func ParamChanges(r *rand.Rand) []simtypes.LegacyParamChange { - return []simtypes.LegacyParamChange{ - simulation.NewSimLegacyParamChange( - types.ModuleName, - string(types.KeyDenomCreationFee), - func(r *rand.Rand) string { - amount := RandDenomCreationFeeParam(r) - return fmt.Sprintf("[{\"denom\":\"%v\",\"amount\":\"%v\"}]", amount[0].Denom, amount[0].Amount) - }, - ), - } -} diff --git a/x/tokenfactory/testhelpers/suite.go b/x/tokenfactory/testhelpers/authz.go similarity index 100% rename from x/tokenfactory/testhelpers/suite.go rename to x/tokenfactory/testhelpers/authz.go index b509a52..dfa7865 100644 --- a/x/tokenfactory/testhelpers/suite.go +++ b/x/tokenfactory/testhelpers/authz.go @@ -5,13 +5,13 @@ import ( "testing" "time" - "github.com/cosmos/cosmos-sdk/x/authz" "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/authz" ) var ( diff --git a/x/tokenfactory/testhelpers/consts.go b/x/tokenfactory/testhelpers/consts.go deleted file mode 100644 index d7804a3..0000000 --- a/x/tokenfactory/testhelpers/consts.go +++ /dev/null @@ -1,8 +0,0 @@ -package testhelpers - -import sdk "github.com/cosmos/cosmos-sdk/types" - -var ( - SecondaryDenom = "uion" - SecondaryAmount = sdk.NewInt(100000000) -) diff --git a/x/tokenfactory/types/authority_metadata.pb.go b/x/tokenfactory/types/authorityMetadata.pb.go similarity index 80% rename from x/tokenfactory/types/authority_metadata.pb.go rename to x/tokenfactory/types/authorityMetadata.pb.go index 7e07827..92ad7ae 100644 --- a/x/tokenfactory/types/authority_metadata.pb.go +++ b/x/tokenfactory/types/authorityMetadata.pb.go @@ -1,25 +1,22 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/tokenfactory/v1beta1/authority_metadata.proto +// source: osmosis/tokenfactory/v1beta1/authorityMetadata.proto package types import ( fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - _ "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 - _ = fmt.Errorf - _ = math.Inf -) +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. @@ -31,7 +28,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // capabilities over a token factory denom. Right now there is only one Admin // permission, but is planned to be extended to the future. type DenomAuthorityMetadata struct { - // Can be empty for no admin, or a valid terp address + // Can be empty for no admin, or a valid osmosis address Admin string `protobuf:"bytes,1,opt,name=admin,proto3" json:"admin,omitempty" yaml:"admin"` } @@ -39,13 +36,11 @@ func (m *DenomAuthorityMetadata) Reset() { *m = DenomAuthorityMetadata{} func (m *DenomAuthorityMetadata) String() string { return proto.CompactTextString(m) } func (*DenomAuthorityMetadata) ProtoMessage() {} func (*DenomAuthorityMetadata) Descriptor() ([]byte, []int) { - return fileDescriptor_5e9c086b3b345014, []int{0} + return fileDescriptor_99435de88ae175f7, []int{0} } - func (m *DenomAuthorityMetadata) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *DenomAuthorityMetadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_DenomAuthorityMetadata.Marshal(b, m, deterministic) @@ -58,15 +53,12 @@ func (m *DenomAuthorityMetadata) XXX_Marshal(b []byte, deterministic bool) ([]by return b[:n], nil } } - func (m *DenomAuthorityMetadata) XXX_Merge(src proto.Message) { xxx_messageInfo_DenomAuthorityMetadata.Merge(m, src) } - func (m *DenomAuthorityMetadata) XXX_Size() int { return m.Size() } - func (m *DenomAuthorityMetadata) XXX_DiscardUnknown() { xxx_messageInfo_DenomAuthorityMetadata.DiscardUnknown(m) } @@ -85,27 +77,27 @@ func init() { } func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/authority_metadata.proto", fileDescriptor_5e9c086b3b345014) + proto.RegisterFile("osmosis/tokenfactory/v1beta1/authorityMetadata.proto", fileDescriptor_99435de88ae175f7) } -var fileDescriptor_5e9c086b3b345014 = []byte{ - // 253 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4b, 0xce, 0x2f, 0xce, - 0x2d, 0x4f, 0x2c, 0xce, 0xd5, 0x2f, 0xc9, 0xcf, 0x4e, 0xcd, 0x4b, 0x4b, 0x4c, 0x2e, 0xc9, 0x2f, - 0xaa, 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x2c, 0x2d, 0xc9, 0xc8, 0x2f, - 0xca, 0x2c, 0xa9, 0x8c, 0xcf, 0x4d, 0x2d, 0x49, 0x4c, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, - 0x2f, 0xc9, 0x17, 0x92, 0xc9, 0x2f, 0xce, 0xcd, 0x2f, 0xce, 0x2c, 0xd6, 0x43, 0xd6, 0xa6, 0x07, - 0xd5, 0x26, 0x25, 0x97, 0x0c, 0x96, 0xd6, 0x4f, 0x4a, 0x2c, 0x4e, 0x85, 0x9b, 0x95, 0x9c, 0x9f, - 0x99, 0x07, 0xd1, 0x2d, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x66, 0xea, 0x83, 0x58, 0x10, 0x51, - 0x25, 0x37, 0x2e, 0x31, 0x97, 0xd4, 0xbc, 0xfc, 0x5c, 0x47, 0x98, 0xa5, 0xbe, 0x50, 0x3b, 0x85, - 0xd4, 0xb8, 0x58, 0x13, 0x53, 0x72, 0x33, 0xf3, 0x24, 0x18, 0x15, 0x18, 0x35, 0x38, 0x9d, 0x04, - 0x3e, 0xdd, 0x93, 0xe7, 0xa9, 0x4c, 0xcc, 0xcd, 0xb1, 0x52, 0x02, 0x0b, 0x2b, 0x05, 0x41, 0xa4, - 0xad, 0x58, 0x5e, 0x2c, 0x90, 0x67, 0x74, 0xf2, 0x3f, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, - 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, - 0x39, 0x86, 0x28, 0xd3, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xfd, 0x92, - 0xd4, 0xa2, 0x82, 0xbc, 0xd4, 0x92, 0xf2, 0xfc, 0xa2, 0x6c, 0x30, 0x5b, 0x37, 0x39, 0xbf, 0x28, - 0x55, 0xbf, 0x02, 0x35, 0x1c, 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0xee, 0x33, 0x06, - 0x04, 0x00, 0x00, 0xff, 0xff, 0x3c, 0x03, 0xdd, 0x97, 0x2d, 0x01, 0x00, 0x00, +var fileDescriptor_99435de88ae175f7 = []byte{ + // 243 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0xc9, 0x2f, 0xce, 0xcd, + 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0xc9, 0xcf, 0x4e, 0xcd, 0x4b, 0x4b, 0x4c, 0x2e, 0xc9, 0x2f, 0xaa, + 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x2c, 0x2d, 0xc9, 0xc8, 0x2f, 0xca, + 0x2c, 0xa9, 0xf4, 0x4d, 0x2d, 0x49, 0x4c, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, + 0x17, 0x92, 0x81, 0xea, 0xd2, 0x43, 0xd6, 0xa5, 0x07, 0xd5, 0x25, 0x25, 0x92, 0x9e, 0x9f, 0x9e, + 0x0f, 0x56, 0xa8, 0x0f, 0x62, 0x41, 0xf4, 0x48, 0xc9, 0x25, 0x83, 0x35, 0xe9, 0x27, 0x25, 0x16, + 0xa7, 0xc2, 0x2d, 0x48, 0xce, 0xcf, 0xcc, 0x83, 0xc8, 0x2b, 0xb9, 0x71, 0x89, 0xb9, 0xa4, 0xe6, + 0xe5, 0xe7, 0x3a, 0xa2, 0xdb, 0x29, 0xa4, 0xc6, 0xc5, 0x9a, 0x98, 0x92, 0x9b, 0x99, 0x27, 0xc1, + 0xa8, 0xc0, 0xa8, 0xc1, 0xe9, 0x24, 0xf0, 0xe9, 0x9e, 0x3c, 0x4f, 0x65, 0x62, 0x6e, 0x8e, 0x95, + 0x12, 0x58, 0x58, 0x29, 0x08, 0x22, 0x6d, 0xc5, 0xf2, 0x62, 0x81, 0x3c, 0xa3, 0x93, 0xff, 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, 0x99, 0xa6, 0x67, 0x96, 0x64, 0x94, 0x26, + 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x97, 0xa4, 0x16, 0x15, 0xe4, 0xa5, 0x96, 0x94, 0xe7, 0x17, 0x65, + 0x83, 0xd9, 0xba, 0xc9, 0xf9, 0x45, 0xa9, 0xfa, 0x15, 0xa8, 0xc1, 0x50, 0x52, 0x59, 0x90, 0x5a, + 0x9c, 0xc4, 0x06, 0x76, 0x9f, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xf0, 0x70, 0xbc, 0xef, 0x2b, + 0x01, 0x00, 0x00, } func (this *DenomAuthorityMetadata) Equal(that interface{}) bool { @@ -132,7 +124,6 @@ func (this *DenomAuthorityMetadata) Equal(that interface{}) bool { } return true } - func (m *DenomAuthorityMetadata) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -174,7 +165,6 @@ func encodeVarintAuthorityMetadata(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } - func (m *DenomAuthorityMetadata) Size() (n int) { if m == nil { return 0 @@ -191,11 +181,9 @@ func (m *DenomAuthorityMetadata) Size() (n int) { func sovAuthorityMetadata(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } - func sozAuthorityMetadata(x uint64) (n int) { return sovAuthorityMetadata(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } - func (m *DenomAuthorityMetadata) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -278,7 +266,6 @@ func (m *DenomAuthorityMetadata) Unmarshal(dAtA []byte) error { } return nil } - func skipAuthorityMetadata(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/tokenfactory/types/authzcodec/codec.go b/x/tokenfactory/types/authzcodec/codec.go deleted file mode 100644 index 366e337..0000000 --- a/x/tokenfactory/types/authzcodec/codec.go +++ /dev/null @@ -1,24 +0,0 @@ -package authzcodec - -// Note: this file is a copy from authz/codec in 0.46 so we can be compatible with 0.45 - -import ( - "github.com/cosmos/cosmos-sdk/codec" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -var ( - Amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(Amino) -) - -func init() { - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - sdk.RegisterLegacyAminoCodec(Amino) - cryptocodec.RegisterCrypto(Amino) - codec.RegisterEvidences(Amino) - - Amino.Seal() -} diff --git a/x/tokenfactory/types/capabilities.go b/x/tokenfactory/types/capabilities.go new file mode 100644 index 0000000..bda91c9 --- /dev/null +++ b/x/tokenfactory/types/capabilities.go @@ -0,0 +1,21 @@ +package types + +const ( + EnableSetMetadata = "enable_metadata" + EnableForceTransfer = "enable_force_transfer" + EnableBurnFrom = "enable_burn_from" +) + +func IsCapabilityEnabled(enabledCapabilities []string, capability string) bool { + if len(enabledCapabilities) == 0 { + return true + } + + for _, v := range enabledCapabilities { + if v == capability { + return true + } + } + + return false +} diff --git a/x/tokenfactory/types/codec.go b/x/tokenfactory/types/codec.go index b086a51..d7fa63b 100644 --- a/x/tokenfactory/types/codec.go +++ b/x/tokenfactory/types/codec.go @@ -2,45 +2,70 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" +) - // this line is used by starport scaffolding # 1 - "github.com/cosmos/cosmos-sdk/types/msgservice" +var ( + amino = codec.NewLegacyAmino() + + // ModuleCdc references the global erc20 module codec. Note, the codec should + // ONLY be used in certain instances of tests and for JSON encoding. + // + // The actual codec used for serialization should be provided to modules/erc20 and + // defined at the application level. + ModuleCdc = codec.NewProtoCodec(codectypes.NewInterfaceRegistry()) + + // AminoCdc is a amino codec created to support amino JSON compatible msgs. + AminoCdc = codec.NewAminoCodec(amino) ) -func RegisterCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgCreateDenom{}, "osmosis/tokenfactory/create-denom", nil) - cdc.RegisterConcrete(&MsgMint{}, "osmosis/tokenfactory/mint", nil) - cdc.RegisterConcrete(&MsgBurn{}, "osmosis/tokenfactory/burn", nil) - // cdc.RegisterConcrete(&MsgForceTransfer{}, "osmosis/tokenfactory/force-transfer", nil) - cdc.RegisterConcrete(&MsgChangeAdmin{}, "osmosis/tokenfactory/change-admin", nil) +const ( + // Amino names + createTFDenom = "osmosis/tokenfactory/create-denom" + mintTFDenom = "osmosis/tokenfactory/mint" + burnTFDenom = "osmosis/tokenfactory/burn" + forceTransferTFDenom = "osmosis/tokenfactory/force-transfer" + changeAdminTFDenom = "osmosis/tokenfactory/change-admin" + updateTFparams = "osmosis/tokenfactory/msg-update-params" +) + +// NOTE: This is required for the GetSignBytes function +func init() { + RegisterLegacyAminoCodec(amino) + + sdk.RegisterLegacyAminoCodec(amino) + // cryptocodec.RegisterCrypto(amino) + // codec.RegisterEvidences(amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec + // so that this can later be used to properly serialize MsgGrant and MsgExec + // instances. + RegisterLegacyAminoCodec(authzcodec.Amino) + + amino.Seal() } -func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { +func RegisterInterfaces(registry codectypes.InterfaceRegistry) { registry.RegisterImplementations( (*sdk.Msg)(nil), &MsgCreateDenom{}, &MsgMint{}, &MsgBurn{}, - // &MsgForceTransfer{}, + &MsgForceTransfer{}, &MsgChangeAdmin{}, + &MsgUpdateParams{}, ) msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } -var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) -) - -func init() { - RegisterCodec(amino) - // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be - // used to properly serialize MsgGrant and MsgExec instances - sdk.RegisterLegacyAminoCodec(amino) - RegisterCodec(authzcodec.Amino) - - amino.Seal() +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(&MsgCreateDenom{}, createTFDenom, nil) + cdc.RegisterConcrete(&MsgMint{}, mintTFDenom, nil) + cdc.RegisterConcrete(&MsgBurn{}, burnTFDenom, nil) + cdc.RegisterConcrete(&MsgForceTransfer{}, forceTransferTFDenom, nil) + cdc.RegisterConcrete(&MsgChangeAdmin{}, changeAdminTFDenom, nil) + cdc.RegisterConcrete(&MsgUpdateParams{}, updateTFparams, nil) } diff --git a/x/tokenfactory/types/codec_test.go b/x/tokenfactory/types/codec_test.go new file mode 100644 index 0000000..7b82637 --- /dev/null +++ b/x/tokenfactory/types/codec_test.go @@ -0,0 +1,36 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/suite" + + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type CodecTestSuite struct { + suite.Suite +} + +func TestCodecSuite(t *testing.T) { + suite.Run(t, new(CodecTestSuite)) +} + +func (suite *CodecTestSuite) TestRegisterInterfaces() { + registry := codectypes.NewInterfaceRegistry() + registry.RegisterInterface(sdk.MsgInterfaceProtoName, (*sdk.Msg)(nil)) + RegisterInterfaces(registry) + + impls := registry.ListImplementations(sdk.MsgInterfaceProtoName) + suite.Require().Equal(7, len(impls)) + suite.Require().ElementsMatch([]string{ + "/osmosis.tokenfactory.v1beta1.MsgCreateDenom", + "/osmosis.tokenfactory.v1beta1.MsgMint", + "/osmosis.tokenfactory.v1beta1.MsgBurn", + "/osmosis.tokenfactory.v1beta1.MsgChangeAdmin", + "/osmosis.tokenfactory.v1beta1.MsgSetDenomMetadata", + "/osmosis.tokenfactory.v1beta1.MsgForceTransfer", + "/osmosis.tokenfactory.v1beta1.MsgUpdateParams", + }, impls) +} diff --git a/x/tokenfactory/types/denoms.go b/x/tokenfactory/types/denoms.go index 6583998..a6fc4e0 100644 --- a/x/tokenfactory/types/denoms.go +++ b/x/tokenfactory/types/denoms.go @@ -4,6 +4,7 @@ import ( "strings" errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/tokenfactory/types/denoms_test.go b/x/tokenfactory/types/denoms_test.go index 12f4637..36f013e 100644 --- a/x/tokenfactory/types/denoms_test.go +++ b/x/tokenfactory/types/denoms_test.go @@ -5,11 +5,11 @@ import ( "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) func TestDeconstructDenom(t *testing.T) { - // Note: this seems to be used in terp to add some more checks (only 20 or 32 byte addresses), + // Note: this seems to be used in osmosis to add some more checks (only 20 or 32 byte addresses), // which is good, but not required for these tests as they make code less reuable // appparams.SetAddressPrefixes() diff --git a/x/tokenfactory/types/errors.go b/x/tokenfactory/types/errors.go index 7742014..5a3c587 100644 --- a/x/tokenfactory/types/errors.go +++ b/x/tokenfactory/types/errors.go @@ -19,4 +19,5 @@ var ( ErrSubdenomTooLong = errorsmod.Register(ModuleName, 8, fmt.Sprintf("subdenom too long, max length is %d bytes", MaxSubdenomLength)) ErrCreatorTooLong = errorsmod.Register(ModuleName, 9, fmt.Sprintf("creator too long, max length is %d bytes", MaxCreatorLength)) ErrDenomDoesNotExist = errorsmod.Register(ModuleName, 10, "denom does not exist") + ErrCapabilityNotEnabled = errorsmod.Register(ModuleName, 11, "this capability is not enabled on chain") ) diff --git a/x/tokenfactory/types/events.go b/x/tokenfactory/types/events.go index 48038e0..602e06f 100644 --- a/x/tokenfactory/types/events.go +++ b/x/tokenfactory/types/events.go @@ -2,7 +2,7 @@ package types // event types // -//nolint:gosec // these are not hard-coded credentials +//nolint:gosec const ( AttributeAmount = "amount" AttributeCreator = "creator" diff --git a/x/tokenfactory/types/expected_keepers.go b/x/tokenfactory/types/expected_keepers.go index 15f377e..ff38423 100644 --- a/x/tokenfactory/types/expected_keepers.go +++ b/x/tokenfactory/types/expected_keepers.go @@ -12,6 +12,7 @@ type BankKeeper interface { SetDenomMetaData(ctx sdk.Context, denomMetaData banktypes.Metadata) HasSupply(ctx sdk.Context, denom string) bool + IterateTotalSupply(ctx sdk.Context, cb func(sdk.Coin) bool) SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error @@ -23,6 +24,8 @@ type BankKeeper interface { GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin + + BlockedAddr(addr sdk.AccAddress) bool } type AccountKeeper interface { diff --git a/x/tokenfactory/types/genesis.go b/x/tokenfactory/types/genesis.go index aef9370..408dc5f 100644 --- a/x/tokenfactory/types/genesis.go +++ b/x/tokenfactory/types/genesis.go @@ -2,6 +2,7 @@ package types import ( errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" ) diff --git a/x/tokenfactory/types/genesis.pb.go b/x/tokenfactory/types/genesis.pb.go index f2c5849..fe6b208 100644 --- a/x/tokenfactory/types/genesis.pb.go +++ b/x/tokenfactory/types/genesis.pb.go @@ -1,24 +1,21 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/tokenfactory/v1beta1/genesis.proto +// source: osmosis/tokenfactory/v1beta1/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" - - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" ) // Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = math.Inf -) +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. @@ -37,13 +34,11 @@ 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_b333539769138b3e, []int{0} + return fileDescriptor_5749c3f71850298b, []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) @@ -56,15 +51,12 @@ func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) 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) } @@ -97,13 +89,11 @@ func (m *GenesisDenom) Reset() { *m = GenesisDenom{} } func (m *GenesisDenom) String() string { return proto.CompactTextString(m) } func (*GenesisDenom) ProtoMessage() {} func (*GenesisDenom) Descriptor() ([]byte, []int) { - return fileDescriptor_b333539769138b3e, []int{1} + return fileDescriptor_5749c3f71850298b, []int{1} } - func (m *GenesisDenom) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *GenesisDenom) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_GenesisDenom.Marshal(b, m, deterministic) @@ -116,15 +106,12 @@ func (m *GenesisDenom) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) return b[:n], nil } } - func (m *GenesisDenom) XXX_Merge(src proto.Message) { xxx_messageInfo_GenesisDenom.Merge(m, src) } - func (m *GenesisDenom) XXX_Size() int { return m.Size() } - func (m *GenesisDenom) XXX_DiscardUnknown() { xxx_messageInfo_GenesisDenom.DiscardUnknown(m) } @@ -151,35 +138,35 @@ func init() { } func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/genesis.proto", fileDescriptor_b333539769138b3e) -} - -var fileDescriptor_b333539769138b3e = []byte{ - // 374 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x4e, 0xce, 0x2f, 0xce, - 0x2d, 0x4f, 0x2c, 0xce, 0xd5, 0x2f, 0xc9, 0xcf, 0x4e, 0xcd, 0x4b, 0x4b, 0x4c, 0x2e, 0xc9, 0x2f, - 0xaa, 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, - 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0xc9, 0x2f, 0xce, 0xcd, 0x07, 0x71, 0x91, - 0xd5, 0xea, 0x41, 0xd5, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x15, 0xea, 0x83, 0x58, 0x10, - 0x3d, 0x52, 0x66, 0xf8, 0x2d, 0x48, 0x2c, 0x2d, 0xc9, 0xc8, 0x2f, 0xca, 0x2c, 0xa9, 0x8c, 0xcf, - 0x4d, 0x2d, 0x49, 0x4c, 0x49, 0x2c, 0x49, 0x84, 0xea, 0xd3, 0xc2, 0xaf, 0xaf, 0x20, 0xb1, 0x28, - 0x31, 0x17, 0xea, 0x2e, 0xa5, 0x23, 0x8c, 0x5c, 0x3c, 0xee, 0x10, 0x97, 0x06, 0x97, 0x24, 0x96, - 0xa4, 0x0a, 0x39, 0x71, 0xb1, 0x41, 0x14, 0x48, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x1b, 0xa9, 0xe8, - 0xe1, 0x73, 0xb9, 0x5e, 0x00, 0x58, 0xad, 0x13, 0xcb, 0x89, 0x7b, 0xf2, 0x0c, 0x41, 0x50, 0x9d, - 0x42, 0x05, 0x5c, 0x7c, 0x50, 0x75, 0xf1, 0x29, 0xa9, 0x79, 0xf9, 0xb9, 0xc5, 0x12, 0x4c, 0x0a, - 0xcc, 0x1a, 0xdc, 0x46, 0x5a, 0xf8, 0xcd, 0x82, 0xba, 0xc3, 0x05, 0xa4, 0xc5, 0x49, 0x16, 0x64, - 0xe2, 0xa7, 0x7b, 0xf2, 0xa2, 0x95, 0x89, 0xb9, 0x39, 0x56, 0x4a, 0xa8, 0xe6, 0x29, 0x05, 0xf1, - 0x42, 0x05, 0x5c, 0x20, 0xfc, 0xa3, 0x08, 0x6f, 0x80, 0x45, 0x84, 0xd4, 0xb8, 0x58, 0xc1, 0x4a, - 0xc1, 0xbe, 0xe0, 0x74, 0x12, 0xf8, 0x74, 0x4f, 0x9e, 0x07, 0x62, 0x12, 0x58, 0x58, 0x29, 0x08, - 0x22, 0x2d, 0xd4, 0xc6, 0xc8, 0x25, 0x84, 0x19, 0x90, 0x12, 0x4c, 0x60, 0xbf, 0x9b, 0xe0, 0x77, - 0x2f, 0xd8, 0x26, 0x47, 0x98, 0x66, 0x5f, 0xa8, 0x5e, 0x27, 0x45, 0xa8, 0xcb, 0x25, 0x21, 0xf6, - 0x61, 0x9a, 0xae, 0x14, 0x24, 0x98, 0x88, 0xae, 0xcb, 0x8a, 0xe5, 0xc5, 0x02, 0x79, 0x46, 0x27, - 0xff, 0x13, 0x8f, 0xe4, 0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, - 0x39, 0x86, 0x0b, 0x8f, 0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x32, 0x4d, 0xcf, 0x2c, 0xc9, - 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x2f, 0x49, 0x2d, 0x2a, 0xc8, 0x4b, 0x2d, 0x29, 0xcf, - 0x2f, 0xca, 0x06, 0xb3, 0x75, 0x93, 0xf3, 0x8b, 0x52, 0xf5, 0x2b, 0x50, 0xa3, 0xbb, 0xa4, 0xb2, - 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0xcd, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe4, 0x72, - 0x8b, 0x18, 0xad, 0x02, 0x00, 0x00, + proto.RegisterFile("osmosis/tokenfactory/v1beta1/genesis.proto", fileDescriptor_5749c3f71850298b) +} + +var fileDescriptor_5749c3f71850298b = []byte{ + // 370 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0xca, 0x2f, 0xce, 0xcd, + 0x2f, 0xce, 0x2c, 0xd6, 0x2f, 0xc9, 0xcf, 0x4e, 0xcd, 0x4b, 0x4b, 0x4c, 0x2e, 0xc9, 0x2f, 0xaa, + 0xd4, 0x2f, 0x33, 0x4c, 0x4a, 0x2d, 0x49, 0x34, 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, + 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x81, 0xaa, 0xd5, 0x43, 0x56, 0xab, 0x07, 0x55, + 0x2b, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xa8, 0x0f, 0x62, 0x41, 0xf4, 0x48, 0x99, 0xe0, + 0x35, 0x3f, 0xb1, 0xb4, 0x24, 0x23, 0xbf, 0x28, 0xb3, 0xa4, 0xd2, 0x37, 0xb5, 0x24, 0x31, 0x25, + 0xb1, 0x24, 0x11, 0xaa, 0x4b, 0x13, 0xaf, 0xae, 0x82, 0xc4, 0xa2, 0xc4, 0x5c, 0xa8, 0xa3, 0x94, + 0x8e, 0x30, 0x72, 0xf1, 0xb8, 0x43, 0x9c, 0x19, 0x5c, 0x92, 0x58, 0x92, 0x2a, 0xe4, 0xc4, 0xc5, + 0x06, 0x51, 0x20, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0xa4, 0xa2, 0x87, 0xcf, 0xd9, 0x7a, 0x01, + 0x60, 0xb5, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x41, 0x75, 0x0a, 0x15, 0x70, 0xf1, 0x41, + 0xd5, 0xc5, 0xa7, 0xa4, 0xe6, 0xe5, 0xe7, 0x16, 0x4b, 0x30, 0x29, 0x30, 0x6b, 0x70, 0x1b, 0x69, + 0xe1, 0x37, 0x0b, 0xea, 0x0e, 0x17, 0x90, 0x16, 0x27, 0x59, 0x90, 0x89, 0x9f, 0xee, 0xc9, 0x8b, + 0x56, 0x26, 0xe6, 0xe6, 0x58, 0x29, 0xa1, 0x9a, 0xa7, 0x14, 0xc4, 0x0b, 0x15, 0x70, 0x81, 0xf0, + 0x8f, 0x22, 0xbc, 0x01, 0x16, 0x11, 0x52, 0xe3, 0x62, 0x05, 0x2b, 0x05, 0xfb, 0x82, 0xd3, 0x49, + 0xe0, 0xd3, 0x3d, 0x79, 0x1e, 0x88, 0x49, 0x60, 0x61, 0xa5, 0x20, 0x88, 0xb4, 0x50, 0x1b, 0x23, + 0x97, 0x10, 0x3c, 0x18, 0xe3, 0x73, 0xa1, 0xe1, 0x28, 0xc1, 0x04, 0xf6, 0xbb, 0x09, 0x7e, 0xf7, + 0x82, 0x6d, 0x72, 0x44, 0x8f, 0x03, 0x27, 0x45, 0xa8, 0xcb, 0x25, 0x21, 0xf6, 0x61, 0x9a, 0xae, + 0x14, 0x24, 0x88, 0x11, 0x73, 0x56, 0x2c, 0x2f, 0x16, 0xc8, 0x33, 0x3a, 0xf9, 0x9f, 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, 0x69, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, + 0x72, 0x7e, 0xae, 0x7e, 0x49, 0x6a, 0x51, 0x41, 0x5e, 0x6a, 0x49, 0x79, 0x7e, 0x51, 0x36, 0x98, + 0xad, 0x9b, 0x9c, 0x5f, 0x94, 0xaa, 0x5f, 0x81, 0x1a, 0xdd, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, + 0x6c, 0xe0, 0x68, 0x36, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x20, 0x30, 0xa0, 0x86, 0xa9, 0x02, + 0x00, 0x00, } func (this *GenesisDenom) Equal(that interface{}) bool { @@ -209,7 +196,6 @@ func (this *GenesisDenom) Equal(that interface{}) bool { } return true } - func (m *GenesisState) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -308,7 +294,6 @@ func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } - func (m *GenesisState) Size() (n int) { if m == nil { return 0 @@ -344,11 +329,9 @@ func (m *GenesisDenom) Size() (n int) { 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 @@ -466,7 +449,6 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { } return nil } - func (m *GenesisDenom) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -582,7 +564,6 @@ func (m *GenesisDenom) Unmarshal(dAtA []byte) error { } return nil } - func skipGenesis(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/tokenfactory/types/genesis_test.go b/x/tokenfactory/types/genesis_test.go index c93adb4..a3134d7 100644 --- a/x/tokenfactory/types/genesis_test.go +++ b/x/tokenfactory/types/genesis_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) func TestGenesisState_Validate(t *testing.T) { diff --git a/x/tokenfactory/types/keys.go b/x/tokenfactory/types/keys.go index fac4a6e..bb52b5d 100644 --- a/x/tokenfactory/types/keys.go +++ b/x/tokenfactory/types/keys.go @@ -4,6 +4,8 @@ import ( "strings" ) +var ParamsKey = []byte{0x00} + const ( // ModuleName defines the module name ModuleName = "tokenfactory" diff --git a/x/tokenfactory/types/msgs.go b/x/tokenfactory/types/msgs.go index e9fb237..f6f06e5 100644 --- a/x/tokenfactory/types/msgs.go +++ b/x/tokenfactory/types/msgs.go @@ -2,6 +2,7 @@ package types import ( errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -62,6 +63,14 @@ func NewMsgMint(sender string, amount sdk.Coin) *MsgMint { } } +func NewMsgMintTo(sender string, amount sdk.Coin, mintToAddress string) *MsgMint { + return &MsgMint{ + Sender: sender, + Amount: amount, + MintToAddress: mintToAddress, + } +} + func (m MsgMint) Route() string { return RouterKey } func (m MsgMint) Type() string { return TypeMsgMint } func (m MsgMint) ValidateBasic() error { @@ -70,6 +79,13 @@ func (m MsgMint) ValidateBasic() error { return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) } + if m.MintToAddress != "" { + _, err = sdk.AccAddressFromBech32(m.MintToAddress) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid mint to address (%s)", err) + } + } + if !m.Amount.IsValid() || m.Amount.Amount.Equal(sdk.ZeroInt()) { return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, m.Amount.String()) } @@ -96,6 +112,15 @@ func NewMsgBurn(sender string, amount sdk.Coin) *MsgBurn { } } +// NewMsgBurn creates a message to burn tokens +func NewMsgBurnFrom(sender string, amount sdk.Coin, burnFromAddress string) *MsgBurn { + return &MsgBurn{ + Sender: sender, + Amount: amount, + BurnFromAddress: burnFromAddress, + } +} + func (m MsgBurn) Route() string { return RouterKey } func (m MsgBurn) Type() string { return TypeMsgBurn } func (m MsgBurn) ValidateBasic() error { @@ -108,6 +133,13 @@ func (m MsgBurn) ValidateBasic() error { return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, m.Amount.String()) } + if m.BurnFromAddress != "" { + _, err = sdk.AccAddressFromBech32(m.BurnFromAddress) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid burn from address (%s)", err) + } + } + return nil } @@ -120,50 +152,50 @@ func (m MsgBurn) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{sender} } -// var _ sdk.Msg = &MsgForceTransfer{} - -// // NewMsgForceTransfer creates a transfer funds from one account to another -// func NewMsgForceTransfer(sender string, amount sdk.Coin, fromAddr, toAddr string) *MsgForceTransfer { -// return &MsgForceTransfer{ -// Sender: sender, -// Amount: amount, -// TransferFromAddress: fromAddr, -// TransferToAddress: toAddr, -// } -// } - -// func (m MsgForceTransfer) Route() string { return RouterKey } -// func (m MsgForceTransfer) Type() string { return TypeMsgForceTransfer } -// func (m MsgForceTransfer) ValidateBasic() error { -// _, err := sdk.AccAddressFromBech32(m.Sender) -// if err != nil { -// return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) -// } - -// _, err = sdk.AccAddressFromBech32(m.TransferFromAddress) -// if err != nil { -// return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid address (%s)", err) -// } -// _, err = sdk.AccAddressFromBech32(m.TransferToAddress) -// if err != nil { -// return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid address (%s)", err) -// } - -// if !m.Amount.IsValid() { -// return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, m.Amount.String()) -// } - -// return nil -// } - -// func (m MsgForceTransfer) GetSignBytes() []byte { -// return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) -// } - -// func (m MsgForceTransfer) GetSigners() []sdk.AccAddress { -// sender, _ := sdk.AccAddressFromBech32(m.Sender) -// return []sdk.AccAddress{sender} -// } +var _ sdk.Msg = &MsgForceTransfer{} + +// NewMsgForceTransfer creates a transfer funds from one account to another +func NewMsgForceTransfer(sender string, amount sdk.Coin, fromAddr, toAddr string) *MsgForceTransfer { + return &MsgForceTransfer{ + Sender: sender, + Amount: amount, + TransferFromAddress: fromAddr, + TransferToAddress: toAddr, + } +} + +func (m MsgForceTransfer) Route() string { return RouterKey } +func (m MsgForceTransfer) Type() string { return TypeMsgForceTransfer } +func (m MsgForceTransfer) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Sender) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) + } + + _, err = sdk.AccAddressFromBech32(m.TransferFromAddress) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid from address (%s)", err) + } + _, err = sdk.AccAddressFromBech32(m.TransferToAddress) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid to address (%s)", err) + } + + if !m.Amount.IsValid() { + return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, m.Amount.String()) + } + + return nil +} + +func (m MsgForceTransfer) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +func (m MsgForceTransfer) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) + return []sdk.AccAddress{sender} +} var _ sdk.Msg = &MsgChangeAdmin{} @@ -245,3 +277,25 @@ func (m MsgSetDenomMetadata) GetSigners() []sdk.AccAddress { sender, _ := sdk.AccAddressFromBech32(m.Sender) return []sdk.AccAddress{sender} } + +var _ sdk.Msg = &MsgUpdateParams{} + +// GetSignBytes implements the LegacyMsg interface. +func (m MsgUpdateParams) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +// GetSigners returns the expected signers for a MsgUpdateParams message. +func (m *MsgUpdateParams) GetSigners() []sdk.AccAddress { + addr, _ := sdk.AccAddressFromBech32(m.Authority) + return []sdk.AccAddress{addr} +} + +// ValidateBasic does a sanity check on the provided data. +func (m *MsgUpdateParams) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(m.Authority); err != nil { + return errorsmod.Wrap(err, "invalid authority address") + } + + return m.Params.Validate() +} diff --git a/x/tokenfactory/types/msgs_test.go b/x/tokenfactory/types/msgs_test.go index 2b71ce1..8c31600 100644 --- a/x/tokenfactory/types/msgs_test.go +++ b/x/tokenfactory/types/msgs_test.go @@ -4,17 +4,18 @@ import ( fmt "fmt" "testing" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/x/tokenfactory/testhelpers" - "github.com/terpnetwork/terp-core/x/tokenfactory/types" - "github.com/cometbft/cometbft/crypto/ed25519" + + sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/testhelpers" + "github.com/terpnetwork/terp-core/v2/x/tokenfactory/types" ) -// // Test authz serialize and de-serializes for tokenfactory msg. +// Test authz serialize and de-serializes for tokenfactory msg. func TestAuthzMsg(t *testing.T) { t.Skip("TODO: figure out how to register authz interfaces for tests") pk1 := ed25519.GenPrivKey().PubKey() diff --git a/x/tokenfactory/types/params.go b/x/tokenfactory/types/params.go index a483078..5942c07 100644 --- a/x/tokenfactory/types/params.go +++ b/x/tokenfactory/types/params.go @@ -4,48 +4,27 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -// Parameter store keys. -var ( - KeyDenomCreationFee = []byte("DenomCreationFee") -) - -// ParamTable for gamm module. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - func NewParams(denomCreationFee sdk.Coins) Params { return Params{ DenomCreationFee: denomCreationFee, } } -// default gamm module parameters. +// default tokenfactory module parameters. func DefaultParams() Params { return Params{ - // this was from osmosis - // DenomCreationFee: sdk.NewCoins(sdk.NewInt64Coin(appparams.BaseCoinUnit, 10_000_000)), // 10 OSMO - DenomCreationFee: sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 10_000_000)), // 10 OSMO + DenomCreationFee: sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 10_000_000)), + DenomCreationGasConsume: 2_000_000, } } // validate params. func (p Params) Validate() error { - if err := validateDenomCreationFee(p.DenomCreationFee); err != nil { - return err - } - - return nil -} + err := validateDenomCreationFee(p.DenomCreationFee) -// Implements params.ParamSet. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyDenomCreationFee, &p.DenomCreationFee, validateDenomCreationFee), - } + return err } func validateDenomCreationFee(i interface{}) error { @@ -60,3 +39,12 @@ func validateDenomCreationFee(i interface{}) error { return nil } + +func validateDenomCreationFeeGasConsume(i interface{}) error { + _, ok := i.(uint64) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + return nil +} diff --git a/x/tokenfactory/types/params.pb.go b/x/tokenfactory/types/params.pb.go index 73973e6..c557cc3 100644 --- a/x/tokenfactory/types/params.pb.go +++ b/x/tokenfactory/types/params.pb.go @@ -1,27 +1,24 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/tokenfactory/v1beta1/params.proto +// source: osmosis/tokenfactory/v1beta1/params.proto package types import ( fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - _ "github.com/cosmos/cosmos-proto" github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" types "github.com/cosmos/cosmos-sdk/types" _ "github.com/cosmos/gogoproto/gogoproto" proto "github.com/cosmos/gogoproto/proto" + io "io" + math "math" + math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = math.Inf -) +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. @@ -32,19 +29,21 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Params defines the parameters for the tokenfactory module. type Params struct { DenomCreationFee github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=denom_creation_fee,json=denomCreationFee,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"denom_creation_fee" yaml:"denom_creation_fee"` + // if denom_creation_fee is an empty array, then this field is used to add more gas consumption + // to the base cost. + // https://github.com/CosmWasm/token-factory/issues/11 + DenomCreationGasConsume uint64 `protobuf:"varint,2,opt,name=denom_creation_gas_consume,json=denomCreationGasConsume,proto3" json:"denom_creation_gas_consume,omitempty" yaml:"denom_creation_gas_consume"` } func (m *Params) Reset() { *m = Params{} } func (m *Params) String() string { return proto.CompactTextString(m) } func (*Params) ProtoMessage() {} func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_c2e403a2e90cdef7, []int{0} + return fileDescriptor_cc8299d306f3ff47, []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) @@ -57,15 +56,12 @@ func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 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) } @@ -79,36 +75,46 @@ func (m *Params) GetDenomCreationFee() github_com_cosmos_cosmos_sdk_types.Coins return nil } +func (m *Params) GetDenomCreationGasConsume() uint64 { + if m != nil { + return m.DenomCreationGasConsume + } + return 0 +} + func init() { proto.RegisterType((*Params)(nil), "osmosis.tokenfactory.v1beta1.Params") } func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/params.proto", fileDescriptor_c2e403a2e90cdef7) + proto.RegisterFile("osmosis/tokenfactory/v1beta1/params.proto", fileDescriptor_cc8299d306f3ff47) } -var fileDescriptor_c2e403a2e90cdef7 = []byte{ - // 314 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x90, 0xb1, 0x4a, 0x03, 0x41, - 0x10, 0x86, 0xef, 0x10, 0x52, 0xc4, 0x46, 0x82, 0x85, 0x09, 0xb2, 0x91, 0x54, 0x41, 0xc8, 0x2d, - 0x51, 0xb4, 0xb0, 0x4c, 0xc0, 0x4e, 0x14, 0x4b, 0x9b, 0x63, 0x6e, 0x33, 0x49, 0x8e, 0xb8, 0x37, - 0xc7, 0xee, 0xc4, 0x78, 0x6f, 0x61, 0x65, 0x6f, 0xeb, 0x93, 0xa4, 0x4c, 0x69, 0x15, 0x25, 0x79, - 0x03, 0x9f, 0x40, 0xb2, 0xb7, 0x4a, 0x44, 0xb0, 0xda, 0x19, 0xe6, 0xff, 0xbf, 0x99, 0x7f, 0xab, - 0xc7, 0x8a, 0xac, 0x9e, 0x81, 0xd5, 0x92, 0x69, 0x82, 0xd9, 0x10, 0x14, 0x93, 0x29, 0xe4, 0x43, - 0x37, 0x41, 0x86, 0xae, 0xcc, 0xc1, 0x80, 0xb6, 0x51, 0x6e, 0x88, 0xa9, 0x76, 0x48, 0x56, 0x93, - 0x4d, 0x6d, 0xb4, 0x2d, 0x8d, 0xbc, 0xb4, 0xb1, 0x3f, 0xa2, 0x11, 0x39, 0xa1, 0xdc, 0x54, 0xa5, - 0xa7, 0x71, 0xfe, 0x3f, 0x1f, 0xa6, 0x3c, 0x26, 0x93, 0x72, 0x11, 0x6b, 0x64, 0x18, 0x00, 0x83, - 0xf7, 0xd5, 0x95, 0x5b, 0x16, 0x97, 0xc0, 0xb2, 0xf1, 0x23, 0x51, 0x76, 0x32, 0x01, 0x8b, 0x3f, - 0x20, 0x45, 0x69, 0x56, 0xce, 0x5b, 0x2f, 0x61, 0xb5, 0x72, 0xe3, 0xee, 0xae, 0x3d, 0x87, 0xd5, - 0xda, 0x00, 0x33, 0xd2, 0xb1, 0x32, 0x08, 0x9c, 0x52, 0x16, 0x0f, 0x11, 0x0f, 0xc2, 0xa3, 0x9d, - 0xf6, 0xee, 0x49, 0x3d, 0xf2, 0xd8, 0x0d, 0xe8, 0x3b, 0x46, 0xd4, 0xa7, 0x34, 0xeb, 0x5d, 0xcd, - 0x97, 0xcd, 0xe0, 0x73, 0xd9, 0xac, 0x17, 0xa0, 0xef, 0x2f, 0x5a, 0x7f, 0x11, 0xad, 0xd7, 0xf7, - 0x66, 0x7b, 0x94, 0xf2, 0x78, 0x9a, 0x44, 0x8a, 0xb4, 0x3f, 0xd0, 0x3f, 0x1d, 0x3b, 0x98, 0x48, - 0x2e, 0x72, 0xb4, 0x8e, 0x66, 0x6f, 0xf7, 0x1c, 0xa0, 0xef, 0xfd, 0x97, 0x88, 0xbd, 0xeb, 0xf9, - 0x4a, 0x84, 0x8b, 0x95, 0x08, 0x3f, 0x56, 0x22, 0x7c, 0x5a, 0x8b, 0x60, 0xb1, 0x16, 0xc1, 0xdb, - 0x5a, 0x04, 0x77, 0x67, 0x5b, 0x54, 0x46, 0x93, 0x67, 0xc8, 0x33, 0x32, 0x13, 0x57, 0x77, 0x14, - 0x19, 0x94, 0x8f, 0xbf, 0xbf, 0xd2, 0x2d, 0x4a, 0x2a, 0x2e, 0xfb, 0xe9, 0x57, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x87, 0xe5, 0x07, 0xed, 0xd0, 0x01, 0x00, 0x00, +var fileDescriptor_cc8299d306f3ff47 = []byte{ + // 357 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0xcf, 0x4e, 0xea, 0x40, + 0x14, 0xc6, 0x5b, 0xee, 0x0d, 0x8b, 0xde, 0xcd, 0x4d, 0x63, 0x22, 0x10, 0xd3, 0x62, 0x57, 0xb0, + 0xa0, 0x0d, 0xfe, 0xd9, 0xb8, 0x84, 0x44, 0x57, 0x44, 0xc3, 0xd2, 0x4d, 0x33, 0x1d, 0x0e, 0xa5, + 0xc1, 0xce, 0x69, 0x66, 0x06, 0xb5, 0x8f, 0xe0, 0xce, 0x95, 0x0f, 0xe1, 0x93, 0xb0, 0x64, 0xe9, + 0xaa, 0x1a, 0x78, 0x03, 0x9e, 0xc0, 0x30, 0x1d, 0x0d, 0xa8, 0x71, 0x35, 0xe7, 0xe4, 0x7c, 0xdf, + 0x6f, 0xbe, 0x33, 0x63, 0xb5, 0x51, 0xa4, 0x28, 0x12, 0x11, 0x48, 0x9c, 0x02, 0x1b, 0x13, 0x2a, + 0x91, 0xe7, 0xc1, 0x6d, 0x37, 0x02, 0x49, 0xba, 0x41, 0x46, 0x38, 0x49, 0x85, 0x9f, 0x71, 0x94, + 0x68, 0x1f, 0x68, 0xa9, 0xbf, 0x2d, 0xf5, 0xb5, 0xb4, 0xb1, 0x17, 0x63, 0x8c, 0x4a, 0x18, 0x6c, + 0xaa, 0xd2, 0xd3, 0x38, 0xf9, 0x15, 0x4f, 0x66, 0x72, 0x82, 0x3c, 0x91, 0xf9, 0x00, 0x24, 0x19, + 0x11, 0x49, 0xb4, 0xab, 0x4e, 0x95, 0x2d, 0x2c, 0x71, 0x65, 0xa3, 0x47, 0x4e, 0xd9, 0x05, 0x11, + 0x11, 0xf0, 0xc9, 0xa1, 0x98, 0xb0, 0x72, 0xee, 0x3d, 0x54, 0xac, 0xea, 0x95, 0x4a, 0x6d, 0x3f, + 0x99, 0x96, 0x3d, 0x02, 0x86, 0x69, 0x48, 0x39, 0x10, 0x99, 0x20, 0x0b, 0xc7, 0x00, 0x35, 0xb3, + 0xf9, 0xa7, 0xf5, 0xef, 0xa8, 0xee, 0x6b, 0xec, 0x06, 0xf4, 0xb1, 0x84, 0xdf, 0xc7, 0x84, 0xf5, + 0x06, 0xf3, 0xc2, 0x35, 0xd6, 0x85, 0x5b, 0xcf, 0x49, 0x7a, 0x73, 0xe6, 0x7d, 0x47, 0x78, 0xcf, + 0xaf, 0x6e, 0x2b, 0x4e, 0xe4, 0x64, 0x16, 0xf9, 0x14, 0x53, 0x1d, 0x50, 0x1f, 0x1d, 0x31, 0x9a, + 0x06, 0x32, 0xcf, 0x40, 0x28, 0x9a, 0x18, 0xfe, 0x57, 0x80, 0xbe, 0xf6, 0x9f, 0x03, 0xd8, 0x63, + 0xab, 0xf1, 0x05, 0x1a, 0x13, 0x11, 0x52, 0x64, 0x62, 0x96, 0x42, 0xad, 0xd2, 0x34, 0x5b, 0x7f, + 0x7b, 0xed, 0x79, 0xe1, 0x9a, 0xeb, 0xc2, 0x3d, 0xfc, 0x31, 0xc4, 0x96, 0xde, 0x1b, 0xee, 0xef, + 0x5c, 0x70, 0x41, 0x44, 0xbf, 0x9c, 0xf4, 0x2e, 0xe7, 0x4b, 0xc7, 0x5c, 0x2c, 0x1d, 0xf3, 0x6d, + 0xe9, 0x98, 0x8f, 0x2b, 0xc7, 0x58, 0xac, 0x1c, 0xe3, 0x65, 0xe5, 0x18, 0xd7, 0xa7, 0x5b, 0xe9, + 0x25, 0xf0, 0x8c, 0x81, 0xbc, 0x43, 0x3e, 0x55, 0x75, 0x87, 0x22, 0x87, 0xe0, 0x7e, 0xf7, 0xc7, + 0xd4, 0x42, 0x51, 0x55, 0xbd, 0xf1, 0xf1, 0x7b, 0x00, 0x00, 0x00, 0xff, 0xff, 0x6f, 0xe7, 0xf3, + 0xf7, 0x35, 0x02, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -131,6 +137,11 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.DenomCreationGasConsume != 0 { + i = encodeVarintParams(dAtA, i, uint64(m.DenomCreationGasConsume)) + i-- + dAtA[i] = 0x10 + } if len(m.DenomCreationFee) > 0 { for iNdEx := len(m.DenomCreationFee) - 1; iNdEx >= 0; iNdEx-- { { @@ -159,7 +170,6 @@ func encodeVarintParams(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } - func (m *Params) Size() (n int) { if m == nil { return 0 @@ -172,17 +182,18 @@ func (m *Params) Size() (n int) { n += 1 + l + sovParams(uint64(l)) } } + if m.DenomCreationGasConsume != 0 { + n += 1 + sovParams(uint64(m.DenomCreationGasConsume)) + } 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 @@ -246,6 +257,25 @@ func (m *Params) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DenomCreationGasConsume", wireType) + } + m.DenomCreationGasConsume = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.DenomCreationGasConsume |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipParams(dAtA[iNdEx:]) @@ -267,7 +297,6 @@ func (m *Params) Unmarshal(dAtA []byte) error { } return nil } - func skipParams(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/tokenfactory/types/params_legacy.go b/x/tokenfactory/types/params_legacy.go new file mode 100644 index 0000000..43c1f6f --- /dev/null +++ b/x/tokenfactory/types/params_legacy.go @@ -0,0 +1,30 @@ +/* +NOTE: Usage of x/params to manage parameters is deprecated in favor of x/gov +controlled execution of MsgUpdateParams messages. These types remains solely +for migration purposes and will be removed in a future release. +*/ +package types + +import ( + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +// Parameter legacy store keys. +var ( + KeyDenomCreationFee = []byte("DenomCreationFee") + KeyDenomCreationGasConsume = []byte("DenomCreationGasConsume") +) + +// ParamTable for tokenfactory module. +func ParamKeyTable() paramtypes.KeyTable { + return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) +} + +// Implements params.ParamSet. +// Deprecated: legacy code. Remove after v47 upgrade. +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{ + paramtypes.NewParamSetPair(KeyDenomCreationFee, &p.DenomCreationFee, validateDenomCreationFee), + paramtypes.NewParamSetPair(KeyDenomCreationGasConsume, &p.DenomCreationGasConsume, validateDenomCreationFeeGasConsume), + } +} diff --git a/x/tokenfactory/types/query.pb.go b/x/tokenfactory/types/query.pb.go index 61e82d9..757b909 100644 --- a/x/tokenfactory/types/query.pb.go +++ b/x/tokenfactory/types/query.pb.go @@ -1,15 +1,11 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/tokenfactory/v1beta1/query.proto +// source: osmosis/tokenfactory/v1beta1/query.proto package types import ( context "context" fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - _ "github.com/cosmos/cosmos-sdk/types/query" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" @@ -18,14 +14,15 @@ import ( 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 - _ = fmt.Errorf - _ = math.Inf -) +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. @@ -34,19 +31,18 @@ var ( const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // QueryParamsRequest is the request type for the Query/Params RPC method. -type QueryParamsRequest struct{} +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_d8606ce711f56ea6, []int{0} + return fileDescriptor_6f22013ad0f72e3f, []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) @@ -59,15 +55,12 @@ func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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) } @@ -84,13 +77,11 @@ 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_d8606ce711f56ea6, []int{1} + return fileDescriptor_6f22013ad0f72e3f, []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) @@ -103,15 +94,12 @@ func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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) } @@ -135,13 +123,11 @@ func (m *QueryDenomAuthorityMetadataRequest) Reset() { *m = QueryDenomAu func (m *QueryDenomAuthorityMetadataRequest) String() string { return proto.CompactTextString(m) } func (*QueryDenomAuthorityMetadataRequest) ProtoMessage() {} func (*QueryDenomAuthorityMetadataRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_d8606ce711f56ea6, []int{2} + return fileDescriptor_6f22013ad0f72e3f, []int{2} } - func (m *QueryDenomAuthorityMetadataRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *QueryDenomAuthorityMetadataRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryDenomAuthorityMetadataRequest.Marshal(b, m, deterministic) @@ -154,15 +140,12 @@ func (m *QueryDenomAuthorityMetadataRequest) XXX_Marshal(b []byte, deterministic return b[:n], nil } } - func (m *QueryDenomAuthorityMetadataRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryDenomAuthorityMetadataRequest.Merge(m, src) } - func (m *QueryDenomAuthorityMetadataRequest) XXX_Size() int { return m.Size() } - func (m *QueryDenomAuthorityMetadataRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryDenomAuthorityMetadataRequest.DiscardUnknown(m) } @@ -186,13 +169,11 @@ func (m *QueryDenomAuthorityMetadataResponse) Reset() { *m = QueryDenomA func (m *QueryDenomAuthorityMetadataResponse) String() string { return proto.CompactTextString(m) } func (*QueryDenomAuthorityMetadataResponse) ProtoMessage() {} func (*QueryDenomAuthorityMetadataResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_d8606ce711f56ea6, []int{3} + return fileDescriptor_6f22013ad0f72e3f, []int{3} } - func (m *QueryDenomAuthorityMetadataResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *QueryDenomAuthorityMetadataResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryDenomAuthorityMetadataResponse.Marshal(b, m, deterministic) @@ -205,15 +186,12 @@ func (m *QueryDenomAuthorityMetadataResponse) XXX_Marshal(b []byte, deterministi return b[:n], nil } } - func (m *QueryDenomAuthorityMetadataResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryDenomAuthorityMetadataResponse.Merge(m, src) } - func (m *QueryDenomAuthorityMetadataResponse) XXX_Size() int { return m.Size() } - func (m *QueryDenomAuthorityMetadataResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryDenomAuthorityMetadataResponse.DiscardUnknown(m) } @@ -237,13 +215,11 @@ func (m *QueryDenomsFromCreatorRequest) Reset() { *m = QueryDenomsFromCr func (m *QueryDenomsFromCreatorRequest) String() string { return proto.CompactTextString(m) } func (*QueryDenomsFromCreatorRequest) ProtoMessage() {} func (*QueryDenomsFromCreatorRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_d8606ce711f56ea6, []int{4} + return fileDescriptor_6f22013ad0f72e3f, []int{4} } - func (m *QueryDenomsFromCreatorRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *QueryDenomsFromCreatorRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryDenomsFromCreatorRequest.Marshal(b, m, deterministic) @@ -256,15 +232,12 @@ func (m *QueryDenomsFromCreatorRequest) XXX_Marshal(b []byte, deterministic bool return b[:n], nil } } - func (m *QueryDenomsFromCreatorRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryDenomsFromCreatorRequest.Merge(m, src) } - func (m *QueryDenomsFromCreatorRequest) XXX_Size() int { return m.Size() } - func (m *QueryDenomsFromCreatorRequest) XXX_DiscardUnknown() { xxx_messageInfo_QueryDenomsFromCreatorRequest.DiscardUnknown(m) } @@ -288,13 +261,11 @@ func (m *QueryDenomsFromCreatorResponse) Reset() { *m = QueryDenomsFromC func (m *QueryDenomsFromCreatorResponse) String() string { return proto.CompactTextString(m) } func (*QueryDenomsFromCreatorResponse) ProtoMessage() {} func (*QueryDenomsFromCreatorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_d8606ce711f56ea6, []int{5} + return fileDescriptor_6f22013ad0f72e3f, []int{5} } - func (m *QueryDenomsFromCreatorResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *QueryDenomsFromCreatorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_QueryDenomsFromCreatorResponse.Marshal(b, m, deterministic) @@ -307,15 +278,12 @@ func (m *QueryDenomsFromCreatorResponse) XXX_Marshal(b []byte, deterministic boo return b[:n], nil } } - func (m *QueryDenomsFromCreatorResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_QueryDenomsFromCreatorResponse.Merge(m, src) } - func (m *QueryDenomsFromCreatorResponse) XXX_Size() int { return m.Size() } - func (m *QueryDenomsFromCreatorResponse) XXX_DiscardUnknown() { xxx_messageInfo_QueryDenomsFromCreatorResponse.DiscardUnknown(m) } @@ -339,55 +307,52 @@ func init() { } func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/query.proto", fileDescriptor_d8606ce711f56ea6) -} - -var fileDescriptor_d8606ce711f56ea6 = []byte{ - // 582 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0x4d, 0x4f, 0x13, 0x41, - 0x18, 0xee, 0x2a, 0xd4, 0x30, 0x7e, 0x44, 0x46, 0x62, 0xb4, 0xc1, 0xad, 0x8e, 0x84, 0x80, 0xc1, - 0x1d, 0xc1, 0x8f, 0x83, 0x68, 0x94, 0xc5, 0xe8, 0x41, 0x89, 0xba, 0x37, 0xbd, 0x34, 0xd3, 0x65, - 0x58, 0x36, 0xb0, 0xfb, 0x2e, 0x33, 0x53, 0xb1, 0x21, 0x5c, 0x3c, 0x78, 0x36, 0xf1, 0xe8, 0x7f, - 0xf0, 0x77, 0x70, 0x24, 0xe1, 0xe2, 0xa9, 0x31, 0x2d, 0xf1, 0x07, 0xf4, 0x17, 0x98, 0xce, 0x4c, - 0xb5, 0xd8, 0xb2, 0xa9, 0x7a, 0xea, 0x64, 0xe6, 0x79, 0x9e, 0xf7, 0x79, 0xde, 0xf7, 0xed, 0xa2, - 0xd9, 0x10, 0x64, 0xb2, 0xcd, 0x64, 0x42, 0x15, 0x6c, 0xf0, 0x74, 0x8d, 0x85, 0x0a, 0x44, 0x9d, - 0xbe, 0x9b, 0xaf, 0x72, 0xc5, 0xe6, 0xe9, 0x56, 0x8d, 0x8b, 0xba, 0x97, 0x09, 0x50, 0x80, 0x27, - 0x41, 0x26, 0x20, 0x63, 0xe9, 0xf5, 0x22, 0x3d, 0x8b, 0x2c, 0x4d, 0x44, 0x10, 0x81, 0x06, 0xd2, - 0xce, 0xc9, 0x70, 0x4a, 0x93, 0x11, 0x40, 0xb4, 0xc9, 0x29, 0xcb, 0x62, 0xca, 0xd2, 0x14, 0x14, - 0x53, 0x31, 0xa4, 0xd2, 0xbe, 0xde, 0x08, 0xb5, 0x24, 0xad, 0x32, 0xc9, 0x4d, 0xa9, 0x5f, 0x85, - 0x33, 0x16, 0xc5, 0xa9, 0x06, 0x5b, 0xec, 0xbd, 0x7c, 0xa3, 0xac, 0xa6, 0xd6, 0x41, 0xc4, 0xaa, - 0x5e, 0x49, 0xb8, 0x62, 0xab, 0x4c, 0xb1, 0xde, 0x1a, 0xc7, 0xf3, 0x32, 0x26, 0x58, 0x62, 0xfd, - 0x90, 0x09, 0x84, 0x5f, 0x77, 0x5c, 0xbc, 0xd2, 0x97, 0x01, 0xdf, 0xaa, 0x71, 0xa9, 0xc8, 0x1b, - 0x74, 0xe1, 0xc8, 0xad, 0xcc, 0x20, 0x95, 0x1c, 0xfb, 0xa8, 0x68, 0xc8, 0x97, 0x9c, 0xab, 0xce, - 0xcc, 0xe9, 0x85, 0x29, 0x2f, 0xaf, 0x3f, 0x9e, 0x61, 0xfb, 0x23, 0x7b, 0x8d, 0x72, 0x21, 0xb0, - 0x4c, 0xf2, 0x02, 0x11, 0x2d, 0xfd, 0x84, 0xa7, 0x90, 0x2c, 0x75, 0x23, 0xac, 0xd8, 0x04, 0xd6, - 0x00, 0x9e, 0x46, 0xa3, 0xab, 0x1d, 0x80, 0x2e, 0x34, 0xe6, 0x9f, 0x6f, 0x37, 0xca, 0x67, 0xea, - 0x2c, 0xd9, 0xbc, 0x4f, 0xf4, 0x35, 0x09, 0xcc, 0x33, 0xf9, 0xea, 0xa0, 0xeb, 0xb9, 0x72, 0xd6, - 0xf9, 0x47, 0x07, 0xe1, 0xfe, 0x7e, 0xd9, 0x18, 0x77, 0xf2, 0x63, 0x0c, 0x96, 0xf6, 0xaf, 0x75, - 0x62, 0xb5, 0x1b, 0xe5, 0xcb, 0xc6, 0x57, 0xbf, 0x3a, 0x09, 0xc6, 0xd9, 0x9f, 0x2c, 0xb2, 0x82, - 0xae, 0xfc, 0xf6, 0x2b, 0x9f, 0x0a, 0x48, 0x96, 0x05, 0x67, 0x0a, 0x44, 0x37, 0xf9, 0x1c, 0x3a, - 0x15, 0x9a, 0x1b, 0x9b, 0x1d, 0xb7, 0x1b, 0xe5, 0x73, 0xa6, 0x86, 0x7d, 0x20, 0x41, 0x17, 0x42, - 0x9e, 0x23, 0xf7, 0x38, 0x39, 0x9b, 0x7c, 0x16, 0x15, 0x75, 0xab, 0x3a, 0x33, 0x3b, 0x39, 0x33, - 0xe6, 0x8f, 0xb7, 0x1b, 0xe5, 0xb3, 0x3d, 0xad, 0x94, 0x24, 0xb0, 0x80, 0x85, 0xc3, 0x11, 0x34, - 0xaa, 0xd5, 0xf0, 0x17, 0x07, 0x15, 0xcd, 0xf4, 0xf0, 0xad, 0xfc, 0xe6, 0xf4, 0x2f, 0x4f, 0x69, - 0xfe, 0x2f, 0x18, 0xc6, 0x24, 0x99, 0xfb, 0x70, 0x70, 0xf8, 0xf9, 0xc4, 0x34, 0x9e, 0xa2, 0x96, - 0x9a, 0xb7, 0xb9, 0xf8, 0x87, 0x83, 0x2e, 0x0e, 0x1e, 0x0a, 0x7e, 0x3c, 0x44, 0xed, 0xdc, 0xcd, - 0x2b, 0x2d, 0xfd, 0x87, 0x82, 0x4d, 0xf3, 0x4c, 0xa7, 0x59, 0xc2, 0x8f, 0xf2, 0xd3, 0x98, 0xae, - 0xd3, 0x1d, 0xfd, 0xbb, 0x3b, 0xe0, 0xef, 0x8c, 0x0f, 0x1c, 0x34, 0xde, 0x37, 0x59, 0xbc, 0x38, - 0xac, 0xc3, 0x01, 0xeb, 0x55, 0x7a, 0xf0, 0x6f, 0x64, 0x9b, 0x6c, 0x59, 0x27, 0x7b, 0x88, 0x17, - 0x87, 0x49, 0x56, 0x59, 0x13, 0x90, 0x54, 0xec, 0xa6, 0xd2, 0x1d, 0x7b, 0xd8, 0xf5, 0x5f, 0xee, - 0x35, 0x5d, 0x67, 0xbf, 0xe9, 0x3a, 0xdf, 0x9b, 0xae, 0xf3, 0xa9, 0xe5, 0x16, 0xf6, 0x5b, 0x6e, - 0xe1, 0x5b, 0xcb, 0x2d, 0xbc, 0xbd, 0x1b, 0xc5, 0x6a, 0xbd, 0x56, 0xf5, 0x42, 0x48, 0xa8, 0xe2, - 0x22, 0x4b, 0xb9, 0xda, 0x06, 0xb1, 0xa1, 0xcf, 0x37, 0x43, 0x10, 0x9c, 0xbe, 0x3f, 0x5a, 0x50, - 0xd5, 0x33, 0x2e, 0xab, 0x45, 0xfd, 0x29, 0xbb, 0xfd, 0x33, 0x00, 0x00, 0xff, 0xff, 0x57, 0xf9, - 0x26, 0xf2, 0xd9, 0x05, 0x00, 0x00, + proto.RegisterFile("osmosis/tokenfactory/v1beta1/query.proto", fileDescriptor_6f22013ad0f72e3f) +} + +var fileDescriptor_6f22013ad0f72e3f = []byte{ + // 576 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0xcf, 0x4f, 0x13, 0x41, + 0x14, 0xee, 0x2a, 0xd4, 0x30, 0xfe, 0x88, 0x1d, 0x89, 0xd1, 0x06, 0xb7, 0x3a, 0x12, 0x52, 0x0c, + 0xee, 0x58, 0xc4, 0x8b, 0x68, 0xb4, 0x8b, 0xd1, 0x83, 0x12, 0x75, 0x6f, 0x7a, 0x69, 0xa6, 0x65, + 0x58, 0x36, 0xb0, 0xfb, 0x96, 0x99, 0xa9, 0xda, 0x10, 0x2e, 0x1e, 0x3c, 0x9b, 0x78, 0xf4, 0x7f, + 0xf0, 0xef, 0xe0, 0x48, 0xc2, 0xc5, 0x53, 0x63, 0x5a, 0xe2, 0x1f, 0xd0, 0xbf, 0xc0, 0x74, 0x66, + 0x40, 0xb0, 0x75, 0x53, 0xe5, 0xb4, 0x93, 0x99, 0xef, 0xfb, 0xde, 0xf7, 0xbd, 0xf7, 0xb2, 0xa8, + 0x0c, 0x32, 0x06, 0x19, 0x49, 0xaa, 0x60, 0x9d, 0x27, 0xab, 0xac, 0xa1, 0x40, 0xb4, 0xe8, 0xbb, + 0x4a, 0x9d, 0x2b, 0x56, 0xa1, 0x9b, 0x4d, 0x2e, 0x5a, 0x5e, 0x2a, 0x40, 0x01, 0x9e, 0xb2, 0x48, + 0xef, 0x28, 0xd2, 0xb3, 0xc8, 0xe2, 0x64, 0x08, 0x21, 0x68, 0x20, 0xed, 0x9f, 0x0c, 0xa7, 0x38, + 0x15, 0x02, 0x84, 0x1b, 0x9c, 0xb2, 0x34, 0xa2, 0x2c, 0x49, 0x40, 0x31, 0x15, 0x41, 0x22, 0xed, + 0xeb, 0xad, 0x86, 0x96, 0xa4, 0x75, 0x26, 0xb9, 0x29, 0x75, 0x58, 0x38, 0x65, 0x61, 0x94, 0x68, + 0xb0, 0xc5, 0x2e, 0x64, 0xfa, 0x64, 0x4d, 0xb5, 0x06, 0x22, 0x52, 0xad, 0x65, 0xae, 0xd8, 0x0a, + 0x53, 0xcc, 0xb2, 0x66, 0x33, 0x59, 0x29, 0x13, 0x2c, 0xb6, 0x66, 0xc8, 0x24, 0xc2, 0xaf, 0xfb, + 0x16, 0x5e, 0xe9, 0xcb, 0x80, 0x6f, 0x36, 0xb9, 0x54, 0xe4, 0x0d, 0xba, 0x74, 0xec, 0x56, 0xa6, + 0x90, 0x48, 0x8e, 0x7d, 0x94, 0x37, 0xe4, 0x2b, 0xce, 0x75, 0xa7, 0x7c, 0x76, 0x7e, 0xda, 0xcb, + 0x6a, 0x8e, 0x67, 0xd8, 0xfe, 0xd8, 0x4e, 0xbb, 0x94, 0x0b, 0x2c, 0x93, 0xbc, 0x40, 0x44, 0x4b, + 0x3f, 0xe1, 0x09, 0xc4, 0xd5, 0x3f, 0x03, 0x58, 0x03, 0x78, 0x06, 0x8d, 0xaf, 0xf4, 0x01, 0xba, + 0xd0, 0x84, 0x7f, 0xb1, 0xd7, 0x2e, 0x9d, 0x6b, 0xb1, 0x78, 0xe3, 0x3e, 0xd1, 0xd7, 0x24, 0x30, + 0xcf, 0xe4, 0x9b, 0x83, 0x6e, 0x66, 0xca, 0x59, 0xe7, 0x9f, 0x1c, 0x84, 0x0f, 0xbb, 0x55, 0x8b, + 0xed, 0xb3, 0x8d, 0xb1, 0x90, 0x1d, 0x63, 0xb8, 0xb4, 0x7f, 0xa3, 0x1f, 0xab, 0xd7, 0x2e, 0x5d, + 0x35, 0xbe, 0x06, 0xd5, 0x49, 0x50, 0x18, 0x18, 0x10, 0x59, 0x46, 0xd7, 0x7e, 0xfb, 0x95, 0x4f, + 0x05, 0xc4, 0x4b, 0x82, 0x33, 0x05, 0xe2, 0x20, 0xf9, 0x1c, 0x3a, 0xd3, 0x30, 0x37, 0x36, 0x3b, + 0xee, 0xb5, 0x4b, 0x17, 0x4c, 0x0d, 0xfb, 0x40, 0x82, 0x03, 0x08, 0x79, 0x8e, 0xdc, 0xbf, 0xc9, + 0xd9, 0xe4, 0xb3, 0x28, 0xaf, 0x5b, 0xd5, 0x9f, 0xd9, 0xe9, 0xf2, 0x84, 0x5f, 0xe8, 0xb5, 0x4b, + 0xe7, 0x8f, 0xb4, 0x52, 0x92, 0xc0, 0x02, 0xe6, 0xf7, 0xc7, 0xd0, 0xb8, 0x56, 0xc3, 0x5f, 0x1d, + 0x94, 0x37, 0xd3, 0xc3, 0x77, 0xb2, 0x9b, 0x33, 0xb8, 0x3c, 0xc5, 0xca, 0x3f, 0x30, 0x8c, 0x49, + 0x32, 0xf7, 0x71, 0x6f, 0xff, 0xcb, 0xa9, 0x19, 0x3c, 0x4d, 0x47, 0xd8, 0x5c, 0xfc, 0xd3, 0x41, + 0x97, 0x87, 0x0f, 0x05, 0x3f, 0x1e, 0xa1, 0x76, 0xe6, 0xe6, 0x15, 0xab, 0x27, 0x50, 0xb0, 0x69, + 0x9e, 0xe9, 0x34, 0x55, 0xfc, 0x28, 0x3b, 0x8d, 0xe9, 0x3a, 0xdd, 0xd2, 0xdf, 0x6d, 0x3a, 0xb8, + 0x40, 0x78, 0xcf, 0x41, 0x85, 0x81, 0xc9, 0xe2, 0xc5, 0x51, 0x1d, 0x0e, 0x59, 0xaf, 0xe2, 0x83, + 0xff, 0x23, 0xdb, 0x64, 0x4b, 0x3a, 0xd9, 0x43, 0xbc, 0x38, 0x4a, 0xb2, 0xda, 0xaa, 0x80, 0xb8, + 0x66, 0x37, 0x95, 0x6e, 0xd9, 0xc3, 0xb6, 0xff, 0x72, 0xa7, 0xe3, 0x3a, 0xbb, 0x1d, 0xd7, 0xf9, + 0xd1, 0x71, 0x9d, 0xcf, 0x5d, 0x37, 0xb7, 0xdb, 0x75, 0x73, 0xdf, 0xbb, 0x6e, 0xee, 0xed, 0xbd, + 0x30, 0x52, 0x6b, 0xcd, 0xba, 0xd7, 0x80, 0x98, 0x2a, 0x2e, 0xd2, 0x84, 0xab, 0xf7, 0x20, 0xd6, + 0xf5, 0xf9, 0x76, 0x03, 0x04, 0xa7, 0x1f, 0x8e, 0x17, 0x54, 0xad, 0x94, 0xcb, 0x7a, 0x5e, 0xff, + 0xca, 0xee, 0xfe, 0x0a, 0x00, 0x00, 0xff, 0xff, 0xbd, 0x78, 0xed, 0x18, 0xd5, 0x05, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. -var ( - _ context.Context - _ grpc.ClientConn -) +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. @@ -457,16 +422,15 @@ type QueryServer interface { } // UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct{} +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) DenomAuthorityMetadata(ctx context.Context, req *QueryDenomAuthorityMetadataRequest) (*QueryDenomAuthorityMetadataResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method DenomAuthorityMetadata not implemented") } - func (*UnimplementedQueryServer) DenomsFromCreator(ctx context.Context, req *QueryDenomsFromCreatorRequest) (*QueryDenomsFromCreatorResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method DenomsFromCreator not implemented") } @@ -547,7 +511,7 @@ var _Query_serviceDesc = grpc.ServiceDesc{ }, }, Streams: []grpc.StreamDesc{}, - Metadata: "cosmwasm/tokenfactory/v1beta1/query.proto", + Metadata: "osmosis/tokenfactory/v1beta1/query.proto", } func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { @@ -742,7 +706,6 @@ func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } - func (m *QueryParamsRequest) Size() (n int) { if m == nil { return 0 @@ -818,11 +781,9 @@ func (m *QueryDenomsFromCreatorResponse) Size() (n int) { 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 @@ -873,7 +834,6 @@ func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { } return nil } - func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -957,7 +917,6 @@ func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { } return nil } - func (m *QueryDenomAuthorityMetadataRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1040,7 +999,6 @@ func (m *QueryDenomAuthorityMetadataRequest) Unmarshal(dAtA []byte) error { } return nil } - func (m *QueryDenomAuthorityMetadataResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1124,7 +1082,6 @@ func (m *QueryDenomAuthorityMetadataResponse) Unmarshal(dAtA []byte) error { } return nil } - func (m *QueryDenomsFromCreatorRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1207,7 +1164,6 @@ func (m *QueryDenomsFromCreatorRequest) Unmarshal(dAtA []byte) error { } return nil } - func (m *QueryDenomsFromCreatorResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1290,7 +1246,6 @@ func (m *QueryDenomsFromCreatorResponse) Unmarshal(dAtA []byte) error { } return nil } - func skipQuery(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/tokenfactory/types/query.pb.gw.go b/x/tokenfactory/types/query.pb.gw.go index af07c01..0b895e7 100644 --- a/x/tokenfactory/types/query.pb.gw.go +++ b/x/tokenfactory/types/query.pb.gw.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: cosmwasm/tokenfactory/v1beta1/query.proto +// source: osmosis/tokenfactory/v1beta1/query.proto /* Package types is a reverse proxy. @@ -25,15 +25,13 @@ import ( ) // Suppress "imported and not used" errors -var ( - _ codes.Code - _ io.Reader - _ status.Status - _ = runtime.String - _ = utilities.NewDoubleArray - _ = descriptor.ForMessage - _ = metadata.Join -) +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 @@ -41,6 +39,7 @@ func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, cl 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) { @@ -49,6 +48,7 @@ func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshal msg, err := server.Params(ctx, &protoReq) return msg, metadata, err + } func request_Query_DenomAuthorityMetadata_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -75,6 +75,7 @@ func request_Query_DenomAuthorityMetadata_0(ctx context.Context, marshaler runti msg, err := client.DenomAuthorityMetadata(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err + } func local_request_Query_DenomAuthorityMetadata_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -101,6 +102,7 @@ func local_request_Query_DenomAuthorityMetadata_0(ctx context.Context, marshaler msg, err := server.DenomAuthorityMetadata(ctx, &protoReq) return msg, metadata, err + } func request_Query_DenomsFromCreator_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -127,6 +129,7 @@ func request_Query_DenomsFromCreator_0(ctx context.Context, marshaler runtime.Ma msg, err := client.DenomsFromCreator(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) return msg, metadata, err + } func local_request_Query_DenomsFromCreator_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { @@ -153,6 +156,7 @@ func local_request_Query_DenomsFromCreator_0(ctx context.Context, marshaler runt msg, err := server.DenomsFromCreator(ctx, &protoReq) return msg, metadata, err + } // RegisterQueryHandlerServer registers the http handlers for service Query to "mux". @@ -160,6 +164,7 @@ func local_request_Query_DenomsFromCreator_0(ctx context.Context, marshaler runt // 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() @@ -180,6 +185,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle("GET", pattern_Query_DenomAuthorityMetadata_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -202,6 +208,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } forward_Query_DenomAuthorityMetadata_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle("GET", pattern_Query_DenomsFromCreator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -224,6 +231,7 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } forward_Query_DenomsFromCreator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) return nil @@ -266,6 +274,7 @@ func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc // 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() @@ -283,6 +292,7 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle("GET", pattern_Query_DenomAuthorityMetadata_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -302,6 +312,7 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } forward_Query_DenomAuthorityMetadata_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) mux.Handle("GET", pattern_Query_DenomsFromCreator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -321,6 +332,7 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } forward_Query_DenomsFromCreator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) return nil diff --git a/x/tokenfactory/types/tx.pb.go b/x/tokenfactory/types/tx.pb.go index 8aafe6e..d47d5ed 100644 --- a/x/tokenfactory/types/tx.pb.go +++ b/x/tokenfactory/types/tx.pb.go @@ -1,16 +1,14 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/tokenfactory/v1beta1/tx.proto +// source: osmosis/tokenfactory/v1beta1/tx.proto package types import ( context "context" fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - + _ "github.com/cosmos/cosmos-proto" types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" types1 "github.com/cosmos/cosmos-sdk/x/bank/types" _ "github.com/cosmos/gogoproto/gogoproto" grpc1 "github.com/cosmos/gogoproto/grpc" @@ -18,14 +16,15 @@ import ( 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 - _ = fmt.Errorf - _ = math.Inf -) +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. @@ -52,13 +51,11 @@ func (m *MsgCreateDenom) Reset() { *m = MsgCreateDenom{} } func (m *MsgCreateDenom) String() string { return proto.CompactTextString(m) } func (*MsgCreateDenom) ProtoMessage() {} func (*MsgCreateDenom) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{0} + return fileDescriptor_283b6c9a90a846b4, []int{0} } - func (m *MsgCreateDenom) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgCreateDenom) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgCreateDenom.Marshal(b, m, deterministic) @@ -71,15 +68,12 @@ func (m *MsgCreateDenom) XXX_Marshal(b []byte, deterministic bool) ([]byte, erro return b[:n], nil } } - func (m *MsgCreateDenom) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgCreateDenom.Merge(m, src) } - func (m *MsgCreateDenom) XXX_Size() int { return m.Size() } - func (m *MsgCreateDenom) XXX_DiscardUnknown() { xxx_messageInfo_MsgCreateDenom.DiscardUnknown(m) } @@ -101,7 +95,7 @@ func (m *MsgCreateDenom) GetSubdenom() string { } // MsgCreateDenomResponse is the return value of MsgCreateDenom -// It returns the full string of the newly created denom. +// It returns the full string of the newly created denom type MsgCreateDenomResponse struct { NewTokenDenom string `protobuf:"bytes,1,opt,name=new_token_denom,json=newTokenDenom,proto3" json:"new_token_denom,omitempty" yaml:"new_token_denom"` } @@ -110,13 +104,11 @@ func (m *MsgCreateDenomResponse) Reset() { *m = MsgCreateDenomResponse{} func (m *MsgCreateDenomResponse) String() string { return proto.CompactTextString(m) } func (*MsgCreateDenomResponse) ProtoMessage() {} func (*MsgCreateDenomResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{1} + return fileDescriptor_283b6c9a90a846b4, []int{1} } - func (m *MsgCreateDenomResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgCreateDenomResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgCreateDenomResponse.Marshal(b, m, deterministic) @@ -129,15 +121,12 @@ func (m *MsgCreateDenomResponse) XXX_Marshal(b []byte, deterministic bool) ([]by return b[:n], nil } } - func (m *MsgCreateDenomResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgCreateDenomResponse.Merge(m, src) } - func (m *MsgCreateDenomResponse) XXX_Size() int { return m.Size() } - func (m *MsgCreateDenomResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgCreateDenomResponse.DiscardUnknown(m) } @@ -154,21 +143,20 @@ func (m *MsgCreateDenomResponse) GetNewTokenDenom() string { // MsgMint is the sdk.Msg type for allowing an admin account to mint // more of a token. For now, we only support minting to the sender account type MsgMint struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount" yaml:"amount"` + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` + Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount" yaml:"amount"` + MintToAddress string `protobuf:"bytes,3,opt,name=mintToAddress,proto3" json:"mintToAddress,omitempty" yaml:"mint_to_address"` } func (m *MsgMint) Reset() { *m = MsgMint{} } func (m *MsgMint) String() string { return proto.CompactTextString(m) } func (*MsgMint) ProtoMessage() {} func (*MsgMint) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{2} + return fileDescriptor_283b6c9a90a846b4, []int{2} } - func (m *MsgMint) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgMint) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgMint.Marshal(b, m, deterministic) @@ -181,15 +169,12 @@ func (m *MsgMint) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return b[:n], nil } } - func (m *MsgMint) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgMint.Merge(m, src) } - func (m *MsgMint) XXX_Size() int { return m.Size() } - func (m *MsgMint) XXX_DiscardUnknown() { xxx_messageInfo_MsgMint.DiscardUnknown(m) } @@ -210,21 +195,25 @@ func (m *MsgMint) GetAmount() types.Coin { return types.Coin{} } -// MsgMintResponse defines the response structure for an executed -// MsgMint message. -type MsgMintResponse struct{} +func (m *MsgMint) GetMintToAddress() string { + if m != nil { + return m.MintToAddress + } + return "" +} + +type MsgMintResponse struct { +} func (m *MsgMintResponse) Reset() { *m = MsgMintResponse{} } func (m *MsgMintResponse) String() string { return proto.CompactTextString(m) } func (*MsgMintResponse) ProtoMessage() {} func (*MsgMintResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{3} + return fileDescriptor_283b6c9a90a846b4, []int{3} } - func (m *MsgMintResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgMintResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgMintResponse.Marshal(b, m, deterministic) @@ -237,15 +226,12 @@ func (m *MsgMintResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, err return b[:n], nil } } - func (m *MsgMintResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgMintResponse.Merge(m, src) } - func (m *MsgMintResponse) XXX_Size() int { return m.Size() } - func (m *MsgMintResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgMintResponse.DiscardUnknown(m) } @@ -255,21 +241,20 @@ var xxx_messageInfo_MsgMintResponse proto.InternalMessageInfo // MsgBurn is the sdk.Msg type for allowing an admin account to burn // a token. For now, we only support burning from the sender account. type MsgBurn struct { - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` - Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount" yaml:"amount"` + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` + Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount" yaml:"amount"` + BurnFromAddress string `protobuf:"bytes,3,opt,name=burnFromAddress,proto3" json:"burnFromAddress,omitempty" yaml:"burn_from_address"` } func (m *MsgBurn) Reset() { *m = MsgBurn{} } func (m *MsgBurn) String() string { return proto.CompactTextString(m) } func (*MsgBurn) ProtoMessage() {} func (*MsgBurn) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{4} + return fileDescriptor_283b6c9a90a846b4, []int{4} } - func (m *MsgBurn) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgBurn) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgBurn.Marshal(b, m, deterministic) @@ -282,15 +267,12 @@ func (m *MsgBurn) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return b[:n], nil } } - func (m *MsgBurn) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgBurn.Merge(m, src) } - func (m *MsgBurn) XXX_Size() int { return m.Size() } - func (m *MsgBurn) XXX_DiscardUnknown() { xxx_messageInfo_MsgBurn.DiscardUnknown(m) } @@ -311,21 +293,25 @@ func (m *MsgBurn) GetAmount() types.Coin { return types.Coin{} } -// MsgBurnResponse defines the response structure for an executed -// MsgBurn message. -type MsgBurnResponse struct{} +func (m *MsgBurn) GetBurnFromAddress() string { + if m != nil { + return m.BurnFromAddress + } + return "" +} + +type MsgBurnResponse struct { +} func (m *MsgBurnResponse) Reset() { *m = MsgBurnResponse{} } func (m *MsgBurnResponse) String() string { return proto.CompactTextString(m) } func (*MsgBurnResponse) ProtoMessage() {} func (*MsgBurnResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{5} + return fileDescriptor_283b6c9a90a846b4, []int{5} } - func (m *MsgBurnResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgBurnResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgBurnResponse.Marshal(b, m, deterministic) @@ -338,15 +324,12 @@ func (m *MsgBurnResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, err return b[:n], nil } } - func (m *MsgBurnResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgBurnResponse.Merge(m, src) } - func (m *MsgBurnResponse) XXX_Size() int { return m.Size() } - func (m *MsgBurnResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgBurnResponse.DiscardUnknown(m) } @@ -365,13 +348,11 @@ func (m *MsgChangeAdmin) Reset() { *m = MsgChangeAdmin{} } func (m *MsgChangeAdmin) String() string { return proto.CompactTextString(m) } func (*MsgChangeAdmin) ProtoMessage() {} func (*MsgChangeAdmin) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{6} + return fileDescriptor_283b6c9a90a846b4, []int{6} } - func (m *MsgChangeAdmin) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgChangeAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgChangeAdmin.Marshal(b, m, deterministic) @@ -384,15 +365,12 @@ func (m *MsgChangeAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, erro return b[:n], nil } } - func (m *MsgChangeAdmin) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgChangeAdmin.Merge(m, src) } - func (m *MsgChangeAdmin) XXX_Size() int { return m.Size() } - func (m *MsgChangeAdmin) XXX_DiscardUnknown() { xxx_messageInfo_MsgChangeAdmin.DiscardUnknown(m) } @@ -422,19 +400,18 @@ func (m *MsgChangeAdmin) GetNewAdmin() string { // MsgChangeAdminResponse defines the response structure for an executed // MsgChangeAdmin message. -type MsgChangeAdminResponse struct{} +type MsgChangeAdminResponse struct { +} func (m *MsgChangeAdminResponse) Reset() { *m = MsgChangeAdminResponse{} } func (m *MsgChangeAdminResponse) String() string { return proto.CompactTextString(m) } func (*MsgChangeAdminResponse) ProtoMessage() {} func (*MsgChangeAdminResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{7} + return fileDescriptor_283b6c9a90a846b4, []int{7} } - func (m *MsgChangeAdminResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgChangeAdminResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgChangeAdminResponse.Marshal(b, m, deterministic) @@ -447,15 +424,12 @@ func (m *MsgChangeAdminResponse) XXX_Marshal(b []byte, deterministic bool) ([]by return b[:n], nil } } - func (m *MsgChangeAdminResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgChangeAdminResponse.Merge(m, src) } - func (m *MsgChangeAdminResponse) XXX_Size() int { return m.Size() } - func (m *MsgChangeAdminResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgChangeAdminResponse.DiscardUnknown(m) } @@ -463,7 +437,7 @@ func (m *MsgChangeAdminResponse) XXX_DiscardUnknown() { var xxx_messageInfo_MsgChangeAdminResponse proto.InternalMessageInfo // MsgSetDenomMetadata is the sdk.Msg type for allowing an admin account to set -// the denom's bank metadata. +// the denom's bank metadata type MsgSetDenomMetadata struct { Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` Metadata types1.Metadata `protobuf:"bytes,2,opt,name=metadata,proto3" json:"metadata" yaml:"metadata"` @@ -473,13 +447,11 @@ func (m *MsgSetDenomMetadata) Reset() { *m = MsgSetDenomMetadata{} } func (m *MsgSetDenomMetadata) String() string { return proto.CompactTextString(m) } func (*MsgSetDenomMetadata) ProtoMessage() {} func (*MsgSetDenomMetadata) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{8} + return fileDescriptor_283b6c9a90a846b4, []int{8} } - func (m *MsgSetDenomMetadata) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgSetDenomMetadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgSetDenomMetadata.Marshal(b, m, deterministic) @@ -492,15 +464,12 @@ func (m *MsgSetDenomMetadata) XXX_Marshal(b []byte, deterministic bool) ([]byte, return b[:n], nil } } - func (m *MsgSetDenomMetadata) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgSetDenomMetadata.Merge(m, src) } - func (m *MsgSetDenomMetadata) XXX_Size() int { return m.Size() } - func (m *MsgSetDenomMetadata) XXX_DiscardUnknown() { xxx_messageInfo_MsgSetDenomMetadata.DiscardUnknown(m) } @@ -523,19 +492,18 @@ func (m *MsgSetDenomMetadata) GetMetadata() types1.Metadata { // MsgSetDenomMetadataResponse defines the response structure for an executed // MsgSetDenomMetadata message. -type MsgSetDenomMetadataResponse struct{} +type MsgSetDenomMetadataResponse struct { +} func (m *MsgSetDenomMetadataResponse) Reset() { *m = MsgSetDenomMetadataResponse{} } func (m *MsgSetDenomMetadataResponse) String() string { return proto.CompactTextString(m) } func (*MsgSetDenomMetadataResponse) ProtoMessage() {} func (*MsgSetDenomMetadataResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_345508fcea0bfc02, []int{9} + return fileDescriptor_283b6c9a90a846b4, []int{9} } - func (m *MsgSetDenomMetadataResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } - func (m *MsgSetDenomMetadataResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { return xxx_messageInfo_MsgSetDenomMetadataResponse.Marshal(b, m, deterministic) @@ -548,21 +516,221 @@ func (m *MsgSetDenomMetadataResponse) XXX_Marshal(b []byte, deterministic bool) return b[:n], nil } } - func (m *MsgSetDenomMetadataResponse) XXX_Merge(src proto.Message) { xxx_messageInfo_MsgSetDenomMetadataResponse.Merge(m, src) } - func (m *MsgSetDenomMetadataResponse) XXX_Size() int { return m.Size() } - func (m *MsgSetDenomMetadataResponse) XXX_DiscardUnknown() { xxx_messageInfo_MsgSetDenomMetadataResponse.DiscardUnknown(m) } var xxx_messageInfo_MsgSetDenomMetadataResponse proto.InternalMessageInfo +type MsgForceTransfer struct { + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` + Amount types.Coin `protobuf:"bytes,2,opt,name=amount,proto3" json:"amount" yaml:"amount"` + TransferFromAddress string `protobuf:"bytes,3,opt,name=transferFromAddress,proto3" json:"transferFromAddress,omitempty" yaml:"transfer_from_address"` + TransferToAddress string `protobuf:"bytes,4,opt,name=transferToAddress,proto3" json:"transferToAddress,omitempty" yaml:"transfer_to_address"` +} + +func (m *MsgForceTransfer) Reset() { *m = MsgForceTransfer{} } +func (m *MsgForceTransfer) String() string { return proto.CompactTextString(m) } +func (*MsgForceTransfer) ProtoMessage() {} +func (*MsgForceTransfer) Descriptor() ([]byte, []int) { + return fileDescriptor_283b6c9a90a846b4, []int{10} +} +func (m *MsgForceTransfer) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgForceTransfer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgForceTransfer.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 *MsgForceTransfer) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgForceTransfer.Merge(m, src) +} +func (m *MsgForceTransfer) XXX_Size() int { + return m.Size() +} +func (m *MsgForceTransfer) XXX_DiscardUnknown() { + xxx_messageInfo_MsgForceTransfer.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgForceTransfer proto.InternalMessageInfo + +func (m *MsgForceTransfer) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgForceTransfer) GetAmount() types.Coin { + if m != nil { + return m.Amount + } + return types.Coin{} +} + +func (m *MsgForceTransfer) GetTransferFromAddress() string { + if m != nil { + return m.TransferFromAddress + } + return "" +} + +func (m *MsgForceTransfer) GetTransferToAddress() string { + if m != nil { + return m.TransferToAddress + } + return "" +} + +type MsgForceTransferResponse struct { +} + +func (m *MsgForceTransferResponse) Reset() { *m = MsgForceTransferResponse{} } +func (m *MsgForceTransferResponse) String() string { return proto.CompactTextString(m) } +func (*MsgForceTransferResponse) ProtoMessage() {} +func (*MsgForceTransferResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_283b6c9a90a846b4, []int{11} +} +func (m *MsgForceTransferResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgForceTransferResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgForceTransferResponse.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 *MsgForceTransferResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgForceTransferResponse.Merge(m, src) +} +func (m *MsgForceTransferResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgForceTransferResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgForceTransferResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgForceTransferResponse proto.InternalMessageInfo + +// MsgUpdateParams is the Msg/UpdateParams request type. +// +// Since: cosmos-sdk 0.47 +type MsgUpdateParams struct { + // authority is the address of the governance account. + Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` + // params defines the x/mint parameters to update. + // + // NOTE: All parameters must be supplied. + Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` +} + +func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } +func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParams) ProtoMessage() {} +func (*MsgUpdateParams) Descriptor() ([]byte, []int) { + return fileDescriptor_283b6c9a90a846b4, []int{12} +} +func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParams.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 *MsgUpdateParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParams.Merge(m, src) +} +func (m *MsgUpdateParams) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParams) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo + +func (m *MsgUpdateParams) GetAuthority() string { + if m != nil { + return m.Authority + } + return "" +} + +func (m *MsgUpdateParams) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +// MsgUpdateParamsResponse defines the response structure for executing a +// MsgUpdateParams message. +// +// Since: cosmos-sdk 0.47 +type MsgUpdateParamsResponse struct { +} + +func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } +func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateParamsResponse) ProtoMessage() {} +func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_283b6c9a90a846b4, []int{13} +} +func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateParamsResponse.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 *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) +} +func (m *MsgUpdateParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo + func init() { proto.RegisterType((*MsgCreateDenom)(nil), "osmosis.tokenfactory.v1beta1.MsgCreateDenom") proto.RegisterType((*MsgCreateDenomResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgCreateDenomResponse") @@ -574,59 +742,78 @@ func init() { proto.RegisterType((*MsgChangeAdminResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgChangeAdminResponse") proto.RegisterType((*MsgSetDenomMetadata)(nil), "osmosis.tokenfactory.v1beta1.MsgSetDenomMetadata") proto.RegisterType((*MsgSetDenomMetadataResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgSetDenomMetadataResponse") + proto.RegisterType((*MsgForceTransfer)(nil), "osmosis.tokenfactory.v1beta1.MsgForceTransfer") + proto.RegisterType((*MsgForceTransferResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgForceTransferResponse") + proto.RegisterType((*MsgUpdateParams)(nil), "osmosis.tokenfactory.v1beta1.MsgUpdateParams") + proto.RegisterType((*MsgUpdateParamsResponse)(nil), "osmosis.tokenfactory.v1beta1.MsgUpdateParamsResponse") } func init() { - proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/tx.proto", fileDescriptor_345508fcea0bfc02) -} - -var fileDescriptor_345508fcea0bfc02 = []byte{ - // 600 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x55, 0x41, 0x6e, 0xd3, 0x40, - 0x14, 0x8d, 0x69, 0x29, 0xe9, 0x94, 0x92, 0xd4, 0x2d, 0x25, 0x18, 0x6a, 0xa3, 0x91, 0xa8, 0x40, - 0xa2, 0xb6, 0x52, 0x60, 0x01, 0x3b, 0x5c, 0x16, 0x6c, 0x2c, 0x24, 0xc3, 0x0a, 0x55, 0xaa, 0x26, - 0xce, 0xe0, 0x5a, 0xa9, 0x67, 0x82, 0x67, 0x42, 0x9a, 0x0d, 0xe2, 0x08, 0x2c, 0x10, 0x87, 0xe0, - 0x24, 0x5d, 0x76, 0xc9, 0xca, 0x42, 0xc9, 0x0d, 0x72, 0x02, 0xe4, 0x99, 0xb1, 0xe3, 0x34, 0x88, - 0x24, 0x2b, 0x76, 0x8e, 0xff, 0x7b, 0x6f, 0xde, 0xbc, 0xff, 0x7f, 0x0c, 0xf6, 0x03, 0xca, 0xe2, - 0x3e, 0x62, 0xb1, 0xc3, 0x69, 0x07, 0x93, 0x8f, 0x28, 0xe0, 0x34, 0x19, 0x38, 0x9f, 0x9b, 0x2d, - 0xcc, 0x51, 0xd3, 0xe1, 0xe7, 0x76, 0x37, 0xa1, 0x9c, 0xea, 0xf7, 0x29, 0x8b, 0x29, 0x8b, 0x98, - 0x5d, 0x86, 0xd9, 0x0a, 0x66, 0xec, 0x84, 0x34, 0xa4, 0x02, 0xe8, 0x64, 0x4f, 0x92, 0x63, 0x98, - 0x81, 0x20, 0x39, 0x2d, 0xc4, 0x70, 0xa1, 0x18, 0xd0, 0x88, 0xcc, 0xd4, 0x49, 0xa7, 0xa8, 0x67, - 0x3f, 0x64, 0x1d, 0x9e, 0x81, 0x5b, 0x1e, 0x0b, 0x8f, 0x12, 0x8c, 0x38, 0x7e, 0x8d, 0x09, 0x8d, - 0xf5, 0xc7, 0x60, 0x8d, 0x61, 0xd2, 0xc6, 0x49, 0x43, 0x7b, 0xa0, 0x3d, 0x5a, 0x77, 0xb7, 0xc6, - 0xa9, 0xb5, 0x39, 0x40, 0xf1, 0xd9, 0x4b, 0x28, 0xdf, 0x43, 0x5f, 0x01, 0x74, 0x07, 0x54, 0x59, - 0xaf, 0xd5, 0xce, 0x68, 0x8d, 0x6b, 0x02, 0xbc, 0x3d, 0x4e, 0xad, 0x9a, 0x02, 0xab, 0x0a, 0xf4, - 0x0b, 0x10, 0x3c, 0x06, 0xbb, 0xd3, 0xa7, 0xf9, 0x98, 0x75, 0x29, 0x61, 0x58, 0x77, 0x41, 0x8d, - 0xe0, 0xfe, 0x89, 0xb8, 0xf9, 0x89, 0x54, 0x94, 0xc7, 0x1b, 0xe3, 0xd4, 0xda, 0x95, 0x8a, 0x57, - 0x00, 0xd0, 0xdf, 0x24, 0xb8, 0xff, 0x3e, 0x7b, 0x21, 0xb4, 0xe0, 0x17, 0x70, 0xc3, 0x63, 0xa1, - 0x17, 0x11, 0xbe, 0xcc, 0x25, 0xde, 0x80, 0x35, 0x14, 0xd3, 0x1e, 0xe1, 0xe2, 0x0a, 0x1b, 0x87, - 0x77, 0x6d, 0x19, 0x99, 0x9d, 0x45, 0x9a, 0xa7, 0x6f, 0x1f, 0xd1, 0x88, 0xb8, 0xb7, 0x2f, 0x52, - 0xab, 0x32, 0x51, 0x92, 0x34, 0xe8, 0x2b, 0x3e, 0xdc, 0x02, 0x35, 0x75, 0x7e, 0x7e, 0x2d, 0x65, - 0xc9, 0xed, 0x25, 0xe4, 0x7f, 0x5a, 0xca, 0xce, 0x2f, 0x2c, 0xfd, 0xd0, 0x64, 0xcb, 0x4f, 0x11, - 0x09, 0xf1, 0xab, 0x76, 0x1c, 0x2d, 0x65, 0x6d, 0x1f, 0x5c, 0x2f, 0xf7, 0xbb, 0x3e, 0x4e, 0xad, - 0x9b, 0x12, 0xa9, 0x7a, 0x22, 0xcb, 0x7a, 0x13, 0xac, 0x67, 0xed, 0x42, 0x99, 0x7e, 0x63, 0x45, - 0x60, 0x77, 0xc6, 0xa9, 0x55, 0x9f, 0x74, 0x52, 0x94, 0xa0, 0x5f, 0x25, 0xb8, 0x2f, 0x5c, 0xc0, - 0x86, 0x1c, 0x8e, 0x89, 0xaf, 0xc2, 0xf2, 0x77, 0x0d, 0x6c, 0x7b, 0x2c, 0x7c, 0x87, 0xb9, 0x68, - 0xb4, 0x87, 0x39, 0x6a, 0x23, 0x8e, 0x96, 0xf1, 0xed, 0x83, 0x6a, 0xac, 0x68, 0x2a, 0xd4, 0xbd, - 0x49, 0xa8, 0xa4, 0x53, 0x84, 0x9a, 0x6b, 0xbb, 0x77, 0x54, 0xb0, 0x6a, 0x9a, 0x73, 0x32, 0xf4, - 0x0b, 0x1d, 0xb8, 0x07, 0xee, 0xfd, 0xc5, 0x55, 0xee, 0xfa, 0xf0, 0xe7, 0x2a, 0x58, 0xf1, 0x58, - 0xa8, 0x7f, 0x02, 0x1b, 0xe5, 0xfd, 0x7a, 0x62, 0xff, 0x6b, 0xcd, 0xed, 0xe9, 0xfd, 0x30, 0x9e, - 0x2d, 0x83, 0x2e, 0xb6, 0xe9, 0x18, 0xac, 0x8a, 0x35, 0x78, 0x38, 0x97, 0x9d, 0xc1, 0x8c, 0x83, - 0x85, 0x60, 0x65, 0x75, 0x31, 0xd1, 0xf3, 0xd5, 0x33, 0xd8, 0x02, 0xea, 0xe5, 0xf9, 0x14, 0x71, - 0x95, 0x66, 0x73, 0x81, 0xb8, 0x26, 0xe8, 0x45, 0xe2, 0x9a, 0x9d, 0x2f, 0xfd, 0xab, 0x06, 0xea, - 0x33, 0xc3, 0xd5, 0x9c, 0x2b, 0x75, 0x95, 0x62, 0xbc, 0x58, 0x9a, 0x92, 0x5b, 0x70, 0xdf, 0x5e, - 0x0c, 0x4d, 0xed, 0x72, 0x68, 0x6a, 0xbf, 0x87, 0xa6, 0xf6, 0x6d, 0x64, 0x56, 0x2e, 0x47, 0x66, - 0xe5, 0xd7, 0xc8, 0xac, 0x7c, 0x78, 0x1e, 0x46, 0xfc, 0xb4, 0xd7, 0xb2, 0x03, 0x1a, 0x3b, 0x1c, - 0x27, 0x5d, 0x82, 0x79, 0x9f, 0x26, 0x1d, 0xf1, 0x7c, 0x10, 0xd0, 0x04, 0x3b, 0xe7, 0xd3, 0xdf, - 0x15, 0x3e, 0xe8, 0x62, 0xd6, 0x5a, 0x13, 0xff, 0xef, 0x4f, 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, - 0x50, 0xaf, 0x99, 0xd6, 0x7d, 0x06, 0x00, 0x00, + proto.RegisterFile("osmosis/tokenfactory/v1beta1/tx.proto", fileDescriptor_283b6c9a90a846b4) +} + +var fileDescriptor_283b6c9a90a846b4 = []byte{ + // 876 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x56, 0x4f, 0x6f, 0xdc, 0x44, + 0x14, 0x8f, 0xdb, 0xb0, 0x24, 0xd3, 0xa6, 0x49, 0x9c, 0xd0, 0x6c, 0x4c, 0x6a, 0x57, 0x23, 0x8a, + 0x28, 0x22, 0xb6, 0xb6, 0xd0, 0x4a, 0xf4, 0x44, 0x5d, 0x14, 0x71, 0x60, 0x05, 0x72, 0xc3, 0x05, + 0x55, 0x5a, 0xcd, 0xee, 0x4e, 0x1c, 0x2b, 0xf5, 0xcc, 0x32, 0x33, 0xdb, 0xed, 0xde, 0x10, 0x9f, + 0x80, 0x03, 0x42, 0xe2, 0xc0, 0x07, 0xe0, 0xc6, 0x81, 0x0f, 0xc0, 0x09, 0xf5, 0x58, 0x71, 0xe2, + 0x64, 0xa1, 0xe4, 0xc0, 0xdd, 0x9f, 0x00, 0x79, 0x66, 0xfc, 0x77, 0xab, 0xec, 0xee, 0xa9, 0xa7, + 0xac, 0xfd, 0x7e, 0xbf, 0xdf, 0xbc, 0xdf, 0x7b, 0x6f, 0x5e, 0x0c, 0xee, 0x50, 0x1e, 0x53, 0x1e, + 0x71, 0x4f, 0xd0, 0x33, 0x4c, 0x4e, 0xd0, 0x40, 0x50, 0x36, 0xf5, 0x9e, 0x77, 0xfa, 0x58, 0xa0, + 0x8e, 0x27, 0x5e, 0xb8, 0x23, 0x46, 0x05, 0x35, 0x0f, 0x34, 0xcc, 0xad, 0xc2, 0x5c, 0x0d, 0xb3, + 0x76, 0x43, 0x1a, 0x52, 0x09, 0xf4, 0xb2, 0x5f, 0x8a, 0x63, 0xd9, 0x03, 0x49, 0xf2, 0xfa, 0x88, + 0xe3, 0x42, 0x71, 0x40, 0x23, 0x32, 0x13, 0x27, 0x67, 0x45, 0x3c, 0x7b, 0xd0, 0xf1, 0xbb, 0x97, + 0xa6, 0x36, 0x42, 0x0c, 0xc5, 0x5c, 0x43, 0xf7, 0xb4, 0x54, 0xcc, 0x43, 0xef, 0x79, 0x27, 0xfb, + 0xa3, 0x03, 0xfb, 0x2a, 0xd0, 0x53, 0xc9, 0xa9, 0x07, 0x15, 0x82, 0xcf, 0xc0, 0x8d, 0x2e, 0x0f, + 0x1f, 0x33, 0x8c, 0x04, 0xfe, 0x1c, 0x13, 0x1a, 0x9b, 0x77, 0x41, 0x8b, 0x63, 0x32, 0xc4, 0xac, + 0x6d, 0xdc, 0x36, 0x3e, 0x58, 0xf7, 0xb7, 0xd3, 0xc4, 0xd9, 0x98, 0xa2, 0xf8, 0xd9, 0x43, 0xa8, + 0xde, 0xc3, 0x40, 0x03, 0x4c, 0x0f, 0xac, 0xf1, 0x71, 0x7f, 0x98, 0xd1, 0xda, 0x57, 0x24, 0x78, + 0x27, 0x4d, 0x9c, 0x4d, 0x0d, 0xd6, 0x11, 0x18, 0x14, 0x20, 0xf8, 0x14, 0xdc, 0xac, 0x9f, 0x16, + 0x60, 0x3e, 0xa2, 0x84, 0x63, 0xd3, 0x07, 0x9b, 0x04, 0x4f, 0x7a, 0xd2, 0x64, 0x4f, 0x29, 0xaa, + 0xe3, 0xad, 0x34, 0x71, 0x6e, 0x2a, 0xc5, 0x06, 0x00, 0x06, 0x1b, 0x04, 0x4f, 0x8e, 0xb3, 0x17, + 0x52, 0x0b, 0xfe, 0x69, 0x80, 0xb7, 0xbb, 0x3c, 0xec, 0x46, 0x44, 0x2c, 0xe3, 0xe2, 0x0b, 0xd0, + 0x42, 0x31, 0x1d, 0x13, 0x21, 0x3d, 0x5c, 0xbb, 0xb7, 0xef, 0xea, 0x0a, 0x65, 0x2d, 0xcb, 0xbb, + 0xeb, 0x3e, 0xa6, 0x11, 0xf1, 0xdf, 0x79, 0x99, 0x38, 0x2b, 0xa5, 0x92, 0xa2, 0xc1, 0x40, 0xf3, + 0xcd, 0xcf, 0xc0, 0x46, 0x1c, 0x11, 0x71, 0x4c, 0x1f, 0x0d, 0x87, 0x0c, 0x73, 0xde, 0xbe, 0xda, + 0xb4, 0x90, 0x85, 0x7b, 0x82, 0xf6, 0x90, 0x02, 0xc0, 0xa0, 0x4e, 0x80, 0xdb, 0x60, 0x53, 0x3b, + 0xc8, 0x2b, 0x03, 0xff, 0x52, 0xae, 0xfc, 0x31, 0x23, 0x6f, 0xc6, 0xd5, 0x11, 0xd8, 0xec, 0x8f, + 0x19, 0x39, 0x62, 0x34, 0xae, 0xfb, 0x3a, 0x48, 0x13, 0xa7, 0xad, 0x38, 0x19, 0xa0, 0x77, 0xc2, + 0x68, 0x5c, 0x3a, 0x6b, 0x92, 0xb4, 0xb7, 0xcc, 0x47, 0xe1, 0xed, 0x67, 0x43, 0x8d, 0xdf, 0x29, + 0x22, 0x21, 0x7e, 0x34, 0x8c, 0xa3, 0xa5, 0x2c, 0xbe, 0x0f, 0xde, 0xaa, 0xce, 0xde, 0x56, 0x9a, + 0x38, 0xd7, 0x15, 0x52, 0xcf, 0x87, 0x0a, 0x9b, 0x1d, 0xb0, 0x9e, 0x8d, 0x0e, 0xca, 0xf4, 0x75, + 0xea, 0xbb, 0x69, 0xe2, 0x6c, 0x95, 0x53, 0x25, 0x43, 0x30, 0x58, 0x23, 0x78, 0x22, 0xb3, 0x80, + 0x6d, 0x35, 0xa8, 0x65, 0x5e, 0x45, 0xca, 0x3f, 0x19, 0x60, 0xa7, 0xcb, 0xc3, 0x27, 0x58, 0xc8, + 0xa1, 0xeb, 0x62, 0x81, 0x86, 0x48, 0xa0, 0x65, 0xf2, 0x0e, 0xc0, 0x5a, 0xac, 0x69, 0xba, 0x39, + 0xb7, 0xca, 0xe6, 0x90, 0xb3, 0xa2, 0x39, 0xb9, 0xb6, 0xbf, 0xa7, 0x1b, 0xa4, 0x6f, 0x56, 0x4e, + 0x86, 0x41, 0xa1, 0x03, 0x6f, 0x81, 0x77, 0x5f, 0x93, 0x55, 0x91, 0xf5, 0x6f, 0x57, 0xc0, 0x56, + 0x97, 0x87, 0x47, 0x94, 0x0d, 0xf0, 0x31, 0x43, 0x84, 0x9f, 0x60, 0xf6, 0x66, 0xa6, 0x29, 0x00, + 0x3b, 0x42, 0x27, 0x30, 0x3b, 0x51, 0xb7, 0xd3, 0xc4, 0x39, 0x50, 0xbc, 0x1c, 0xd4, 0x98, 0xaa, + 0xd7, 0x91, 0xcd, 0x2f, 0xc1, 0x76, 0xfe, 0xba, 0xbc, 0x7b, 0xab, 0x52, 0xd1, 0x4e, 0x13, 0xc7, + 0x6a, 0x28, 0x56, 0xef, 0xdf, 0x2c, 0x11, 0x5a, 0xa0, 0xdd, 0x2c, 0x55, 0x51, 0xc7, 0x5f, 0x0d, + 0x39, 0xc4, 0xdf, 0x8c, 0x86, 0x48, 0xe0, 0xaf, 0xe5, 0xf2, 0x35, 0x1f, 0x80, 0x75, 0x34, 0x16, + 0xa7, 0x94, 0x45, 0x62, 0xaa, 0x2b, 0xd9, 0xfe, 0xfb, 0x8f, 0xc3, 0x5d, 0x5d, 0x21, 0x2d, 0xfb, + 0x44, 0xb0, 0x88, 0x84, 0x41, 0x09, 0x35, 0x7d, 0xd0, 0x52, 0xeb, 0x5b, 0xd7, 0xf4, 0x3d, 0xf7, + 0xb2, 0x7f, 0x2f, 0xae, 0x3a, 0xcd, 0x5f, 0xcd, 0xca, 0x1b, 0x68, 0xe6, 0xc3, 0x1b, 0x3f, 0xfc, + 0xf7, 0xfb, 0x87, 0xa5, 0x26, 0xdc, 0x07, 0x7b, 0x8d, 0xf4, 0xf2, 0xd4, 0xef, 0xfd, 0xd2, 0x02, + 0x57, 0xbb, 0x3c, 0x34, 0xbf, 0x03, 0xd7, 0xaa, 0xeb, 0xfe, 0xa3, 0xcb, 0x4f, 0xad, 0xaf, 0x6b, + 0xeb, 0x93, 0x65, 0xd0, 0xc5, 0x72, 0x7f, 0x0a, 0x56, 0xe5, 0x52, 0xbe, 0x33, 0x97, 0x9d, 0xc1, + 0xac, 0xc3, 0x85, 0x60, 0x55, 0x75, 0xb9, 0x1c, 0xe7, 0xab, 0x67, 0xb0, 0x05, 0xd4, 0xab, 0x2b, + 0x4a, 0x96, 0xab, 0xb2, 0x9e, 0x16, 0x28, 0x57, 0x89, 0x5e, 0xa4, 0x5c, 0xb3, 0x2b, 0xc6, 0xfc, + 0xde, 0x00, 0x5b, 0x33, 0xfb, 0xa5, 0x33, 0x57, 0xaa, 0x49, 0xb1, 0x3e, 0x5d, 0x9a, 0x52, 0xa4, + 0x30, 0x01, 0x1b, 0xf5, 0x5d, 0xe1, 0xce, 0xd5, 0xaa, 0xe1, 0xad, 0x07, 0xcb, 0xe1, 0x8b, 0x83, + 0x05, 0xb8, 0x5e, 0xbb, 0x5c, 0xf3, 0xbb, 0x55, 0x85, 0x5b, 0xf7, 0x97, 0x82, 0xe7, 0xa7, 0xfa, + 0x5f, 0xbd, 0x3c, 0xb7, 0x8d, 0x57, 0xe7, 0xb6, 0xf1, 0xef, 0xb9, 0x6d, 0xfc, 0x78, 0x61, 0xaf, + 0xbc, 0xba, 0xb0, 0x57, 0xfe, 0xb9, 0xb0, 0x57, 0xbe, 0xbd, 0x1f, 0x46, 0xe2, 0x74, 0xdc, 0x77, + 0x07, 0x34, 0xf6, 0x04, 0x66, 0x23, 0x82, 0xc5, 0x84, 0xb2, 0x33, 0xf9, 0xfb, 0x70, 0x40, 0x19, + 0xf6, 0x5e, 0xd4, 0xbf, 0xcc, 0xc4, 0x74, 0x84, 0x79, 0xbf, 0x25, 0xbf, 0xae, 0x3e, 0xfe, 0x3f, + 0x00, 0x00, 0xff, 0xff, 0x41, 0x67, 0x99, 0xb2, 0x59, 0x0a, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. -var ( - _ context.Context - _ grpc.ClientConn -) +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. @@ -636,21 +823,17 @@ const _ = grpc.SupportPackageIsVersion4 // // 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 { - // CreateDenom Creates a denom of factory/{creator address}/{subdenom} given - // the denom creator address and the subdenom. Subdenoms can contain - // [a-zA-Z0-9./]. CreateDenom(ctx context.Context, in *MsgCreateDenom, opts ...grpc.CallOption) (*MsgCreateDenomResponse, error) - // Mint is message type that represents a request to mint a new denom. Mint(ctx context.Context, in *MsgMint, opts ...grpc.CallOption) (*MsgMintResponse, error) - // Burn message type that represents a request to burn (i.e., destroy) a - // denom. Burn(ctx context.Context, in *MsgBurn, opts ...grpc.CallOption) (*MsgBurnResponse, error) - // A message type that represents a request to change the administrator of the - // denom. ChangeAdmin(ctx context.Context, in *MsgChangeAdmin, opts ...grpc.CallOption) (*MsgChangeAdminResponse, error) - // A message type that represents a request to set metadata for a - // denomination. SetDenomMetadata(ctx context.Context, in *MsgSetDenomMetadata, opts ...grpc.CallOption) (*MsgSetDenomMetadataResponse, error) + ForceTransfer(ctx context.Context, in *MsgForceTransfer, opts ...grpc.CallOption) (*MsgForceTransferResponse, error) + // UpdateParams defines a governance operation for updating the x/mint module + // parameters. The authority is hard-coded to the x/gov module account. + // + // Since: cosmos-sdk 0.47 + UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) } type msgClient struct { @@ -706,47 +889,64 @@ func (c *msgClient) SetDenomMetadata(ctx context.Context, in *MsgSetDenomMetadat return out, nil } +func (c *msgClient) ForceTransfer(ctx context.Context, in *MsgForceTransfer, opts ...grpc.CallOption) (*MsgForceTransferResponse, error) { + out := new(MsgForceTransferResponse) + err := c.cc.Invoke(ctx, "/osmosis.tokenfactory.v1beta1.Msg/ForceTransfer", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { + out := new(MsgUpdateParamsResponse) + err := c.cc.Invoke(ctx, "/osmosis.tokenfactory.v1beta1.Msg/UpdateParams", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // MsgServer is the server API for Msg service. type MsgServer interface { - // CreateDenom Creates a denom of factory/{creator address}/{subdenom} given - // the denom creator address and the subdenom. Subdenoms can contain - // [a-zA-Z0-9./]. CreateDenom(context.Context, *MsgCreateDenom) (*MsgCreateDenomResponse, error) - // Mint is message type that represents a request to mint a new denom. Mint(context.Context, *MsgMint) (*MsgMintResponse, error) - // Burn message type that represents a request to burn (i.e., destroy) a - // denom. Burn(context.Context, *MsgBurn) (*MsgBurnResponse, error) - // A message type that represents a request to change the administrator of the - // denom. ChangeAdmin(context.Context, *MsgChangeAdmin) (*MsgChangeAdminResponse, error) - // A message type that represents a request to set metadata for a - // denomination. SetDenomMetadata(context.Context, *MsgSetDenomMetadata) (*MsgSetDenomMetadataResponse, error) + ForceTransfer(context.Context, *MsgForceTransfer) (*MsgForceTransferResponse, error) + // UpdateParams defines a governance operation for updating the x/mint module + // parameters. The authority is hard-coded to the x/gov module account. + // + // Since: cosmos-sdk 0.47 + UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) } // UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct{} +type UnimplementedMsgServer struct { +} func (*UnimplementedMsgServer) CreateDenom(ctx context.Context, req *MsgCreateDenom) (*MsgCreateDenomResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method CreateDenom not implemented") } - func (*UnimplementedMsgServer) Mint(ctx context.Context, req *MsgMint) (*MsgMintResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Mint not implemented") } - func (*UnimplementedMsgServer) Burn(ctx context.Context, req *MsgBurn) (*MsgBurnResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Burn not implemented") } - func (*UnimplementedMsgServer) ChangeAdmin(ctx context.Context, req *MsgChangeAdmin) (*MsgChangeAdminResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ChangeAdmin not implemented") } - func (*UnimplementedMsgServer) SetDenomMetadata(ctx context.Context, req *MsgSetDenomMetadata) (*MsgSetDenomMetadataResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method SetDenomMetadata not implemented") } +func (*UnimplementedMsgServer) ForceTransfer(ctx context.Context, req *MsgForceTransfer) (*MsgForceTransferResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ForceTransfer not implemented") +} +func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") +} func RegisterMsgServer(s grpc1.Server, srv MsgServer) { s.RegisterService(&_Msg_serviceDesc, srv) @@ -842,6 +1042,42 @@ func _Msg_SetDenomMetadata_Handler(srv interface{}, ctx context.Context, dec fun return interceptor(ctx, in, info, handler) } +func _Msg_ForceTransfer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgForceTransfer) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).ForceTransfer(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/osmosis.tokenfactory.v1beta1.Msg/ForceTransfer", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).ForceTransfer(ctx, req.(*MsgForceTransfer)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgUpdateParams) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).UpdateParams(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/osmosis.tokenfactory.v1beta1.Msg/UpdateParams", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) + } + return interceptor(ctx, in, info, handler) +} + var _Msg_serviceDesc = grpc.ServiceDesc{ ServiceName: "osmosis.tokenfactory.v1beta1.Msg", HandlerType: (*MsgServer)(nil), @@ -866,9 +1102,17 @@ var _Msg_serviceDesc = grpc.ServiceDesc{ MethodName: "SetDenomMetadata", Handler: _Msg_SetDenomMetadata_Handler, }, + { + MethodName: "ForceTransfer", + Handler: _Msg_ForceTransfer_Handler, + }, + { + MethodName: "UpdateParams", + Handler: _Msg_UpdateParams_Handler, + }, }, Streams: []grpc.StreamDesc{}, - Metadata: "cosmwasm/tokenfactory/v1beta1/tx.proto", + Metadata: "osmosis/tokenfactory/v1beta1/tx.proto", } func (m *MsgCreateDenom) Marshal() (dAtA []byte, err error) { @@ -958,6 +1202,13 @@ func (m *MsgMint) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.MintToAddress) > 0 { + i -= len(m.MintToAddress) + copy(dAtA[i:], m.MintToAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.MintToAddress))) + i-- + dAtA[i] = 0x1a + } { size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) if err != nil { @@ -1021,6 +1272,13 @@ func (m *MsgBurn) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.BurnFromAddress) > 0 { + i -= len(m.BurnFromAddress) + copy(dAtA[i:], m.BurnFromAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.BurnFromAddress))) + i-- + dAtA[i] = 0x1a + } { size, err := m.Amount.MarshalToSizedBuffer(dAtA[:i]) if err != nil { @@ -1194,18 +1452,157 @@ func (m *MsgSetDenomMetadataResponse) MarshalToSizedBuffer(dAtA []byte) (int, er 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++ +func (m *MsgForceTransfer) 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 *MsgForceTransfer) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgForceTransfer) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.TransferToAddress) > 0 { + i -= len(m.TransferToAddress) + copy(dAtA[i:], m.TransferToAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.TransferToAddress))) + i-- + dAtA[i] = 0x22 + } + if len(m.TransferFromAddress) > 0 { + i -= len(m.TransferFromAddress) + copy(dAtA[i:], m.TransferFromAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.TransferFromAddress))) + i-- + dAtA[i] = 0x1a + } + { + size, err := m.Amount.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 *MsgForceTransferResponse) 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 *MsgForceTransferResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgForceTransferResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgUpdateParams) 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 *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParams) 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 = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Authority) > 0 { + i -= len(m.Authority) + copy(dAtA[i:], m.Authority) + i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateParamsResponse) 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 *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ } dAtA[offset] = uint8(v) return base } - func (m *MsgCreateDenom) Size() (n int) { if m == nil { return 0 @@ -1248,6 +1645,10 @@ func (m *MsgMint) Size() (n int) { } l = m.Amount.Size() n += 1 + l + sovTx(uint64(l)) + l = len(m.MintToAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } return n } @@ -1272,6 +1673,10 @@ func (m *MsgBurn) Size() (n int) { } l = m.Amount.Size() n += 1 + l + sovTx(uint64(l)) + l = len(m.BurnFromAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } return n } @@ -1338,14 +1743,68 @@ func (m *MsgSetDenomMetadataResponse) Size() (n int) { return n } +func (m *MsgForceTransfer) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Amount.Size() + n += 1 + l + sovTx(uint64(l)) + l = len(m.TransferFromAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.TransferToAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgForceTransferResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgUpdateParams) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Authority) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = m.Params.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgUpdateParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + func sovTx(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } - func sozTx(x uint64) (n int) { return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } - func (m *MsgCreateDenom) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1460,7 +1919,6 @@ func (m *MsgCreateDenom) Unmarshal(dAtA []byte) error { } return nil } - func (m *MsgCreateDenomResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1543,7 +2001,6 @@ func (m *MsgCreateDenomResponse) Unmarshal(dAtA []byte) error { } return nil } - func (m *MsgMint) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1638,6 +2095,38 @@ func (m *MsgMint) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MintToAddress", 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.MintToAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -1659,7 +2148,6 @@ func (m *MsgMint) Unmarshal(dAtA []byte) error { } return nil } - func (m *MsgMintResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1710,7 +2198,6 @@ func (m *MsgMintResponse) Unmarshal(dAtA []byte) error { } return nil } - func (m *MsgBurn) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1805,6 +2292,38 @@ func (m *MsgBurn) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field BurnFromAddress", 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.BurnFromAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTx(dAtA[iNdEx:]) @@ -1826,7 +2345,6 @@ func (m *MsgBurn) Unmarshal(dAtA []byte) error { } return nil } - func (m *MsgBurnResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1877,7 +2395,6 @@ func (m *MsgBurnResponse) Unmarshal(dAtA []byte) error { } return nil } - func (m *MsgChangeAdmin) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -2024,7 +2541,6 @@ func (m *MsgChangeAdmin) Unmarshal(dAtA []byte) error { } return nil } - func (m *MsgChangeAdminResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -2075,7 +2591,6 @@ func (m *MsgChangeAdminResponse) Unmarshal(dAtA []byte) error { } return nil } - func (m *MsgSetDenomMetadata) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -2191,7 +2706,6 @@ func (m *MsgSetDenomMetadata) Unmarshal(dAtA []byte) error { } return nil } - func (m *MsgSetDenomMetadataResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -2242,7 +2756,400 @@ func (m *MsgSetDenomMetadataResponse) Unmarshal(dAtA []byte) error { } return nil } - +func (m *MsgForceTransfer) 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: MsgForceTransfer: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgForceTransfer: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Amount", wireType) + } + var 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.Amount.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TransferFromAddress", 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.TransferFromAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field TransferToAddress", 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.TransferToAddress = 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 *MsgForceTransferResponse) 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: MsgForceTransferResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgForceTransferResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdateParams) 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: MsgUpdateParams: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Authority", 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.Authority = 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 err := m.Params.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 *MsgUpdateParamsResponse) 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: MsgUpdateParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipTx(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/wasm/Governance.md b/x/wasm/Governance.md deleted file mode 100644 index 8760412..0000000 --- a/x/wasm/Governance.md +++ /dev/null @@ -1,205 +0,0 @@ -# Governance - -This document gives an overview of how the various governance -proposals interact with the CosmWasm contract lifecycle. It is -a high-level, technical introduction meant to provide context before -looking into the code, or constructing proposals. - -## Proposal Types -We have added 9 new wasm specific proposal types that cover the contract's live cycle and authorization: - -* `StoreCodeProposal` - upload a wasm binary -* `InstantiateContractProposal` - instantiate a wasm contract -* `MigrateContractProposal` - migrate a wasm contract to a new code version -* `SudoContractProposal` - call into the protected `sudo` entry point of a contract -* `ExecuteContractProposal` - execute a wasm contract as an arbitrary user -* `UpdateAdminProposal` - set a new admin for a contract -* `ClearAdminProposal` - clear admin for a contract to prevent further migrations -* `PinCodes` - pin the given code ids in cache. This trades memory for reduced startup time and lowers gas cost -* `UnpinCodes` - unpin the given code ids from the cache. This frees up memory and returns to standard speed and gas cost -* `UpdateInstantiateConfigProposal` - update instantiate permissions to a list of given code ids. -* `StoreAndInstantiateContractProposal` - upload and instantiate a wasm contract. - -For details see the proposal type [implementation](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/proposal.go) - -### Unit tests -[Proposal type validations](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/proposal_test.go) - -## Proposal Handler -The [wasmd proposal_handler](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/keeper/proposal_handler.go) implements the `gov.Handler` function -and executes the wasmd proposal types after a successful tally. - -The proposal handler uses a [`GovAuthorizationPolicy`](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/keeper/authz_policy.go#L29) to bypass the existing contract's authorization policy. - -### Tests -* [Integration: Submit and execute proposal](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/keeper/proposal_integration_test.go) - -## Gov Integration -The wasmd proposal handler can be added to the gov router in the [abci app](https://github.com/terpnetwork/terp-core/blob/master/app/app.go#L306) -to receive proposal execution calls. -```go -govRouter.AddRoute(wasm.RouterKey, wasm.NewWasmProposalHandler(app.wasmKeeper, enabledProposals)) -``` - -## Wasmd Authorization Settings - -Settings via sdk `params` module: -- `code_upload_access` - who can upload a wasm binary: `Nobody`, `Everybody`, `OnlyAddress` -- `instantiate_default_permission` - platform default, who can instantiate a wasm binary when the code owner has not set it - -See [params.go](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/params.go) - -### Init Params Via Genesis - -```json - "wasm": { - "params": { - "code_upload_access": { - "permission": "Everybody" - }, - "instantiate_default_permission": "Everybody" - } - }, -``` - -The values can be updated via gov proposal implemented in the `params` module. - -### Update Params Via [ParamChangeProposal](https://github.com/cosmos/cosmos-sdk/blob/v0.45.3/proto/cosmos/params/v1beta1/params.proto#L10) -Example to submit a parameter change gov proposal: -```sh -wasmd tx gov submit-proposal param-change --from validator --chain-id=testing -b block -``` -#### Content examples -* Disable wasm code uploads -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "uploadAccess", - "value": { - "permission": "Nobody" - } - } - ], - "deposit": "" -} -``` -* Allow wasm code uploads for everybody -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "uploadAccess", - "value": { - "permission": "Everybody" - } - } - ], - "deposit": "" -} -``` - -* Restrict code uploads to a single address -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "uploadAccess", - "value": { - "permission": "OnlyAddress", - "address": "cosmos1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0fr2sh" - } - } - ], - "deposit": "" -} -``` -* Set chain **default** instantiation settings to nobody -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "instantiateAccess", - "value": "Nobody" - } - ], - "deposit": "" -} -``` -* Set chain **default** instantiation settings to everybody -```json -{ - "title": "Foo", - "description": "Bar", - "changes": [ - { - "subspace": "wasm", - "key": "instantiateAccess", - "value": "Everybody" - } - ], - "deposit": "" -} -``` - -### Enable gov proposals at **compile time**. -As gov proposals bypass the existing authorization policy they are disabled and require to be enabled at compile time. -``` --X github.com/terpnetwork/terp-core/app.ProposalsEnabled=true - enable all x/wasm governance proposals (default false) --X github.com/terpnetwork/terp-core/app.EnableSpecificProposals=MigrateContract,UpdateAdmin,ClearAdmin - enable a subset of the x/wasm governance proposal types (overrides ProposalsEnabled) -``` - -The `ParamChangeProposal` is always enabled. - -### Tests -* [params validation unit tests](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/params_test.go) -* [genesis validation tests](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/genesis_test.go) -* [policy integration tests](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/keeper/keeper_test.go) - -## CLI - -```shell script - wasmd tx gov submit-proposal [command] - -Available Commands: - wasm-store Submit a wasm binary proposal - instantiate-contract Submit an instantiate wasm contract proposal - migrate-contract Submit a migrate wasm contract to a new code version proposal - set-contract-admin Submit a new admin for a contract proposal - clear-contract-admin Submit a clear admin for a contract to prevent further migrations proposal -... -``` -## Rest -New [`ProposalHandlers`](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/client/proposal_handler.go) - -* Integration -```shell script -gov.NewAppModuleBasic(append(wasmclient.ProposalHandlers, paramsclient.ProposalHandler, distr.ProposalHandler, upgradeclient.ProposalHandler)...), -``` -In [abci app](https://github.com/terpnetwork/terp-core/blob/master/app/app.go#L109) - -### Tests -* [Rest Unit tests](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/client/proposal_handler_test.go) -* [Rest smoke LCD test](https://github.com/terpnetwork/terp-core/blob/master/lcd_test/wasm_test.go) - - - -## Pull requests -* https://github.com/terpnetwork/terp-core/pull/190 -* https://github.com/terpnetwork/terp-core/pull/186 -* https://github.com/terpnetwork/terp-core/pull/183 -* https://github.com/terpnetwork/terp-core/pull/180 -* https://github.com/terpnetwork/terp-core/pull/179 -* https://github.com/terpnetwork/terp-core/pull/173 diff --git a/x/wasm/IBC.md b/x/wasm/IBC.md deleted file mode 100644 index c3cd0a0..0000000 --- a/x/wasm/IBC.md +++ /dev/null @@ -1,137 +0,0 @@ -# IBC specification - -This documents how CosmWasm contracts are expected to interact with IBC. - -## General Concepts - -**IBC Enabled** - when instantiating a contract, we detect if it supports IBC messages. - We require "feature flags" in the contract/vm handshake to ensure compatibility - for features like staking or chain-specific extensions. IBC functionality will require - another "feature flag", and the list of "enabled features" can be returned to the `x/wasm` - module to control conditional IBC behavior. - - If this feature is enabled, it is considered "IBC Enabled", and that info will - be stored in the ContractInfo. (For mock, we assume all contracts are IBC enabled) - -Also, please read the [IBC Docs](https://docs.cosmos.network/master/ibc/overview.html) -for detailed descriptions of the terms *Port*, *Client*, *Connection*, -and *Channel* - -## Overview - -We use "One Port per Contract", which is the most straight-forward mapping, treating each contract -like a module. It does lead to very long portIDs however. Pay special attention to both the Channel establishment -(which should be compatible with standard ICS20 modules without changes on their part), as well -as how contracts can properly identify their counterparty. - -(We considered on port for the `x/wasm` module and multiplexing on it, but [dismissed that idea](#rejected-ideas)) - -* Upon `Instantiate`, if a contract is *IBC Enabled*, we dynamically - bind a port for this contract. The port name is `wasm.`, - eg. `wasm.cosmos1hmdudppzceg27qsuq707tjg8rkgj7g5hnvnw29` -* If a *Channel* is being established with a registered `wasm.xyz` port, - the `x/wasm.Keeper` will handle this and call into the appropriate - contract to determine supported protocol versions during the - [`ChanOpenTry` and `ChanOpenAck` phases](https://docs.cosmos.network/master/ibc/overview.html#channels). - (See [Channel Handshake Version Negotiation](https://docs.cosmos.network/master/ibc/custom.html#channel-handshake-version-negotiation)) -* Both the *Port* and the *Channel* are fully owned by one contract. -* `x/wasm` will allow both *ORDERED* and *UNORDERED* channels and pass that mode - down to the contract in `OnChanOpenTry`, so the contract can decide if it accepts - the mode. We will recommend the contract developers stick with *ORDERED* channels - for custom protocols unless they can reason about async packet timing. -* When sending a packet, the CosmWasm contract must specify the local *ChannelID*. - As there is a unique *PortID* per contract, that is filled in by `x/wasm` - to produce the globally unique `(PortID, ChannelID)` -* When receiving a Packet (or Ack or Timeout), the contracts receives the local - *ChannelID* it came from, as well as the packet that was sent by the counterparty. -* When receiving an Ack or Timeout packet, the contract also receives the - original packet that it sent earlier. -* We do not support multihop packets in this model (they are rejected by `x/wasm`). - They are currently not fully specified nor implemented in IBC 1.0, so let us - simplify our model until this is well established - -## Workflow - -Establishing *Clients* and *Connections* is out of the scope of this -module and must be created by the same means as for `ibc-transfer` -(via the [go cli](https://github.com/cosmos/relayer) or better [ts-relayer](https://github.com/confio/ts-relayer)). -`x/wasm` will bind a unique *Port* for each "IBC Enabled" contract. - -For mocks, all the Packet Handling and Channel Lifecycle Hooks are routed -to some Golang stub handler, but containing the contract address, so we -can perform contract-specific actions for each packet. In a real setting, -we route to the contract that owns the port/channel and call one of it's various -entry points. - -Please refer to the CosmWasm repo for all -[details on the IBC API from the point of view of a CosmWasm contract](https://github.com/CosmWasm/cosmwasm/blob/main/IBC.md). - -## Future Ideas - -Here are some ideas we may add in the future - -### Dynamic Ports and Channels - -* multiple ports per contract -* elastic ports that can be assigned to different contracts -* transfer of channels to another contract - -This is inspired by the Agoric design, but also adds considerable complexity to both the `x/wasm` -implementation as well as the correctness reasoning of any given contract. This will not be -available in the first version of our "IBC Enabled contracts", but we can consider it for later, -if there are concrete user cases that would significantly benefit from this added complexity. - -### Add multihop support - -Once the ICS and IBC specs fully establish how multihop packets work, we should add support for that. -Both on setting up the routes with OpenChannel, as well as acting as an intermediate relayer (if that is possible) - -## Rejected Ideas - -### One Port per Module - -We decided on "one port per contract", especially after the IBC team raised -the max length on port names to allow `wasm-` to be a valid port. -Here are the arguments for "one port for x/wasm" vs "one port per contract". Here -was an alternate proposal: - -In this approach, the `x/wasm` module just binds one port to handle all -modules. This can be well defined name like `wasm`. Since we always -have `(ChannelID, PortID)` for routing messages, we can reuse one port -for all contracts as long as we have a clear way to map the `ChannelID` -to a specific contract when it is being established. - - -* On genesis we bind the port `wasm` for all communication with the `x/wasm` - module. -* The *Port* is fully owned by `x/wasm` -* Each *Channel* is fully owned by one contract. -* `x/wasm` only accepts *ORDERED Channels* for simplicity of contract - correctness. - -To clarify: - -* When a *Channel* is being established with port `wasm`, the - `x/wasm.Keeper` must be able to identify for which contract this - is destined. **how to do so**?? - * One idea: the channel name must be the contract address. This means - (`wasm`, `cosmos13d...`) will map to the given contract in the wasm module. - The problem with this is that if two contracts from chainA want to - connect to the same contracts on chainB, they will want to claim the - same *ChannelID* and *PortID*. Not sure how to differentiate multiple - parties in this way. - * Other ideas: have a special field we send on `OnChanOpenInit` that - specifies the destination contract, and allow any *ChannelID*. - However, looking at [`OnChanOpenInit` function signature](https://docs.cosmos.network/master/ibc/custom.html#implement-ibcmodule-interface-and-callbacks), - I don't see a place to put this extra info, without abusing the version field, - which is a [specified field](https://docs.cosmos.network/master/ibc/custom.html#channel-handshake-version-negotiation): - ``` - Versions must be strings but can implement any versioning structure. - If your application plans to have linear releases then semantic versioning is recommended. - ... - Valid version selection includes selecting a compatible version identifier with a subset - of features supported by your application for that version. - ... - ICS20 currently implements basic string matching with a - single supported version. - ``` \ No newline at end of file diff --git a/x/wasm/README.md b/x/wasm/README.md deleted file mode 100644 index cba9c5c..0000000 --- a/x/wasm/README.md +++ /dev/null @@ -1,219 +0,0 @@ -# Wasm Module - -This should be a brief overview of the functionality - -## Configuration - -You can add the following section to `config/app.toml`: - -```toml -[wasm] -# This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries -query_gas_limit = 300000 -# This defines the memory size for Wasm modules that we can keep cached to speed-up instantiation -# The value is in MiB not bytes -memory_cache_size = 300 -``` - -The values can also be set via CLI flags on with the `start` command: -```shell script ---wasm.memory_cache_size uint32 Sets the size in MiB (NOT bytes) of an in-memory cache for wasm modules. Set to 0 to disable. (default 100) ---wasm.query_gas_limit uint Set the max gas that can be spent on executing a query with a Wasm contract (default 3000000) -``` - -## Events - -A number of events are returned to allow good indexing of the transactions from smart contracts. - -Every call to Instantiate or Execute will be tagged with the info on the contract that was executed and who executed it. -It should look something like this (with different addresses). The module is always `wasm`, and `code_id` is only present -when Instantiating a contract, so you can subscribe to new instances, it is omitted on Execute. There is also an `action` tag -which is auto-added by the Cosmos SDK and has a value of either `store-code`, `instantiate` or `execute` depending on which message -was sent: - -```json -{ - "Type": "message", - "Attr": [ - { - "key": "module", - "value": "wasm" - }, - { - "key": "action", - "value": "instantiate" - }, - { - "key": "signer", - "value": "cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x" - }, - { - "key": "code_id", - "value": "1" - }, - { - "key": "_contract_address", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - } - ] -} -``` - -If any funds were transferred to the contract as part of the message, or if the contract released funds as part of it's executions, -it will receive the typical events associated with sending tokens from bank. In this case, we instantiate the contract and -provide a initial balance in the same `MsgInstantiateContract`. We see the following events in addition to the above one: - -```json -[ - { - "Type": "transfer", - "Attr": [ - { - "key": "recipient", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "sender", - "value": "cosmos1ffnqn02ft2psvyv4dyr56nnv6plllf9pm2kpmv" - }, - { - "key": "amount", - "value": "100000denom" - } - ] - } -] -``` - -Finally, the contract itself can emit a "custom event" on Execute only (not on Init). -There is one event per contract, so if one contract calls a second contract, you may receive -one event for the original contract and one for the re-invoked contract. All attributes from the contract are passed through verbatim, -and we add a `_contract_address` attribute that contains the actual contract that emitted that event. -Here is an example from the escrow contract successfully releasing funds to the destination address: - -```json -{ - "Type": "wasm", - "Attr": [ - { - "key": "_contract_address", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "action", - "value": "release" - }, - { - "key": "destination", - "value": "cosmos14k7v7ms4jxkk2etmg9gljxjm4ru3qjdugfsflq" - } - ] -} -``` - -### Pulling this all together - -We will invoke an escrow contract to release to the designated beneficiary. -The escrow was previously loaded with `100000denom` (from the above example). -In this transaction, we send `5000denom` along with the `MsgExecuteContract` -and the contract releases the entire funds (`105000denom`) to the beneficiary. - -We will see all the following events, where you should be able to reconstruct the actions -(remember there are two events for each transfer). We see (1) the initial transfer of funds -to the contract, (2) the contract custom event that it released funds (3) the transfer of funds -from the contract to the beneficiary and (4) the generic x/wasm event stating that the contract -was executed (which always appears, while 2 is optional and has information as reliable as the contract): - -```json -[ - { - "Type": "transfer", - "Attr": [ - { - "key": "recipient", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "sender", - "value": "cosmos1zm074khx32hqy20hlshlsd423n07pwlu9cpt37" - }, - { - "key": "amount", - "value": "5000denom" - } - ] - }, - { - "Type": "wasm", - "Attr": [ - { - "key": "_contract_address", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "action", - "value": "release" - }, - { - "key": "destination", - "value": "cosmos14k7v7ms4jxkk2etmg9gljxjm4ru3qjdugfsflq" - } - ] - }, - { - "Type": "transfer", - "Attr": [ - { - "key": "recipient", - "value": "cosmos14k7v7ms4jxkk2etmg9gljxjm4ru3qjdugfsflq" - }, - { - "key": "sender", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - }, - { - "key": "amount", - "value": "105000denom" - } - ] - }, - { - "Type": "message", - "Attr": [ - { - "key": "module", - "value": "wasm" - }, - { - "key": "action", - "value": "execute" - }, - { - "key": "signer", - "value": "cosmos1zm074khx32hqy20hlshlsd423n07pwlu9cpt37" - }, - { - "key": "_contract_address", - "value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - } - ] - } -] -``` - -A note on this format. This is what we return from our module. However, it seems to me that many events with the same `Type` -get merged together somewhere along the stack, so in this case, you *may* end up with one "transfer" event with the info for -both transfers. Double check when evaluating the event logs, I will document better with more experience, especially when I -find out the entire path for the events. - -## Messages - -TODO - -## CLI - -TODO - working, but not the nicest interface (json + bash = bleh). Use to upload, but I suggest to focus on frontend / js tooling - -## Rest - -TODO - main supported interface, under rapid change diff --git a/x/wasm/alias.go b/x/wasm/alias.go deleted file mode 100644 index 8f952e2..0000000 --- a/x/wasm/alias.go +++ /dev/null @@ -1,124 +0,0 @@ -// autogenerated code using github.com/rigelrozanski/multitool -// aliases generated for the following subdirectories: -// ALIASGEN: github.com/Cosmwasm/wasmd/x/wasm/types -// ALIASGEN: github.com/terpnetwork/terp-core/x/wasm/keeper -package wasm - -import ( - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - firstCodeID = 1 - ModuleName = types.ModuleName - StoreKey = types.StoreKey - TStoreKey = types.TStoreKey - QuerierRoute = types.QuerierRoute - RouterKey = types.RouterKey - WasmModuleEventType = types.WasmModuleEventType - AttributeKeyContractAddr = types.AttributeKeyContractAddr - ProposalTypeStoreCode = types.ProposalTypeStoreCode - ProposalTypeInstantiateContract = types.ProposalTypeInstantiateContract - ProposalTypeMigrateContract = types.ProposalTypeMigrateContract - ProposalTypeUpdateAdmin = types.ProposalTypeUpdateAdmin - ProposalTypeClearAdmin = types.ProposalTypeClearAdmin -) - -var ( - // functions aliases - RegisterCodec = types.RegisterLegacyAminoCodec - RegisterInterfaces = types.RegisterInterfaces - ValidateGenesis = types.ValidateGenesis - ConvertToProposals = types.ConvertToProposals - GetCodeKey = types.GetCodeKey - GetContractAddressKey = types.GetContractAddressKey - GetContractStorePrefixKey = types.GetContractStorePrefix - NewCodeInfo = types.NewCodeInfo - NewAbsoluteTxPosition = types.NewAbsoluteTxPosition - NewContractInfo = types.NewContractInfo - NewEnv = types.NewEnv - NewWasmCoins = types.NewWasmCoins - DefaultWasmConfig = types.DefaultWasmConfig - DefaultParams = types.DefaultParams - InitGenesis = keeper.InitGenesis - ExportGenesis = keeper.ExportGenesis - NewMessageHandler = keeper.NewDefaultMessageHandler - DefaultEncoders = keeper.DefaultEncoders - EncodeBankMsg = keeper.EncodeBankMsg - NoCustomMsg = keeper.NoCustomMsg - EncodeStakingMsg = keeper.EncodeStakingMsg - EncodeWasmMsg = keeper.EncodeWasmMsg - NewKeeper = keeper.NewKeeper - DefaultQueryPlugins = keeper.DefaultQueryPlugins - BankQuerier = keeper.BankQuerier - NoCustomQuerier = keeper.NoCustomQuerier - StakingQuerier = keeper.StakingQuerier - WasmQuerier = keeper.WasmQuerier - CreateTestInput = keeper.CreateTestInput - TestHandler = keeper.TestHandler - NewWasmProposalHandler = keeper.NewWasmProposalHandler //nolint:staticcheck - NewQuerier = keeper.Querier - ContractFromPortID = keeper.ContractFromPortID - WithWasmEngine = keeper.WithWasmEngine - NewCountTXDecorator = keeper.NewCountTXDecorator - - // variable aliases - ModuleCdc = types.ModuleCdc - DefaultCodespace = types.DefaultCodespace - ErrCreateFailed = types.ErrCreateFailed - ErrAccountExists = types.ErrAccountExists - ErrInstantiateFailed = types.ErrInstantiateFailed - ErrExecuteFailed = types.ErrExecuteFailed - ErrGasLimit = types.ErrGasLimit - ErrInvalidGenesis = types.ErrInvalidGenesis - ErrNotFound = types.ErrNotFound - ErrQueryFailed = types.ErrQueryFailed - ErrInvalidMsg = types.ErrInvalidMsg - KeyLastCodeID = types.KeyLastCodeID - KeyLastInstanceID = types.KeyLastInstanceID - CodeKeyPrefix = types.CodeKeyPrefix - ContractKeyPrefix = types.ContractKeyPrefix - ContractStorePrefix = types.ContractStorePrefix - EnableAllProposals = types.EnableAllProposals - DisableAllProposals = types.DisableAllProposals -) - -type ( - ProposalType = types.ProposalType - GenesisState = types.GenesisState - Code = types.Code - Contract = types.Contract - MsgStoreCode = types.MsgStoreCode - MsgStoreCodeResponse = types.MsgStoreCodeResponse - MsgInstantiateContract = types.MsgInstantiateContract - MsgInstantiateContract2 = types.MsgInstantiateContract2 - MsgInstantiateContractResponse = types.MsgInstantiateContractResponse - MsgExecuteContract = types.MsgExecuteContract - MsgExecuteContractResponse = types.MsgExecuteContractResponse - MsgMigrateContract = types.MsgMigrateContract - MsgMigrateContractResponse = types.MsgMigrateContractResponse - MsgUpdateAdmin = types.MsgUpdateAdmin - MsgUpdateAdminResponse = types.MsgUpdateAdminResponse - MsgClearAdmin = types.MsgClearAdmin - MsgWasmIBCCall = types.MsgIBCSend - MsgClearAdminResponse = types.MsgClearAdminResponse - MsgServer = types.MsgServer - Model = types.Model - CodeInfo = types.CodeInfo - ContractInfo = types.ContractInfo - CreatedAt = types.AbsoluteTxPosition - Config = types.WasmConfig - CodeInfoResponse = types.CodeInfoResponse - MessageHandler = keeper.SDKMessageHandler - BankEncoder = keeper.BankEncoder - CustomEncoder = keeper.CustomEncoder - StakingEncoder = keeper.StakingEncoder - WasmEncoder = keeper.WasmEncoder - MessageEncoders = keeper.MessageEncoders - Keeper = keeper.Keeper - QueryHandler = keeper.QueryHandler - CustomQuerier = keeper.CustomQuerier - QueryPlugins = keeper.QueryPlugins - Option = keeper.Option -) diff --git a/x/wasm/client/cli/new_tx.go b/x/wasm/client/cli/new_tx.go deleted file mode 100644 index 8ce605a..0000000 --- a/x/wasm/client/cli/new_tx.go +++ /dev/null @@ -1,160 +0,0 @@ -package cli - -import ( - "strconv" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/spf13/cobra" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// MigrateContractCmd will migrate a contract to a new code version -func MigrateContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "migrate [contract_addr_bech32] [new_code_id_int64] [json_encoded_migration_args]", - Short: "Migrate a wasm contract to a new code version", - Aliases: []string{"update", "mig", "m"}, - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg, err := parseMigrateContractArgs(args, clientCtx.GetFromAddress().String()) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return nil - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -func parseMigrateContractArgs(args []string, sender string) (types.MsgMigrateContract, error) { - // get the id of the code to instantiate - codeID, err := strconv.ParseUint(args[1], 10, 64) - if err != nil { - return types.MsgMigrateContract{}, errorsmod.Wrap(err, "code id") - } - - migrateMsg := args[2] - - msg := types.MsgMigrateContract{ - Sender: sender, - Contract: args[0], - CodeID: codeID, - Msg: []byte(migrateMsg), - } - return msg, nil -} - -// UpdateContractAdminCmd sets an new admin for a contract -func UpdateContractAdminCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "set-contract-admin [contract_addr_bech32] [new_admin_addr_bech32]", - Short: "Set new admin for a contract", - Aliases: []string{"new-admin", "admin", "set-adm", "sa"}, - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := parseUpdateContractAdminArgs(args, clientCtx.GetFromAddress().String()) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -func parseUpdateContractAdminArgs(args []string, sender string) types.MsgUpdateAdmin { - msg := types.MsgUpdateAdmin{ - Sender: sender, - Contract: args[0], - NewAdmin: args[1], - } - return msg -} - -// ClearContractAdminCmd clears an admin for a contract -func ClearContractAdminCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "clear-contract-admin [contract_addr_bech32]", - Short: "Clears admin for a contract to prevent further migrations", - Aliases: []string{"clear-admin", "clr-adm"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := types.MsgClearAdmin{ - Sender: clientCtx.GetFromAddress().String(), - Contract: args[0], - } - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -// UpdateInstantiateConfigCmd updates instantiate config for a smart contract. -func UpdateInstantiateConfigCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "update-instantiate-config [code_id_int64]", - Short: "Update instantiate config for a codeID", - Aliases: []string{"update-instantiate-config"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - codeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - perm, err := parseAccessConfigFlags(cmd.Flags()) - if err != nil { - return err - } - - msg := types.MsgUpdateInstantiateConfig{ - Sender: string(clientCtx.GetFromAddress()), - CodeID: codeID, - NewInstantiatePermission: perm, - } - if err = msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - - addInstantiatePermissionFlags(cmd) - flags.AddTxFlagsToCmd(cmd) - return cmd -} diff --git a/x/wasm/client/cli/query.go b/x/wasm/client/cli/query.go deleted file mode 100644 index 2971e1e..0000000 --- a/x/wasm/client/cli/query.go +++ /dev/null @@ -1,675 +0,0 @@ -package cli - -import ( - "context" - "encoding/base64" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "os" - "strconv" - - wasmvm "github.com/CosmWasm/wasmvm" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/spf13/cobra" - flag "github.com/spf13/pflag" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func GetQueryCmd() *cobra.Command { - queryCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Querying commands for the wasm module", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - SilenceUsage: true, - } - queryCmd.AddCommand( - GetCmdListCode(), - GetCmdListContractByCode(), - GetCmdQueryCode(), - GetCmdQueryCodeInfo(), - GetCmdGetContractInfo(), - GetCmdGetContractHistory(), - GetCmdGetContractState(), - GetCmdListPinnedCode(), - GetCmdLibVersion(), - GetCmdQueryParams(), - GetCmdBuildAddress(), - GetCmdListContractsByCreator(), - ) - return queryCmd -} - -// GetCmdLibVersion gets current libwasmvm version. -func GetCmdLibVersion() *cobra.Command { - cmd := &cobra.Command{ - Use: "libwasmvm-version", - Short: "Get libwasmvm version", - Long: "Get libwasmvm version", - Aliases: []string{"lib-version"}, - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - version, err := wasmvm.LibwasmvmVersion() - if err != nil { - return fmt.Errorf("error retrieving libwasmvm version: %w", err) - } - fmt.Println(version) - return nil - }, - SilenceUsage: true, - } - return cmd -} - -// GetCmdBuildAddress build a contract address -func GetCmdBuildAddress() *cobra.Command { - decoder := newArgDecoder(hex.DecodeString) - cmd := &cobra.Command{ - Use: "build-address [code-hash] [creator-address] [salt-hex-encoded] [json_encoded_init_args (required when set as fixed)]", - Short: "build contract address", - Aliases: []string{"address"}, - Args: cobra.RangeArgs(3, 4), - RunE: func(cmd *cobra.Command, args []string) error { - codeHash, err := hex.DecodeString(args[0]) - if err != nil { - return fmt.Errorf("code-hash: %s", err) - } - creator, err := sdk.AccAddressFromBech32(args[1]) - if err != nil { - return fmt.Errorf("creator: %s", err) - } - salt, err := hex.DecodeString(args[2]) - switch { - case err != nil: - return fmt.Errorf("salt: %s", err) - case len(salt) == 0: - return errors.New("empty salt") - } - - if len(args) == 3 { - cmd.Println(keeper.BuildContractAddressPredictable(codeHash, creator, salt, []byte{}).String()) - return nil - } - msg := types.RawContractMessage(args[3]) - if err := msg.ValidateBasic(); err != nil { - return fmt.Errorf("init message: %s", err) - } - cmd.Println(keeper.BuildContractAddressPredictable(codeHash, creator, salt, msg).String()) - return nil - }, - SilenceUsage: true, - } - decoder.RegisterFlags(cmd.PersistentFlags(), "salt") - return cmd -} - -// GetCmdListCode lists all wasm code uploaded -func GetCmdListCode() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-code", - Short: "List all wasm bytecode on the chain", - Long: "List all wasm bytecode on the chain", - Aliases: []string{"list-codes", "codes", "lco"}, - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Codes( - context.Background(), - &types.QueryCodesRequest{ - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "list codes") - return cmd -} - -// GetCmdListContractByCode lists all wasm code uploaded for given code id -func GetCmdListContractByCode() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-contract-by-code [code_id]", - Short: "List wasm all bytecode on the chain for given code id", - Long: "List wasm all bytecode on the chain for given code id", - Aliases: []string{"list-contracts-by-code", "list-contracts", "contracts", "lca"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - codeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - if codeID == 0 { - return errors.New("empty code id") - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.ContractsByCode( - context.Background(), - &types.QueryContractsByCodeRequest{ - CodeId: codeID, - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "list contracts by code") - return cmd -} - -// GetCmdQueryCode returns the bytecode for a given contract -func GetCmdQueryCode() *cobra.Command { - cmd := &cobra.Command{ - Use: "code [code_id] [output filename]", - Short: "Downloads wasm bytecode for given code id", - Long: "Downloads wasm bytecode for given code id", - Aliases: []string{"source-code", "source"}, - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - codeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Code( - context.Background(), - &types.QueryCodeRequest{ - CodeId: codeID, - }, - ) - if err != nil { - return err - } - if len(res.Data) == 0 { - return fmt.Errorf("contract not found") - } - - fmt.Printf("Downloading wasm code to %s\n", args[1]) - return os.WriteFile(args[1], res.Data, 0o600) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdQueryCodeInfo returns the code info for a given code id -func GetCmdQueryCodeInfo() *cobra.Command { - cmd := &cobra.Command{ - Use: "code-info [code_id]", - Short: "Prints out metadata of a code id", - Long: "Prints out metadata of a code id", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - codeID, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.Code( - context.Background(), - &types.QueryCodeRequest{ - CodeId: codeID, - }, - ) - if err != nil { - return err - } - if res.CodeInfoResponse == nil { - return fmt.Errorf("contract not found") - } - - return clientCtx.PrintProto(res.CodeInfoResponse) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdGetContractInfo gets details about a given contract -func GetCmdGetContractInfo() *cobra.Command { - cmd := &cobra.Command{ - Use: "contract [bech32_address]", - Short: "Prints out metadata of a contract given its address", - Long: "Prints out metadata of a contract given its address", - Aliases: []string{"meta", "c"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.ContractInfo( - context.Background(), - &types.QueryContractInfoRequest{ - Address: args[0], - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdGetContractState dumps full internal state of a given contract -func GetCmdGetContractState() *cobra.Command { - cmd := &cobra.Command{ - Use: "contract-state", - Short: "Querying commands for the wasm module", - Aliases: []string{"state", "cs", "s"}, - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - SilenceUsage: true, - } - cmd.AddCommand( - GetCmdGetContractStateAll(), - GetCmdGetContractStateRaw(), - GetCmdGetContractStateSmart(), - ) - return cmd -} - -func GetCmdGetContractStateAll() *cobra.Command { - cmd := &cobra.Command{ - Use: "all [bech32_address]", - Short: "Prints out all internal state of a contract given its address", - Long: "Prints out all internal state of a contract given its address", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.AllContractState( - context.Background(), - &types.QueryAllContractStateRequest{ - Address: args[0], - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "contract state") - return cmd -} - -func GetCmdGetContractStateRaw() *cobra.Command { - decoder := newArgDecoder(hex.DecodeString) - cmd := &cobra.Command{ - Use: "raw [bech32_address] [key]", - Short: "Prints out internal state for key of a contract given its address", - Long: "Prints out internal state for of a contract given its address", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - queryData, err := decoder.DecodeString(args[1]) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.RawContractState( - context.Background(), - &types.QueryRawContractStateRequest{ - Address: args[0], - QueryData: queryData, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - decoder.RegisterFlags(cmd.PersistentFlags(), "key argument") - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -func GetCmdGetContractStateSmart() *cobra.Command { - decoder := newArgDecoder(asciiDecodeString) - cmd := &cobra.Command{ - Use: "smart [bech32_address] [query]", - Short: "Calls contract with given address with query data and prints the returned result", - Long: "Calls contract with given address with query data and prints the returned result", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - if args[1] == "" { - return errors.New("query data must not be empty") - } - - queryData, err := decoder.DecodeString(args[1]) - if err != nil { - return fmt.Errorf("decode query: %s", err) - } - if !json.Valid(queryData) { - return errors.New("query data must be json") - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.SmartContractState( - context.Background(), - &types.QuerySmartContractStateRequest{ - Address: args[0], - QueryData: queryData, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - decoder.RegisterFlags(cmd.PersistentFlags(), "query argument") - flags.AddQueryFlagsToCmd(cmd) - return cmd -} - -// GetCmdGetContractHistory prints the code history for a given contract -func GetCmdGetContractHistory() *cobra.Command { - cmd := &cobra.Command{ - Use: "contract-history [bech32_address]", - Short: "Prints out the code history for a contract given its address", - Long: "Prints out the code history for a contract given its address", - Aliases: []string{"history", "hist", "ch"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.ContractHistory( - context.Background(), - &types.QueryContractHistoryRequest{ - Address: args[0], - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "contract history") - return cmd -} - -// GetCmdListPinnedCode lists all wasm code ids that are pinned -func GetCmdListPinnedCode() *cobra.Command { - cmd := &cobra.Command{ - Use: "pinned", - Short: "List all pinned code ids", - Long: "List all pinned code ids", - Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.PinnedCodes( - context.Background(), - &types.QueryPinnedCodesRequest{ - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "list codes") - return cmd -} - -// GetCmdListContractsByCreator lists all contracts by creator -func GetCmdListContractsByCreator() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-contracts-by-creator [creator]", - Short: "List all contracts by creator", - Long: "List all contracts by creator", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientQueryContext(cmd) - if err != nil { - return err - } - _, err = sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - pageReq, err := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags())) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - res, err := queryClient.ContractsByCreator( - context.Background(), - &types.QueryContractsByCreatorRequest{ - CreatorAddress: args[0], - Pagination: pageReq, - }, - ) - if err != nil { - return err - } - return clientCtx.PrintProto(res) - }, - SilenceUsage: true, - } - flags.AddQueryFlagsToCmd(cmd) - flags.AddPaginationFlagsToCmd(cmd, "list contracts by creator") - return cmd -} - -type argumentDecoder struct { - // dec is the default decoder - dec func(string) ([]byte, error) - asciiF, hexF, b64F bool -} - -func newArgDecoder(def func(string) ([]byte, error)) *argumentDecoder { - return &argumentDecoder{dec: def} -} - -func (a *argumentDecoder) RegisterFlags(f *flag.FlagSet, argName string) { - f.BoolVar(&a.asciiF, "ascii", false, "ascii encoded "+argName) - f.BoolVar(&a.hexF, "hex", false, "hex encoded "+argName) - f.BoolVar(&a.b64F, "b64", false, "base64 encoded "+argName) -} - -func (a *argumentDecoder) DecodeString(s string) ([]byte, error) { - found := -1 - for i, v := range []*bool{&a.asciiF, &a.hexF, &a.b64F} { - if !*v { - continue - } - if found != -1 { - return nil, errors.New("multiple decoding flags used") - } - found = i - } - switch found { - case 0: - return asciiDecodeString(s) - case 1: - return hex.DecodeString(s) - case 2: - return base64.StdEncoding.DecodeString(s) - default: - return a.dec(s) - } -} - -func asciiDecodeString(s string) ([]byte, error) { - return []byte(s), nil -} - -// sdk ReadPageRequest expects binary but we encoded to base64 in our marshaller -func withPageKeyDecoded(flagSet *flag.FlagSet) *flag.FlagSet { - encoded, err := flagSet.GetString(flags.FlagPageKey) - if err != nil { - panic(err.Error()) - } - raw, err := base64.StdEncoding.DecodeString(encoded) - if err != nil { - panic(err.Error()) - } - err = flagSet.Set(flags.FlagPageKey, string(raw)) - if err != nil { - panic(err.Error()) - } - return flagSet -} - -// GetCmdQueryParams implements a command to return the current wasm -// parameters. -func GetCmdQueryParams() *cobra.Command { - cmd := &cobra.Command{ - Use: "params", - Short: "Query the current wasm parameters", - 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) - - params := &types.QueryParamsRequest{} - res, err := queryClient.Params(cmd.Context(), params) - if err != nil { - return err - } - - return clientCtx.PrintProto(&res.Params) - }, - SilenceUsage: true, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} diff --git a/x/wasm/client/cli/tx.go b/x/wasm/client/cli/tx.go deleted file mode 100644 index 6131620..0000000 --- a/x/wasm/client/cli/tx.go +++ /dev/null @@ -1,566 +0,0 @@ -package cli - -import ( - "encoding/hex" - "errors" - "fmt" - "os" - "strconv" - "time" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/authz" - "github.com/spf13/cobra" - flag "github.com/spf13/pflag" - - "github.com/terpnetwork/terp-core/x/wasm/ioutils" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - flagAmount = "amount" - flagLabel = "label" - flagSource = "code-source-url" - flagBuilder = "builder" - flagCodeHash = "code-hash" - flagAdmin = "admin" - flagNoAdmin = "no-admin" - flagFixMsg = "fix-msg" - flagRunAs = "run-as" - flagInstantiateByEverybody = "instantiate-everybody" - flagInstantiateNobody = "instantiate-nobody" - flagInstantiateByAddress = "instantiate-only-address" - flagInstantiateByAnyOfAddress = "instantiate-anyof-addresses" - flagUnpinCode = "unpin-code" - flagAllowedMsgKeys = "allow-msg-keys" - flagAllowedRawMsgs = "allow-raw-msgs" - flagExpiration = "expiration" - flagMaxCalls = "max-calls" - flagMaxFunds = "max-funds" - flagAllowAllMsgs = "allow-all-messages" - flagNoTokenTransfer = "no-token-transfer" //nolint:gosec -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - txCmd := &cobra.Command{ - Use: types.ModuleName, - Short: "Wasm transaction subcommands", - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - SilenceUsage: true, - } - txCmd.AddCommand( - StoreCodeCmd(), - InstantiateContractCmd(), - InstantiateContract2Cmd(), - ExecuteContractCmd(), - MigrateContractCmd(), - UpdateContractAdminCmd(), - ClearContractAdminCmd(), - GrantAuthorizationCmd(), - UpdateInstantiateConfigCmd(), - ) - return txCmd -} - -// StoreCodeCmd will upload code to be reused. -func StoreCodeCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "store [wasm file]", - Short: "Upload a wasm binary", - Aliases: []string{"upload", "st", "s"}, - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - msg, err := parseStoreCodeArgs(args[0], clientCtx.GetFromAddress().String(), cmd.Flags()) - if err != nil { - return err - } - if err = msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - - addInstantiatePermissionFlags(cmd) - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -// Prepares MsgStoreCode object from flags with gzipped wasm byte code field -func parseStoreCodeArgs(file string, sender string, flags *flag.FlagSet) (types.MsgStoreCode, error) { - wasm, err := os.ReadFile(file) - if err != nil { - return types.MsgStoreCode{}, err - } - - // gzip the wasm file - if ioutils.IsWasm(wasm) { - wasm, err = ioutils.GzipIt(wasm) - - if err != nil { - return types.MsgStoreCode{}, err - } - } else if !ioutils.IsGzip(wasm) { - return types.MsgStoreCode{}, fmt.Errorf("invalid input file. Use wasm binary or gzip") - } - - perm, err := parseAccessConfigFlags(flags) - if err != nil { - return types.MsgStoreCode{}, err - } - - msg := types.MsgStoreCode{ - Sender: sender, - WASMByteCode: wasm, - InstantiatePermission: perm, - } - return msg, nil -} - -func parseAccessConfigFlags(flags *flag.FlagSet) (*types.AccessConfig, error) { - addrs, err := flags.GetStringSlice(flagInstantiateByAnyOfAddress) - if err != nil { - return nil, fmt.Errorf("flag any of: %s", err) - } - if len(addrs) != 0 { - acceptedAddrs := make([]sdk.AccAddress, len(addrs)) - for i, v := range addrs { - acceptedAddrs[i], err = sdk.AccAddressFromBech32(v) - if err != nil { - return nil, fmt.Errorf("parse %q: %w", v, err) - } - } - x := types.AccessTypeAnyOfAddresses.With(acceptedAddrs...) - return &x, nil - } - - onlyAddrStr, err := flags.GetString(flagInstantiateByAddress) - if err != nil { - return nil, fmt.Errorf("instantiate by address: %s", err) - } - if onlyAddrStr != "" { - return nil, fmt.Errorf("not supported anymore. Use: %s", flagInstantiateByAnyOfAddress) - } - everybodyStr, err := flags.GetString(flagInstantiateByEverybody) - if err != nil { - return nil, fmt.Errorf("instantiate by everybody: %s", err) - } - if everybodyStr != "" { - ok, err := strconv.ParseBool(everybodyStr) - if err != nil { - return nil, fmt.Errorf("boolean value expected for instantiate by everybody: %s", err) - } - if ok { - return &types.AllowEverybody, nil - } - } - - nobodyStr, err := flags.GetString(flagInstantiateNobody) - if err != nil { - return nil, fmt.Errorf("instantiate by nobody: %s", err) - } - if nobodyStr != "" { - ok, err := strconv.ParseBool(nobodyStr) - if err != nil { - return nil, fmt.Errorf("boolean value expected for instantiate by nobody: %s", err) - } - if ok { - return &types.AllowNobody, nil - } - } - return nil, nil -} - -func addInstantiatePermissionFlags(cmd *cobra.Command) { - cmd.Flags().String(flagInstantiateByEverybody, "", "Everybody can instantiate a contract from the code, optional") - cmd.Flags().String(flagInstantiateNobody, "", "Nobody except the governance process can instantiate a contract from the code, optional") - cmd.Flags().String(flagInstantiateByAddress, "", fmt.Sprintf("Removed: use %s instead", flagInstantiateByAnyOfAddress)) - cmd.Flags().StringSlice(flagInstantiateByAnyOfAddress, []string{}, "Any of the addresses can instantiate a contract from the code, optional") -} - -// InstantiateContractCmd will instantiate a contract from previously uploaded code. -func InstantiateContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "instantiate [code_id_int64] [json_encoded_init_args] --label [text] --admin [address,optional] --amount [coins,optional] ", - Short: "Instantiate a wasm contract", - Long: fmt.Sprintf(`Creates a new instance of an uploaded wasm code with the given 'constructor' message. -Each contract instance has a unique address assigned. -Example: -$ %s tx wasm instantiate 1 '{"foo":"bar"}' --admin="$(%s keys show mykey -a)" \ - --from mykey --amount="100ustake" --label "local0.1.0" -`, version.AppName, version.AppName), - Aliases: []string{"start", "init", "inst", "i"}, - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - msg, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.GetFromAddress().String(), cmd.Flags()) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - - cmd.Flags().String(flagAmount, "", "Coins to send to the contract during instantiation") - cmd.Flags().String(flagLabel, "", "A human-readable name for this contract in lists") - cmd.Flags().String(flagAdmin, "", "Address or key name of an admin") - cmd.Flags().Bool(flagNoAdmin, false, "You must set this explicitly if you don't want an admin") - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -// InstantiateContract2Cmd will instantiate a contract from previously uploaded code with predicable address generated -func InstantiateContract2Cmd() *cobra.Command { - decoder := newArgDecoder(hex.DecodeString) - cmd := &cobra.Command{ - Use: "instantiate2 [code_id_int64] [json_encoded_init_args] [salt] --label [text] --admin [address,optional] --amount [coins,optional] " + - "--fix-msg [bool,optional]", - Short: "Instantiate a wasm contract with predictable address", - Long: fmt.Sprintf(`Creates a new instance of an uploaded wasm code with the given 'constructor' message. -Each contract instance has a unique address assigned. They are assigned automatically but in order to have predictable addresses -for special use cases, the given 'salt' argument and '--fix-msg' parameters can be used to generate a custom address. - -Predictable address example (also see '%s query wasm build-address -h'): -$ %s tx wasm instantiate2 1 '{"foo":"bar"}' $(echo -n "testing" | xxd -ps) --admin="$(%s keys show mykey -a)" \ - --from mykey --amount="100ustake" --label "local0.1.0" \ - --fix-msg -`, version.AppName, version.AppName, version.AppName), - Aliases: []string{"start", "init", "inst", "i"}, - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - salt, err := decoder.DecodeString(args[2]) - if err != nil { - return fmt.Errorf("salt: %w", err) - } - fixMsg, err := cmd.Flags().GetBool(flagFixMsg) - if err != nil { - return fmt.Errorf("fix msg: %w", err) - } - data, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.GetFromAddress().String(), cmd.Flags()) - if err != nil { - return err - } - msg := &types.MsgInstantiateContract2{ - Sender: data.Sender, - Admin: data.Admin, - CodeID: data.CodeID, - Label: data.Label, - Msg: data.Msg, - Funds: data.Funds, - Salt: salt, - FixMsg: fixMsg, - } - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - - cmd.Flags().String(flagAmount, "", "Coins to send to the contract during instantiation") - cmd.Flags().String(flagLabel, "", "A human-readable name for this contract in lists") - cmd.Flags().String(flagAdmin, "", "Address or key name of an admin") - cmd.Flags().Bool(flagNoAdmin, false, "You must set this explicitly if you don't want an admin") - cmd.Flags().Bool(flagFixMsg, false, "An optional flag to include the json_encoded_init_args for the predictable address generation mode") - decoder.RegisterFlags(cmd.PersistentFlags(), "salt") - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -func parseInstantiateArgs(rawCodeID, initMsg string, kr keyring.Keyring, sender string, flags *flag.FlagSet) (*types.MsgInstantiateContract, error) { - // get the id of the code to instantiate - codeID, err := strconv.ParseUint(rawCodeID, 10, 64) - if err != nil { - return nil, err - } - - amountStr, err := flags.GetString(flagAmount) - if err != nil { - return nil, fmt.Errorf("amount: %s", err) - } - amount, err := sdk.ParseCoinsNormalized(amountStr) - if err != nil { - return nil, fmt.Errorf("amount: %s", err) - } - label, err := flags.GetString(flagLabel) - if err != nil { - return nil, fmt.Errorf("label: %s", err) - } - if label == "" { - return nil, errors.New("label is required on all contracts") - } - adminStr, err := flags.GetString(flagAdmin) - if err != nil { - return nil, fmt.Errorf("admin: %s", err) - } - - noAdmin, err := flags.GetBool(flagNoAdmin) - if err != nil { - return nil, fmt.Errorf("no-admin: %s", err) - } - - // ensure sensible admin is set (or explicitly immutable) - if adminStr == "" && !noAdmin { - return nil, fmt.Errorf("you must set an admin or explicitly pass --no-admin to make it immutible (wasmd issue #719)") - } - if adminStr != "" && noAdmin { - return nil, fmt.Errorf("you set an admin and passed --no-admin, those cannot both be true") - } - - if adminStr != "" { - addr, err := sdk.AccAddressFromBech32(adminStr) - if err != nil { - info, err := kr.Key(adminStr) - if err != nil { - return nil, fmt.Errorf("admin %s", err) - } - admin, err := info.GetAddress() - if err != nil { - return nil, err - } - adminStr = admin.String() - } else { - adminStr = addr.String() - } - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.MsgInstantiateContract{ - Sender: sender, - CodeID: codeID, - Label: label, - Funds: amount, - Msg: []byte(initMsg), - Admin: adminStr, - } - return &msg, nil -} - -// ExecuteContractCmd will instantiate a contract from previously uploaded code. -func ExecuteContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "execute [contract_addr_bech32] [json_encoded_send_args] --amount [coins,optional]", - Short: "Execute a command on a wasm contract", - Aliases: []string{"run", "call", "exec", "ex", "e"}, - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg, err := parseExecuteArgs(args[0], args[1], clientCtx.GetFromAddress(), cmd.Flags()) - if err != nil { - return err - } - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) - }, - SilenceUsage: true, - } - - cmd.Flags().String(flagAmount, "", "Coins to send to the contract along with command") - flags.AddTxFlagsToCmd(cmd) - return cmd -} - -func parseExecuteArgs(contractAddr string, execMsg string, sender sdk.AccAddress, flags *flag.FlagSet) (types.MsgExecuteContract, error) { - amountStr, err := flags.GetString(flagAmount) - if err != nil { - return types.MsgExecuteContract{}, fmt.Errorf("amount: %s", err) - } - - amount, err := sdk.ParseCoinsNormalized(amountStr) - if err != nil { - return types.MsgExecuteContract{}, err - } - - return types.MsgExecuteContract{ - Sender: sender.String(), - Contract: contractAddr, - Funds: amount, - Msg: []byte(execMsg), - }, nil -} - -func GrantAuthorizationCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "grant [grantee] [message_type=\"execution\"|\"migration\"] [contract_addr_bech32] --allow-raw-msgs [msg1,msg2,...] --allow-msg-keys [key1,key2,...] --allow-all-messages", - Short: "Grant authorization to an address", - Long: fmt.Sprintf(`Grant authorization to an address. -Examples: -$ %s tx grant execution --allow-all-messages --max-calls 1 --no-token-transfer --expiration 1667979596 - -$ %s tx grant execution --allow-all-messages --max-funds 100000uwasm --expiration 1667979596 - -$ %s tx grant execution --allow-all-messages --max-calls 5 --max-funds 100000uwasm --expiration 1667979596 -`, version.AppName, version.AppName, version.AppName), - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - grantee, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - return err - } - - contract, err := sdk.AccAddressFromBech32(args[2]) - if err != nil { - return err - } - - msgKeys, err := cmd.Flags().GetStringSlice(flagAllowedMsgKeys) - if err != nil { - return err - } - - rawMsgs, err := cmd.Flags().GetStringSlice(flagAllowedRawMsgs) - if err != nil { - return err - } - - maxFundsStr, err := cmd.Flags().GetString(flagMaxFunds) - if err != nil { - return fmt.Errorf("max funds: %s", err) - } - - maxCalls, err := cmd.Flags().GetUint64(flagMaxCalls) - if err != nil { - return err - } - - exp, err := cmd.Flags().GetInt64(flagExpiration) - if err != nil { - return err - } - if exp == 0 { - return errors.New("expiration must be set") - } - - allowAllMsgs, err := cmd.Flags().GetBool(flagAllowAllMsgs) - if err != nil { - return err - } - - noTokenTransfer, err := cmd.Flags().GetBool(flagNoTokenTransfer) - if err != nil { - return err - } - - var limit types.ContractAuthzLimitX - switch { - case maxFundsStr != "" && maxCalls != 0 && !noTokenTransfer: - maxFunds, err := sdk.ParseCoinsNormalized(maxFundsStr) - if err != nil { - return fmt.Errorf("max funds: %s", err) - } - limit = types.NewCombinedLimit(maxCalls, maxFunds...) - case maxFundsStr != "" && maxCalls == 0 && !noTokenTransfer: - maxFunds, err := sdk.ParseCoinsNormalized(maxFundsStr) - if err != nil { - return fmt.Errorf("max funds: %s", err) - } - limit = types.NewMaxFundsLimit(maxFunds...) - case maxCalls != 0 && noTokenTransfer && maxFundsStr == "": - limit = types.NewMaxCallsLimit(maxCalls) - default: - return errors.New("invalid limit setup") - } - - var filter types.ContractAuthzFilterX - switch { - case allowAllMsgs && len(msgKeys) != 0 || allowAllMsgs && len(rawMsgs) != 0 || len(msgKeys) != 0 && len(rawMsgs) != 0: - return errors.New("cannot set more than one filter within one grant") - case allowAllMsgs: - filter = types.NewAllowAllMessagesFilter() - case len(msgKeys) != 0: - filter = types.NewAcceptedMessageKeysFilter(msgKeys...) - case len(rawMsgs) != 0: - msgs := make([]types.RawContractMessage, len(rawMsgs)) - for i, msg := range rawMsgs { - msgs[i] = types.RawContractMessage(msg) - } - filter = types.NewAcceptedMessagesFilter(msgs...) - default: - return errors.New("invalid filter setup") - } - - grant, err := types.NewContractGrant(contract, limit, filter) - if err != nil { - return err - } - - var authorization authz.Authorization - switch args[1] { - case "execution": - authorization = types.NewContractExecutionAuthorization(*grant) - case "migration": - authorization = types.NewContractMigrationAuthorization(*grant) - default: - return fmt.Errorf("%s authorization type not supported", args[1]) - } - - expire, err := getExpireTime(cmd) - if err != nil { - return err - } - - grantMsg, err := authz.NewMsgGrant(clientCtx.GetFromAddress(), grantee, authorization, expire) - if err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), grantMsg) - }, - } - flags.AddTxFlagsToCmd(cmd) - cmd.Flags().StringSlice(flagAllowedMsgKeys, []string{}, "Allowed msg keys") - cmd.Flags().StringSlice(flagAllowedRawMsgs, []string{}, "Allowed raw msgs") - cmd.Flags().Uint64(flagMaxCalls, 0, "Maximal number of calls to the contract") - cmd.Flags().String(flagMaxFunds, "", "Maximal amount of tokens transferable to the contract.") - cmd.Flags().Int64(flagExpiration, 0, "The Unix timestamp.") - cmd.Flags().Bool(flagAllowAllMsgs, false, "Allow all messages") - cmd.Flags().Bool(flagNoTokenTransfer, false, "Don't allow token transfer") - return cmd -} - -func getExpireTime(cmd *cobra.Command) (*time.Time, error) { - exp, err := cmd.Flags().GetInt64(flagExpiration) - if err != nil { - return nil, err - } - if exp == 0 { - return nil, nil - } - e := time.Unix(exp, 0) - return &e, nil -} diff --git a/x/wasm/client/cli/tx_test.go b/x/wasm/client/cli/tx_test.go deleted file mode 100644 index 0521f5e..0000000 --- a/x/wasm/client/cli/tx_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package cli - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestParseAccessConfigFlags(t *testing.T) { - specs := map[string]struct { - args []string - expCfg *types.AccessConfig - expErr bool - }{ - "nobody": { - args: []string{"--instantiate-nobody=true"}, - expCfg: &types.AccessConfig{Permission: types.AccessTypeNobody}, - }, - "everybody": { - args: []string{"--instantiate-everybody=true"}, - expCfg: &types.AccessConfig{Permission: types.AccessTypeEverybody}, - }, - "only address": { - args: []string{"--instantiate-only-address=cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x"}, - expErr: true, - }, - "only address - invalid": { - args: []string{"--instantiate-only-address=foo"}, - expErr: true, - }, - "any of address": { - args: []string{"--instantiate-anyof-addresses=cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x,cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"}, - expCfg: &types.AccessConfig{Permission: types.AccessTypeAnyOfAddresses, Addresses: []string{"cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x", "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"}}, - }, - "any of address - invalid": { - args: []string{"--instantiate-anyof-addresses=cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x,foo"}, - expErr: true, - }, - "not set": { - args: []string{}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - flags := StoreCodeCmd().Flags() - require.NoError(t, flags.Parse(spec.args)) - gotCfg, gotErr := parseAccessConfigFlags(flags) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expCfg, gotCfg) - }) - } -} diff --git a/x/wasm/common_test.go b/x/wasm/common_test.go deleted file mode 100644 index 4500abe..0000000 --- a/x/wasm/common_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package wasm - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -// ensure store code returns the expected response -func assertStoreCodeResponse(t *testing.T, data []byte, expected uint64) { - var pStoreResp MsgStoreCodeResponse - require.NoError(t, pStoreResp.Unmarshal(data)) - require.Equal(t, pStoreResp.CodeID, expected) -} - -// ensure execution returns the expected data -func assertExecuteResponse(t *testing.T, data []byte, expected []byte) { - var pExecResp MsgExecuteContractResponse - require.NoError(t, pExecResp.Unmarshal(data)) - require.Equal(t, pExecResp.Data, expected) -} - -// ensures this returns a valid bech32 address and returns it -func parseInitResponse(t *testing.T, data []byte) string { - t.Helper() - var pInstResp MsgInstantiateContractResponse - require.NoError(t, pInstResp.Unmarshal(data)) - require.NotEmpty(t, pInstResp.Address) - addr := pInstResp.Address - // ensure this is a valid sdk address - _, err := sdk.AccAddressFromBech32(addr) - require.NoError(t, err) - return addr -} diff --git a/x/wasm/genesis_test.go b/x/wasm/genesis_test.go deleted file mode 100644 index 83d5db2..0000000 --- a/x/wasm/genesis_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package wasm - -import ( - "encoding/json" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestInitGenesis(t *testing.T) { - data := setupTest(t) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := data.faucet.NewFundedRandomAccount(data.ctx, deposit.Add(deposit...)...) - fred := data.faucet.NewFundedRandomAccount(data.ctx, topUp...) - - msg := MsgStoreCode{ - Sender: creator.String(), - WASMByteCode: testContract, - } - h := data.msgServiceRouter.Handler(&msg) - q := data.grpcQueryRouter - - err := msg.ValidateBasic() - require.NoError(t, err) - - res, err := h(data.ctx, &msg) - require.NoError(t, err) - assertStoreCodeResponse(t, res.Data, 1) - - bob := keyPubAddr() - initMsg := initMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - instMsg := MsgInstantiateContract{ - Sender: creator.String(), - CodeID: firstCodeID, - Msg: initMsgBz, - Funds: deposit, - Label: "testing", - } - h = data.msgServiceRouter.Handler(&instMsg) - res, err = h(data.ctx, &instMsg) - require.NoError(t, err) - contractBech32Addr := parseInitResponse(t, res.Data) - - execMsg := MsgExecuteContract{ - Sender: fred.String(), - Contract: contractBech32Addr, - Msg: []byte(`{"release":{}}`), - Funds: topUp, - } - h = data.msgServiceRouter.Handler(&execMsg) - res, err = h(data.ctx, &execMsg) - require.NoError(t, err) - // from https://github.com/CosmWasm/cosmwasm/blob/master/contracts/hackatom/src/contract.rs#L167 - assertExecuteResponse(t, res.Data, []byte{0xf0, 0x0b, 0xaa}) - - // ensure all contract state is as after init - assertCodeList(t, q, data.ctx, 1, data.encConf.Marshaler) - assertCodeBytes(t, q, data.ctx, 1, testContract, data.encConf.Marshaler) - - assertContractList(t, q, data.ctx, 1, []string{contractBech32Addr}, data.encConf.Marshaler) - assertContractInfo(t, q, data.ctx, contractBech32Addr, 1, creator, data.encConf.Marshaler) - assertContractState(t, q, data.ctx, contractBech32Addr, state{ - Verifier: fred.String(), - Beneficiary: bob.String(), - Funder: creator.String(), - }, data.encConf.Marshaler) - - // export into genstate - genState := ExportGenesis(data.ctx, &data.keeper) - - // create new app to import genstate into - newData := setupTest(t) - q2 := newData.grpcQueryRouter - - // initialize new app with genstate - _, err = InitGenesis(newData.ctx, &newData.keeper, *genState) - require.NoError(t, err) - - // run same checks again on newdata, to make sure it was reinitialized correctly - assertCodeList(t, q2, newData.ctx, 1, data.encConf.Marshaler) - assertCodeBytes(t, q2, newData.ctx, 1, testContract, data.encConf.Marshaler) - - assertContractList(t, q2, newData.ctx, 1, []string{contractBech32Addr}, data.encConf.Marshaler) - assertContractInfo(t, q2, newData.ctx, contractBech32Addr, 1, creator, data.encConf.Marshaler) - assertContractState(t, q2, newData.ctx, contractBech32Addr, state{ - Verifier: fred.String(), - Beneficiary: bob.String(), - Funder: creator.String(), - }, data.encConf.Marshaler) -} diff --git a/x/wasm/ibc.go b/x/wasm/ibc.go deleted file mode 100644 index cf06e64..0000000 --- a/x/wasm/ibc.go +++ /dev/null @@ -1,357 +0,0 @@ -package wasm - -import ( - "math" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - porttypes "github.com/cosmos/ibc-go/v7/modules/core/05-port/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ porttypes.IBCModule = IBCHandler{} - -// internal interface that is implemented by ibc middleware -type appVersionGetter interface { - // GetAppVersion returns the application level version with all middleware data stripped out - GetAppVersion(ctx sdk.Context, portID, channelID string) (string, bool) -} - -type IBCHandler struct { - keeper types.IBCContractKeeper - channelKeeper types.ChannelKeeper - appVersionGetter appVersionGetter -} - -func NewIBCHandler(k types.IBCContractKeeper, ck types.ChannelKeeper, vg appVersionGetter) IBCHandler { - return IBCHandler{keeper: k, channelKeeper: ck, appVersionGetter: vg} -} - -// OnChanOpenInit implements the IBCModule interface -func (i IBCHandler) OnChanOpenInit( - ctx sdk.Context, - order channeltypes.Order, - connectionHops []string, - portID string, - channelID string, - chanCap *capabilitytypes.Capability, - counterParty channeltypes.Counterparty, - version string, -) (string, error) { - // ensure port, version, capability - if err := ValidateChannelParams(channelID); err != nil { - return "", err - } - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return "", errorsmod.Wrapf(err, "contract port id") - } - - msg := wasmvmtypes.IBCChannelOpenMsg{ - OpenInit: &wasmvmtypes.IBCOpenInit{ - Channel: wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{PortID: portID, ChannelID: channelID}, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{PortID: counterParty.PortId, ChannelID: counterParty.ChannelId}, - Order: order.String(), - // DESIGN V3: this may be "" ?? - Version: version, - ConnectionID: connectionHops[0], // At the moment this list must be of length 1. In the future multi-hop channels may be supported. - }, - }, - } - - // Allow contracts to return a version (or default to proposed version if unset) - acceptedVersion, err := i.keeper.OnOpenChannel(ctx, contractAddr, msg) - if err != nil { - return "", err - } - if acceptedVersion == "" { // accept incoming version when nothing returned by contract - acceptedVersion = version - } - - // Claim channel capability passed back by IBC module - if err := i.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return "", errorsmod.Wrap(err, "claim capability") - } - return acceptedVersion, nil -} - -// OnChanOpenTry implements the IBCModule interface -func (i IBCHandler) OnChanOpenTry( - ctx sdk.Context, - order channeltypes.Order, - connectionHops []string, - portID, channelID string, - chanCap *capabilitytypes.Capability, - counterParty channeltypes.Counterparty, - counterpartyVersion string, -) (string, error) { - // ensure port, version, capability - if err := ValidateChannelParams(channelID); err != nil { - return "", err - } - - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return "", errorsmod.Wrapf(err, "contract port id") - } - - msg := wasmvmtypes.IBCChannelOpenMsg{ - OpenTry: &wasmvmtypes.IBCOpenTry{ - Channel: wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{PortID: portID, ChannelID: channelID}, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{PortID: counterParty.PortId, ChannelID: counterParty.ChannelId}, - Order: order.String(), - Version: counterpartyVersion, - ConnectionID: connectionHops[0], // At the moment this list must be of length 1. In the future multi-hop channels may be supported. - }, - CounterpartyVersion: counterpartyVersion, - }, - } - - // Allow contracts to return a version (or default to counterpartyVersion if unset) - version, err := i.keeper.OnOpenChannel(ctx, contractAddr, msg) - if err != nil { - return "", err - } - if version == "" { - version = counterpartyVersion - } - - // Module may have already claimed capability in OnChanOpenInit in the case of crossing hellos - // (ie chainA and chainB both call ChanOpenInit before one of them calls ChanOpenTry) - // If module can already authenticate the capability then module already owns it, so we don't need to claim - // Otherwise, module does not have channel capability, and we must claim it from IBC - if !i.keeper.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) { - // Only claim channel capability passed back by IBC module if we do not already own it - if err := i.keeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil { - return "", errorsmod.Wrap(err, "claim capability") - } - } - - return version, nil -} - -// OnChanOpenAck implements the IBCModule interface -func (i IBCHandler) OnChanOpenAck( - ctx sdk.Context, - portID, channelID string, - counterpartyChannelID string, - counterpartyVersion string, -) error { - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) - } - channelInfo.Counterparty.ChannelId = counterpartyChannelID - - appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) - } - - msg := wasmvmtypes.IBCChannelConnectMsg{ - OpenAck: &wasmvmtypes.IBCOpenAck{ - Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion), - CounterpartyVersion: counterpartyVersion, - }, - } - return i.keeper.OnConnectChannel(ctx, contractAddr, msg) -} - -// OnChanOpenConfirm implements the IBCModule interface -func (i IBCHandler) OnChanOpenConfirm(ctx sdk.Context, portID, channelID string) error { - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) - } - appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) - } - msg := wasmvmtypes.IBCChannelConnectMsg{ - OpenConfirm: &wasmvmtypes.IBCOpenConfirm{ - Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion), - }, - } - return i.keeper.OnConnectChannel(ctx, contractAddr, msg) -} - -// OnChanCloseInit implements the IBCModule interface -func (i IBCHandler) OnChanCloseInit(ctx sdk.Context, portID, channelID string) error { - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) - } - appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) - } - - msg := wasmvmtypes.IBCChannelCloseMsg{ - CloseInit: &wasmvmtypes.IBCCloseInit{Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion)}, - } - err = i.keeper.OnCloseChannel(ctx, contractAddr, msg) - if err != nil { - return err - } - // emit events? - - return err -} - -// OnChanCloseConfirm implements the IBCModule interface -func (i IBCHandler) OnChanCloseConfirm(ctx sdk.Context, portID, channelID string) error { - // counterparty has closed the channel - contractAddr, err := ContractFromPortID(portID) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) - } - appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) - if !ok { - return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) - } - - msg := wasmvmtypes.IBCChannelCloseMsg{ - CloseConfirm: &wasmvmtypes.IBCCloseConfirm{Channel: toWasmVMChannel(portID, channelID, channelInfo, appVersion)}, - } - err = i.keeper.OnCloseChannel(ctx, contractAddr, msg) - if err != nil { - return err - } - // emit events? - - return err -} - -func toWasmVMChannel(portID, channelID string, channelInfo channeltypes.Channel, appVersion string) wasmvmtypes.IBCChannel { - return wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{PortID: portID, ChannelID: channelID}, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{PortID: channelInfo.Counterparty.PortId, ChannelID: channelInfo.Counterparty.ChannelId}, - Order: channelInfo.Ordering.String(), - Version: appVersion, - ConnectionID: channelInfo.ConnectionHops[0], // At the moment this list must be of length 1. In the future multi-hop channels may be supported. - } -} - -// OnRecvPacket implements the IBCModule interface -func (i IBCHandler) OnRecvPacket( - ctx sdk.Context, - packet channeltypes.Packet, - relayer sdk.AccAddress, -) ibcexported.Acknowledgement { - contractAddr, err := ContractFromPortID(packet.DestinationPort) - if err != nil { - return channeltypes.NewErrorAcknowledgement(errorsmod.Wrapf(err, "contract port id")) - } - msg := wasmvmtypes.IBCPacketReceiveMsg{Packet: newIBCPacket(packet), Relayer: relayer.String()} - ack, err := i.keeper.OnRecvPacket(ctx, contractAddr, msg) - if err != nil { - return channeltypes.NewErrorAcknowledgement(err) - } - return ContractConfirmStateAck(ack) -} - -var _ ibcexported.Acknowledgement = ContractConfirmStateAck{} - -type ContractConfirmStateAck []byte - -func (w ContractConfirmStateAck) Success() bool { - return true // always commit state -} - -func (w ContractConfirmStateAck) Acknowledgement() []byte { - return w -} - -// OnAcknowledgementPacket implements the IBCModule interface -func (i IBCHandler) OnAcknowledgementPacket( - ctx sdk.Context, - packet channeltypes.Packet, - acknowledgement []byte, - relayer sdk.AccAddress, -) error { - contractAddr, err := ContractFromPortID(packet.SourcePort) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - - err = i.keeper.OnAckPacket(ctx, contractAddr, wasmvmtypes.IBCPacketAckMsg{ - Acknowledgement: wasmvmtypes.IBCAcknowledgement{Data: acknowledgement}, - OriginalPacket: newIBCPacket(packet), - Relayer: relayer.String(), - }) - if err != nil { - return errorsmod.Wrap(err, "on ack") - } - return nil -} - -// OnTimeoutPacket implements the IBCModule interface -func (i IBCHandler) OnTimeoutPacket(ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) error { - contractAddr, err := ContractFromPortID(packet.SourcePort) - if err != nil { - return errorsmod.Wrapf(err, "contract port id") - } - msg := wasmvmtypes.IBCPacketTimeoutMsg{Packet: newIBCPacket(packet), Relayer: relayer.String()} - err = i.keeper.OnTimeoutPacket(ctx, contractAddr, msg) - if err != nil { - return errorsmod.Wrap(err, "on timeout") - } - return nil -} - -func newIBCPacket(packet channeltypes.Packet) wasmvmtypes.IBCPacket { - timeout := wasmvmtypes.IBCTimeout{ - Timestamp: packet.TimeoutTimestamp, - } - if !packet.TimeoutHeight.IsZero() { - timeout.Block = &wasmvmtypes.IBCTimeoutBlock{ - Height: packet.TimeoutHeight.RevisionHeight, - Revision: packet.TimeoutHeight.RevisionNumber, - } - } - - return wasmvmtypes.IBCPacket{ - Data: packet.Data, - Src: wasmvmtypes.IBCEndpoint{ChannelID: packet.SourceChannel, PortID: packet.SourcePort}, - Dest: wasmvmtypes.IBCEndpoint{ChannelID: packet.DestinationChannel, PortID: packet.DestinationPort}, - Sequence: packet.Sequence, - Timeout: timeout, - } -} - -func ValidateChannelParams(channelID string) error { - // NOTE: for escrow address security only 2^32 channels are allowed to be created - // Issue: https://github.com/cosmos/cosmos-sdk/issues/7737 - channelSequence, err := channeltypes.ParseChannelSequence(channelID) - if err != nil { - return err - } - if channelSequence > math.MaxUint32 { - return errorsmod.Wrapf(types.ErrMaxIBCChannels, "channel sequence %d is greater than max allowed transfer channels %d", channelSequence, math.MaxUint32) - } - return nil -} diff --git a/x/wasm/ibc_integration_test.go b/x/wasm/ibc_integration_test.go deleted file mode 100644 index f348f46..0000000 --- a/x/wasm/ibc_integration_test.go +++ /dev/null @@ -1,126 +0,0 @@ -package wasm_test - -import ( - "testing" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" -) - -func TestOnChanOpenInitVersion(t *testing.T) { - const startVersion = "v1" - specs := map[string]struct { - contractRsp *wasmvmtypes.IBC3ChannelOpenResponse - expVersion string - }{ - "different version": { - contractRsp: &wasmvmtypes.IBC3ChannelOpenResponse{Version: "v2"}, - expVersion: "v2", - }, - "no response": { - expVersion: startVersion, - }, - "empty result": { - contractRsp: &wasmvmtypes.IBC3ChannelOpenResponse{}, - expVersion: startVersion, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myContract := &wasmtesting.MockIBCContractCallbacks{ - IBCChannelOpenFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - return spec.contractRsp, 0, nil - }, - } - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - myContractAddr = chainA.SeedNewContractInstance() - contractInfo = chainA.App.WasmKeeper.GetContractInfo(chainA.GetContext(), myContractAddr) - ) - - path := wasmibctesting.NewPath(chainA, chainB) - coordinator.SetupConnections(path) - - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: contractInfo.IBCPortID, - Version: startVersion, - Order: channeltypes.UNORDERED, - } - require.NoError(t, path.EndpointA.ChanOpenInit()) - assert.Equal(t, spec.expVersion, path.EndpointA.ChannelConfig.Version) - }) - } -} - -func TestOnChanOpenTryVersion(t *testing.T) { - const startVersion = ibctransfertypes.Version - specs := map[string]struct { - contractRsp *wasmvmtypes.IBC3ChannelOpenResponse - expVersion string - }{ - "different version": { - contractRsp: &wasmvmtypes.IBC3ChannelOpenResponse{Version: "v2"}, - expVersion: "v2", - }, - "no response": { - expVersion: startVersion, - }, - "empty result": { - contractRsp: &wasmvmtypes.IBC3ChannelOpenResponse{}, - expVersion: startVersion, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myContract := &wasmtesting.MockIBCContractCallbacks{ - IBCChannelOpenFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - return spec.contractRsp, 0, nil - }, - } - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - myContractAddr = chainA.SeedNewContractInstance() - contractInfo = chainA.ContractInfo(myContractAddr) - ) - - path := wasmibctesting.NewPath(chainA, chainB) - coordinator.SetupConnections(path) - - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: contractInfo.IBCPortID, - Version: startVersion, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - - require.NoError(t, path.EndpointB.ChanOpenInit()) - require.NoError(t, path.EndpointA.ChanOpenTry()) - assert.Equal(t, spec.expVersion, path.EndpointA.ChannelConfig.Version) - }) - } -} diff --git a/x/wasm/ibc_reflect_test.go b/x/wasm/ibc_reflect_test.go deleted file mode 100644 index 7d4e41d..0000000 --- a/x/wasm/ibc_reflect_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package wasm_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" -) - -func TestIBCReflectContract(t *testing.T) { - // scenario: - // chain A: ibc_reflect_send.wasm - // chain B: reflect.wasm + ibc_reflect.wasm - // - // Chain A "ibc_reflect_send" sends a IBC packet "on channel connect" event to chain B "ibc_reflect" - // "ibc_reflect" sends a submessage to "reflect" which is returned as submessage. - - var ( - coordinator = wasmibctesting.NewCoordinator(t, 2) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - coordinator.CommitBlock(chainA, chainB) - - initMsg := []byte(`{}`) - codeID := chainA.StoreCodeFile("./keeper/testdata/ibc_reflect_send.wasm").CodeID - sendContractAddr := chainA.InstantiateContract(codeID, initMsg) - - reflectID := chainB.StoreCodeFile("./keeper/testdata/reflect.wasm").CodeID - initMsg = wasmkeeper.IBCReflectInitMsg{ - ReflectCodeID: reflectID, - }.GetBytes(t) - codeID = chainB.StoreCodeFile("./keeper/testdata/ibc_reflect.wasm").CodeID - - reflectContractAddr := chainB.InstantiateContract(codeID, initMsg) - var ( - sourcePortID = chainA.ContractInfo(sendContractAddr).IBCPortID - counterpartPortID = chainB.ContractInfo(reflectContractAddr).IBCPortID - ) - coordinator.CommitBlock(chainA, chainB) - coordinator.UpdateTime() - - require.Equal(t, chainA.CurrentHeader.Time, chainB.CurrentHeader.Time) - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: sourcePortID, - Version: "ibc-reflect-v1", - Order: channeltypes.ORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: counterpartPortID, - Version: "ibc-reflect-v1", - Order: channeltypes.ORDERED, - } - - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // TODO: query both contracts directly to ensure they have registered the proper connection - // (and the chainB has created a reflect contract) - - // there should be one packet to relay back and forth (whoami) - // TODO: how do I find the packet that was previously sent by the smart contract? - // Coordinator.RecvPacket requires channeltypes.Packet as input? - // Given the source (portID, channelID), we should be able to count how many packets are pending, query the data - // and submit them to the other side (same with acks). This is what the real relayer does. I guess the test framework doesn't? - - // Update: I dug through the code, especially channel.Keeper.SendPacket, and it only writes a commitment - // only writes I see: https://github.com/cosmos/cosmos-sdk/blob/31fdee0228bd6f3e787489c8e4434aabc8facb7d/x/ibc/core/04-channel/keeper/packet.go#L115-L116 - // commitment is hashed packet: https://github.com/cosmos/cosmos-sdk/blob/31fdee0228bd6f3e787489c8e4434aabc8facb7d/x/ibc/core/04-channel/types/packet.go#L14-L34 - // how is the relayer supposed to get the original packet data?? - // eg. ibctransfer doesn't store the packet either: https://github.com/cosmos/cosmos-sdk/blob/master/x/ibc/applications/transfer/keeper/relay.go#L145-L162 - // ... or I guess the original packet data is only available in the event logs???? - // https://github.com/cosmos/cosmos-sdk/blob/31fdee0228bd6f3e787489c8e4434aabc8facb7d/x/ibc/core/04-channel/keeper/packet.go#L121-L132 - - // ensure the expected packet was prepared, and relay it - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - err := coordinator.RelayAndAckPendingPackets(path) - require.NoError(t, err) - require.Equal(t, 0, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // let's query the source contract and make sure it registered an address - query := ReflectSendQueryMsg{Account: &AccountQuery{ChannelID: path.EndpointA.ChannelID}} - var account AccountResponse - err = chainA.SmartQuery(sendContractAddr.String(), query, &account) - require.NoError(t, err) - require.NotEmpty(t, account.RemoteAddr) - require.Empty(t, account.RemoteBalance) - - // close channel - coordinator.CloseChannel(path) - - // let's query the source contract and make sure it registered an address - account = AccountResponse{} - err = chainA.SmartQuery(sendContractAddr.String(), query, &account) - require.Error(t, err) - assert.Contains(t, err.Error(), "not found") -} - -type ReflectSendQueryMsg struct { - Admin *struct{} `json:"admin,omitempty"` - ListAccounts *struct{} `json:"list_accounts,omitempty"` - Account *AccountQuery `json:"account,omitempty"` -} - -type AccountQuery struct { - ChannelID string `json:"channel_id"` -} - -type AccountResponse struct { - LastUpdateTime uint64 `json:"last_update_time,string"` - RemoteAddr string `json:"remote_addr"` - RemoteBalance wasmvmtypes.Coins `json:"remote_balance"` -} diff --git a/x/wasm/ibc_test.go b/x/wasm/ibc_test.go deleted file mode 100644 index a92d451..0000000 --- a/x/wasm/ibc_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package wasm - -import ( - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" -) - -func TestMapToWasmVMIBCPacket(t *testing.T) { - var myTimestamp uint64 = 1 - specs := map[string]struct { - src channeltypes.Packet - exp wasmvmtypes.IBCPacket - }{ - "with height timeout": { - src: IBCPacketFixture(), - exp: wasmvmtypes.IBCPacket{ - Data: []byte("myData"), - Src: wasmvmtypes.IBCEndpoint{PortID: "srcPort", ChannelID: "channel-1"}, - Dest: wasmvmtypes.IBCEndpoint{PortID: "destPort", ChannelID: "channel-2"}, - Sequence: 1, - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{Height: 1, Revision: 2}}, - }, - }, - "with time timeout": { - src: IBCPacketFixture(func(p *channeltypes.Packet) { - p.TimeoutTimestamp = myTimestamp - p.TimeoutHeight = clienttypes.Height{} - }), - exp: wasmvmtypes.IBCPacket{ - Data: []byte("myData"), - Src: wasmvmtypes.IBCEndpoint{PortID: "srcPort", ChannelID: "channel-1"}, - Dest: wasmvmtypes.IBCEndpoint{PortID: "destPort", ChannelID: "channel-2"}, - Sequence: 1, - Timeout: wasmvmtypes.IBCTimeout{Timestamp: myTimestamp}, - }, - }, "with time and height timeout": { - src: IBCPacketFixture(func(p *channeltypes.Packet) { - p.TimeoutTimestamp = myTimestamp - }), - exp: wasmvmtypes.IBCPacket{ - Data: []byte("myData"), - Src: wasmvmtypes.IBCEndpoint{PortID: "srcPort", ChannelID: "channel-1"}, - Dest: wasmvmtypes.IBCEndpoint{PortID: "destPort", ChannelID: "channel-2"}, - Sequence: 1, - Timeout: wasmvmtypes.IBCTimeout{ - Block: &wasmvmtypes.IBCTimeoutBlock{Height: 1, Revision: 2}, - Timestamp: myTimestamp, - }, - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - got := newIBCPacket(spec.src) - assert.Equal(t, spec.exp, got) - }) - } -} - -func IBCPacketFixture(mutators ...func(p *channeltypes.Packet)) channeltypes.Packet { - r := channeltypes.Packet{ - Sequence: 1, - SourcePort: "srcPort", - SourceChannel: "channel-1", - DestinationPort: "destPort", - DestinationChannel: "channel-2", - Data: []byte("myData"), - TimeoutHeight: clienttypes.Height{ - RevisionHeight: 1, - RevisionNumber: 2, - }, - TimeoutTimestamp: 0, - } - for _, m := range mutators { - m(&r) - } - return r -} diff --git a/x/wasm/ibctesting/README.md b/x/wasm/ibctesting/README.md deleted file mode 100644 index 1c92869..0000000 --- a/x/wasm/ibctesting/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# testing package for ibc -Customized version of cosmos-sdk x/ibc/testing \ No newline at end of file diff --git a/x/wasm/ibctesting/chain.go b/x/wasm/ibctesting/chain.go deleted file mode 100644 index 844befc..0000000 --- a/x/wasm/ibctesting/chain.go +++ /dev/null @@ -1,611 +0,0 @@ -package ibctesting - -import ( - "fmt" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm" - - // simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/crypto/tmhash" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmprotoversion "github.com/cometbft/cometbft/proto/tendermint/version" - tmtypes "github.com/cometbft/cometbft/types" - tmversion "github.com/cometbft/cometbft/version" - 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" - capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - "github.com/cosmos/cosmos-sdk/x/staking/testutil" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - commitmenttypes "github.com/cosmos/ibc-go/v7/modules/core/23-commitment/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - "github.com/cosmos/ibc-go/v7/modules/core/exported" - "github.com/cosmos/ibc-go/v7/modules/core/types" - ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/cosmos/ibc-go/v7/testing/mock" - "github.com/stretchr/testify/require" -) - -var MaxAccounts = 10 - -type SenderAccount struct { - SenderPrivKey cryptotypes.PrivKey - SenderAccount authtypes.AccountI -} - -// TestChain is a testing struct that wraps a simapp with the last TM Header, the current ABCI -// header and the validators of the TestChain. It also contains a field called ChainID. This -// is the clientID that *other* chains use to refer to this TestChain. The SenderAccount -// is used for delivering transactions through the application state. -// NOTE: the actual application uses an empty chain-id for ease of testing. -type TestChain struct { - t *testing.T - - Coordinator *Coordinator - App *app.TerpApp - ChainID string - LastHeader *ibctm.Header // header for last block height committed - CurrentHeader tmproto.Header // header for current block height - QueryServer types.QueryServer - TxConfig client.TxConfig - Codec codec.BinaryCodec - - Vals *tmtypes.ValidatorSet - NextVals *tmtypes.ValidatorSet - - // Signers is a map from validator address to the PrivValidator - // The map is converted into an array that is the same order as the validators right before signing commit - // This ensures that signers will always be in correct order even as validator powers change. - // If a test adds a new validator after chain creation, then the signer map must be updated to include - // the new PrivValidator entry. - Signers map[string]tmtypes.PrivValidator - - // autogenerated sender private key - SenderPrivKey cryptotypes.PrivKey - SenderAccount authtypes.AccountI - SenderAccounts []SenderAccount - - PendingSendPackets []channeltypes.Packet -} - -type PacketAck struct { - Packet channeltypes.Packet - Ack []byte -} - -// NewTestChain initializes a new test chain with a default of 4 validators -// Use this function if the tests do not need custom control over the validator set -func NewTestChain(t *testing.T, coord *Coordinator, chainID string, opts ...wasm.Option) *TestChain { - // generate validators private/public key - var ( - validatorsPerChain = 4 - validators = make([]*tmtypes.Validator, 0, validatorsPerChain) - signersByAddress = make(map[string]tmtypes.PrivValidator, validatorsPerChain) - ) - - for i := 0; i < validatorsPerChain; i++ { - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - require.NoError(t, err) - validators = append(validators, tmtypes.NewValidator(pubKey, 1)) - signersByAddress[pubKey.Address().String()] = privVal - } - - // construct validator set; - // Note that the validators are sorted by voting power - // or, if equal, by address lexical order - valSet := tmtypes.NewValidatorSet(validators) - - return NewTestChainWithValSet(t, coord, chainID, valSet, signersByAddress, opts...) -} - -// NewTestChainWithValSet initializes a new TestChain instance with the given validator set -// and signer array. It also initializes 10 Sender accounts with a balance of 10000000000000000000 coins of -// bond denom to use for tests. -// -// The first block height is committed to state in order to allow for client creations on -// counterparty chains. The TestChain will return with a block height starting at 2. -// -// Time management is handled by the Coordinator in order to ensure synchrony between chains. -// Each update of any chain increments the block header time for all chains by 5 seconds. -// -// NOTE: to use a custom sender privkey and account for testing purposes, replace and modify this -// constructor function. -// -// CONTRACT: Validator array must be provided in the order expected by Tendermint. -// i.e. sorted first by power and then lexicographically by address. -func NewTestChainWithValSet(t *testing.T, coord *Coordinator, chainID string, valSet *tmtypes.ValidatorSet, signers map[string]tmtypes.PrivValidator, opts ...wasm.Option) *TestChain { - genAccs := []authtypes.GenesisAccount{} - genBals := []banktypes.Balance{} - senderAccs := []SenderAccount{} - - // generate genesis accounts - for i := 0; i < MaxAccounts; i++ { - senderPrivKey := secp256k1.GenPrivKey() - acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), uint64(i), 0) - amount, ok := sdk.NewIntFromString("10000000000000000000") - require.True(t, ok) - - // add sender account - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amount)), - } - - genAccs = append(genAccs, acc) - genBals = append(genBals, balance) - - senderAcc := SenderAccount{ - SenderAccount: acc, - SenderPrivKey: senderPrivKey, - } - - senderAccs = append(senderAccs, senderAcc) - } - - wasmApp := app.SetupWithGenesisValSet(t, valSet, genAccs, chainID, opts, genBals...) - - // create current header and call begin block - header := tmproto.Header{ - ChainID: chainID, - Height: 1, - Time: coord.CurrentTime.UTC(), - } - - txConfig := wasmApp.TxConfig() - - // create an account to send transactions from - chain := &TestChain{ - t: t, - Coordinator: coord, - ChainID: chainID, - App: wasmApp, - CurrentHeader: header, - QueryServer: wasmApp.IBCKeeper, - TxConfig: txConfig, - Codec: wasmApp.AppCodec(), - Vals: valSet, - NextVals: valSet, - Signers: signers, - SenderPrivKey: senderAccs[0].SenderPrivKey, - SenderAccount: senderAccs[0].SenderAccount, - SenderAccounts: senderAccs, - } - - coord.CommitBlock(chain) - - return chain -} - -// GetContext returns the current context for the application. -func (chain *TestChain) GetContext() sdk.Context { - return chain.App.BaseApp.NewContext(false, chain.CurrentHeader) -} - -// QueryProof performs an abci query with the given key and returns the proto encoded merkle proof -// for the query and the height at which the proof will succeed on a tendermint verifier. -func (chain *TestChain) QueryProof(key []byte) ([]byte, clienttypes.Height) { - return chain.QueryProofAtHeight(key, chain.App.LastBlockHeight()) -} - -// QueryProofAtHeight performs an abci query with the given key and returns the proto encoded merkle proof -// for the query and the height at which the proof will succeed on a tendermint verifier. Only the IBC -// store is supported -func (chain *TestChain) QueryProofAtHeight(key []byte, height int64) ([]byte, clienttypes.Height) { - return chain.QueryProofForStore(exported.StoreKey, key, height) -} - -// QueryProofForStore performs an abci query with the given key and returns the proto encoded merkle proof -// for the query and the height at which the proof will succeed on a tendermint verifier. -func (chain *TestChain) QueryProofForStore(storeKey string, key []byte, height int64) ([]byte, clienttypes.Height) { - res := chain.App.Query(abci.RequestQuery{ - Path: fmt.Sprintf("store/%s/key", storeKey), - Height: height - 1, - Data: key, - Prove: true, - }) - - merkleProof, err := commitmenttypes.ConvertProofs(res.ProofOps) - require.NoError(chain.t, err) - - proof, err := chain.App.AppCodec().Marshal(&merkleProof) - require.NoError(chain.t, err) - - revision := clienttypes.ParseChainID(chain.ChainID) - - // proof height + 1 is returned as the proof created corresponds to the height the proof - // was created in the IAVL tree. Tendermint and subsequently the clients that rely on it - // have heights 1 above the IAVL tree. Thus we return proof height + 1 - return proof, clienttypes.NewHeight(revision, uint64(res.Height)+1) -} - -// QueryUpgradeProof performs an abci query with the given key and returns the proto encoded merkle proof -// for the query and the height at which the proof will succeed on a tendermint verifier. -func (chain *TestChain) QueryUpgradeProof(key []byte, height uint64) ([]byte, clienttypes.Height) { - res := chain.App.Query(abci.RequestQuery{ - Path: "store/upgrade/key", - Height: int64(height - 1), - Data: key, - Prove: true, - }) - - merkleProof, err := commitmenttypes.ConvertProofs(res.ProofOps) - require.NoError(chain.t, err) - - proof, err := chain.App.AppCodec().Marshal(&merkleProof) - require.NoError(chain.t, err) - - revision := clienttypes.ParseChainID(chain.ChainID) - - // proof height + 1 is returned as the proof created corresponds to the height the proof - // was created in the IAVL tree. Tendermint and subsequently the clients that rely on it - // have heights 1 above the IAVL tree. Thus we return proof height + 1 - return proof, clienttypes.NewHeight(revision, uint64(res.Height+1)) -} - -// QueryConsensusStateProof performs an abci query for a consensus state -// stored on the given clientID. The proof and consensusHeight are returned. -func (chain *TestChain) QueryConsensusStateProof(clientID string) ([]byte, clienttypes.Height) { - clientState := chain.GetClientState(clientID) - - consensusHeight := clientState.GetLatestHeight().(clienttypes.Height) - consensusKey := host.FullConsensusStateKey(clientID, consensusHeight) - proofConsensus, _ := chain.QueryProof(consensusKey) - - return proofConsensus, consensusHeight -} - -// NextBlock sets the last header to the current header and increments the current header to be -// at the next block height. It does not update the time as that is handled by the Coordinator. -// It will call Endblock and Commit and apply the validator set changes to the next validators -// of the next block being created. This follows the Tendermint protocol of applying valset changes -// returned on block `n` to the validators of block `n+2`. -// It calls BeginBlock with the new block created before returning. -func (chain *TestChain) NextBlock() { - res := chain.App.EndBlock(abci.RequestEndBlock{Height: chain.CurrentHeader.Height}) - - chain.App.Commit() - - // set the last header to the current header - // use nil trusted fields - chain.LastHeader = chain.CurrentTMClientHeader() - - // val set changes returned from previous block get applied to the next validators - // of this block. See tendermint spec for details. - chain.Vals = chain.NextVals - chain.NextVals = ibctesting.ApplyValSetChanges(chain.t, chain.Vals, res.ValidatorUpdates) - - // increment the current header - chain.CurrentHeader = tmproto.Header{ - ChainID: chain.ChainID, - Height: chain.App.LastBlockHeight() + 1, - AppHash: chain.App.LastCommitID().Hash, - // NOTE: the time is increased by the coordinator to maintain time synchrony amongst - // chains. - Time: chain.CurrentHeader.Time, - ValidatorsHash: chain.Vals.Hash(), - NextValidatorsHash: chain.NextVals.Hash(), - ProposerAddress: chain.CurrentHeader.ProposerAddress, - } - - chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader}) -} - -// sendMsgs delivers a transaction through the application without returning the result. -func (chain *TestChain) sendMsgs(msgs ...sdk.Msg) error { - _, err := chain.SendMsgs(msgs...) - return err -} - -// SendMsgs delivers a transaction through the application. It updates the senders sequence -// number and updates the TestChain's headers. It returns the result and error if one -// occurred. -func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { - // ensure the chain has the latest time - chain.Coordinator.UpdateTimeForChain(chain) - - _, r, err := app.SignAndDeliverWithoutCommit( - chain.t, - chain.TxConfig, - chain.App.BaseApp, - chain.GetContext().BlockHeader(), - msgs, - chain.ChainID, - []uint64{chain.SenderAccount.GetAccountNumber()}, - []uint64{chain.SenderAccount.GetSequence()}, - chain.SenderPrivKey, - ) - if err != nil { - return nil, err - } - - // NextBlock calls app.Commit() - chain.NextBlock() - - // increment sequence for successful transaction execution - err = chain.SenderAccount.SetSequence(chain.SenderAccount.GetSequence() + 1) - if err != nil { - return nil, err - } - - chain.Coordinator.IncrementTime() - - chain.CaptureIBCEvents(r) - - return r, nil -} - -func (chain *TestChain) CaptureIBCEvents(r *sdk.Result) { - toSend := getSendPackets(r.Events) - if len(toSend) > 0 { - // Keep a queue on the chain that we can relay in tests - chain.PendingSendPackets = append(chain.PendingSendPackets, toSend...) - } -} - -// GetClientState retrieves the client state for the provided clientID. The client is -// expected to exist otherwise testing will fail. -func (chain *TestChain) GetClientState(clientID string) exported.ClientState { - clientState, found := chain.App.IBCKeeper.ClientKeeper.GetClientState(chain.GetContext(), clientID) - require.True(chain.t, found) - - return clientState -} - -// GetConsensusState retrieves the consensus state for the provided clientID and height. -// It will return a success boolean depending on if consensus state exists or not. -func (chain *TestChain) GetConsensusState(clientID string, height exported.Height) (exported.ConsensusState, bool) { - return chain.App.IBCKeeper.ClientKeeper.GetClientConsensusState(chain.GetContext(), clientID, height) -} - -// GetValsAtHeight will return the validator set of the chain at a given height. It will return -// a success boolean depending on if the validator set exists or not at that height. -func (chain *TestChain) GetValsAtHeight(height int64) (*tmtypes.ValidatorSet, bool) { - histInfo, ok := chain.App.StakingKeeper.GetHistoricalInfo(chain.GetContext(), height) - if !ok { - return nil, false - } - - valSet := stakingtypes.Validators(histInfo.Valset) - - tmValidators, err := testutil.ToTmValidators(valSet, sdk.DefaultPowerReduction) - if err != nil { - panic(err) - } - return tmtypes.NewValidatorSet(tmValidators), true -} - -// GetAcknowledgement retrieves an acknowledgement for the provided packet. If the -// acknowledgement does not exist then testing will fail. -func (chain *TestChain) GetAcknowledgement(packet exported.PacketI) []byte { - ack, found := chain.App.IBCKeeper.ChannelKeeper.GetPacketAcknowledgement(chain.GetContext(), packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - require.True(chain.t, found) - - return ack -} - -// GetPrefix returns the prefix for used by a chain in connection creation -func (chain *TestChain) GetPrefix() commitmenttypes.MerklePrefix { - return commitmenttypes.NewMerklePrefix(chain.App.IBCKeeper.ConnectionKeeper.GetCommitmentPrefix().Bytes()) -} - -// ConstructUpdateTMClientHeader will construct a valid 07-tendermint Header to update the -// light client on the source chain. -func (chain *TestChain) ConstructUpdateTMClientHeader(counterparty *TestChain, clientID string) (*ibctm.Header, error) { - return chain.ConstructUpdateTMClientHeaderWithTrustedHeight(counterparty, clientID, clienttypes.ZeroHeight()) -} - -// ConstructUpdateTMClientHeader will construct a valid 07-tendermint Header to update the -// light client on the source chain. -func (chain *TestChain) ConstructUpdateTMClientHeaderWithTrustedHeight(counterparty *TestChain, clientID string, trustedHeight clienttypes.Height) (*ibctm.Header, error) { - header := counterparty.LastHeader - // Relayer must query for LatestHeight on client to get TrustedHeight if the trusted height is not set - if trustedHeight.IsZero() { - trustedHeight = chain.GetClientState(clientID).GetLatestHeight().(clienttypes.Height) - } - var ( - tmTrustedVals *tmtypes.ValidatorSet - ok bool - ) - // Once we get TrustedHeight from client, we must query the validators from the counterparty chain - // If the LatestHeight == LastHeader.Height, then TrustedValidators are current validators - // If LatestHeight < LastHeader.Height, we can query the historical validator set from HistoricalInfo - if trustedHeight == counterparty.LastHeader.GetHeight() { - tmTrustedVals = counterparty.Vals - } else { - // NOTE: We need to get validators from counterparty at height: trustedHeight+1 - // since the last trusted validators for a header at height h - // is the NextValidators at h+1 committed to in header h by - // NextValidatorsHash - tmTrustedVals, ok = counterparty.GetValsAtHeight(int64(trustedHeight.RevisionHeight + 1)) - if !ok { - return nil, errorsmod.Wrapf(ibctm.ErrInvalidHeaderHeight, "could not retrieve trusted validators at trustedHeight: %d", trustedHeight) - } - } - // inject trusted fields into last header - // for now assume revision number is 0 - header.TrustedHeight = trustedHeight - - trustedVals, err := tmTrustedVals.ToProto() - if err != nil { - return nil, err - } - header.TrustedValidators = trustedVals - - return header, nil -} - -// ExpireClient fast forwards the chain's block time by the provided amount of time which will -// expire any clients with a trusting period less than or equal to this amount of time. -func (chain *TestChain) ExpireClient(amount time.Duration) { - chain.Coordinator.IncrementTimeBy(amount) -} - -// CurrentTMClientHeader creates a TM header using the current header parameters -// on the chain. The trusted fields in the header are set to nil. -func (chain *TestChain) CurrentTMClientHeader() *ibctm.Header { - return chain.CreateTMClientHeader(chain.ChainID, chain.CurrentHeader.Height, clienttypes.Height{}, chain.CurrentHeader.Time, chain.Vals, chain.NextVals, nil, chain.Signers) -} - -// CreateTMClientHeader creates a TM header to update the TM client. Args are passed in to allow -// caller flexibility to use params that differ from the chain. -func (chain *TestChain) CreateTMClientHeader(chainID string, blockHeight int64, trustedHeight clienttypes.Height, timestamp time.Time, tmValSet, nextVals, tmTrustedVals *tmtypes.ValidatorSet, signers map[string]tmtypes.PrivValidator) *ibctm.Header { - var ( - valSet *tmproto.ValidatorSet - trustedVals *tmproto.ValidatorSet - ) - require.NotNil(chain.t, tmValSet) - - vsetHash := tmValSet.Hash() - nextValHash := nextVals.Hash() - - tmHeader := tmtypes.Header{ - Version: tmprotoversion.Consensus{Block: tmversion.BlockProtocol, App: 2}, - ChainID: chainID, - Height: blockHeight, - Time: timestamp, - LastBlockID: MakeBlockID(make([]byte, tmhash.Size), 10_000, make([]byte, tmhash.Size)), - LastCommitHash: chain.App.LastCommitID().Hash, - DataHash: tmhash.Sum([]byte("data_hash")), - ValidatorsHash: vsetHash, - NextValidatorsHash: nextValHash, - ConsensusHash: tmhash.Sum([]byte("consensus_hash")), - AppHash: chain.CurrentHeader.AppHash, - LastResultsHash: tmhash.Sum([]byte("last_results_hash")), - EvidenceHash: tmhash.Sum([]byte("evidence_hash")), - ProposerAddress: tmValSet.Proposer.Address, //nolint:staticcheck // SA5011: possible nil pointer dereference - } - - hhash := tmHeader.Hash() - blockID := MakeBlockID(hhash, 3, tmhash.Sum([]byte("part_set"))) - voteSet := tmtypes.NewVoteSet(chainID, blockHeight, 1, tmproto.PrecommitType, tmValSet) - // MakeCommit expects a signer array in the same order as the validator array. - // Thus we iterate over the ordered validator set and construct a signer array - // from the signer map in the same order. - signerArr := make([]tmtypes.PrivValidator, len(tmValSet.Validators)) //nolint:staticcheck - for i, v := range tmValSet.Validators { //nolint:staticcheck - signerArr[i] = signers[v.Address.String()] - } - - commit, err := tmtypes.MakeCommit(blockID, blockHeight, 1, voteSet, signerArr, timestamp) - require.NoError(chain.t, err) - - signedHeader := &tmproto.SignedHeader{ - Header: tmHeader.ToProto(), - Commit: commit.ToProto(), - } - - if tmValSet != nil { //nolint:staticcheck - valSet, err = tmValSet.ToProto() - require.NoError(chain.t, err) - } - - if tmTrustedVals != nil { - trustedVals, err = tmTrustedVals.ToProto() - require.NoError(chain.t, err) - } - - // The trusted fields may be nil. They may be filled before relaying messages to a client. - // The relayer is responsible for querying client and injecting appropriate trusted fields. - return &ibctm.Header{ - SignedHeader: signedHeader, - ValidatorSet: valSet, - TrustedHeight: trustedHeight, - TrustedValidators: trustedVals, - } -} - -// MakeBlockID copied unimported test functions from tmtypes to use them here -func MakeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) tmtypes.BlockID { - return tmtypes.BlockID{ - Hash: hash, - PartSetHeader: tmtypes.PartSetHeader{ - Total: partSetSize, - Hash: partSetHash, - }, - } -} - -// CreatePortCapability binds and claims a capability for the given portID if it does not -// already exist. This function will fail testing on any resulting error. -// NOTE: only creation of a capability for a transfer or mock port is supported -// Other applications must bind to the port in InitGenesis or modify this code. -func (chain *TestChain) CreatePortCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID string) { - // check if the portId is already binded, if not bind it - _, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.PortPath(portID)) - if !ok { - // create capability using the IBC capability keeper - portCap, err := chain.App.ScopedIBCKeeper.NewCapability(chain.GetContext(), host.PortPath(portID)) - require.NoError(chain.t, err) - - // claim capability using the scopedKeeper - err = scopedKeeper.ClaimCapability(chain.GetContext(), portCap, host.PortPath(portID)) - require.NoError(chain.t, err) - } - - chain.NextBlock() -} - -// GetPortCapability returns the port capability for the given portID. The capability must -// exist, otherwise testing will fail. -func (chain *TestChain) GetPortCapability(portID string) *capabilitytypes.Capability { - portCap, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.PortPath(portID)) - require.True(chain.t, ok) - - return portCap -} - -// CreateChannelCapability binds and claims a capability for the given portID and channelID -// if it does not already exist. This function will fail testing on any resulting error. The -// scoped keeper passed in will claim the new capability. -func (chain *TestChain) CreateChannelCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID, channelID string) { - capName := host.ChannelCapabilityPath(portID, channelID) - // check if the portId is already binded, if not bind it - _, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), capName) - if !ok { - portCap, err := chain.App.ScopedIBCKeeper.NewCapability(chain.GetContext(), capName) - require.NoError(chain.t, err) - err = scopedKeeper.ClaimCapability(chain.GetContext(), portCap, capName) - require.NoError(chain.t, err) - } - - chain.NextBlock() -} - -// GetChannelCapability returns the channel capability for the given portID and channelID. -// The capability must exist, otherwise testing will fail. -func (chain *TestChain) GetChannelCapability(portID, channelID string) *capabilitytypes.Capability { - chanCap, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.ChannelCapabilityPath(portID, channelID)) - require.True(chain.t, ok) - - return chanCap -} - -// GetTimeoutHeight is a convenience function which returns a IBC packet timeout height -// to be used for testing. It returns the current IBC height + 100 blocks -func (chain *TestChain) GetTimeoutHeight() clienttypes.Height { - return clienttypes.NewHeight(clienttypes.ParseChainID(chain.ChainID), uint64(chain.GetContext().BlockHeight())+100) -} - -func (chain *TestChain) Balance(acc sdk.AccAddress, denom string) sdk.Coin { - return chain.App.BankKeeper.GetBalance(chain.GetContext(), acc, denom) -} - -func (chain *TestChain) AllBalances(acc sdk.AccAddress) sdk.Coins { - return chain.App.BankKeeper.GetAllBalances(chain.GetContext(), acc) -} diff --git a/x/wasm/ibctesting/coordinator.go b/x/wasm/ibctesting/coordinator.go deleted file mode 100644 index 4f691ff..0000000 --- a/x/wasm/ibctesting/coordinator.go +++ /dev/null @@ -1,311 +0,0 @@ -package ibctesting - -import ( - "fmt" - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/require" - - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" -) - -var ( - TimeIncrement = time.Second * 5 - globalStartTime = time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC) -) - -// Coordinator is a testing struct which contains N TestChain's. It handles keeping all chains -// in sync with regards to time. -type Coordinator struct { - t *testing.T - - CurrentTime time.Time - Chains map[string]*TestChain -} - -// NewCoordinator initializes Coordinator with N TestChain's -func NewCoordinator(t *testing.T, n int, opts ...[]wasmkeeper.Option) *Coordinator { - t.Helper() - chains := make(map[string]*TestChain) - coord := &Coordinator{ - t: t, - CurrentTime: globalStartTime, - } - - for i := 1; i <= n; i++ { - chainID := GetChainID(i) - var x []wasmkeeper.Option - if len(opts) > (i - 1) { - x = opts[i-1] - } - chains[chainID] = NewTestChain(t, coord, chainID, x...) - } - coord.Chains = chains - - return coord -} - -// IncrementTime iterates through all the TestChain's and increments their current header time -// by 5 seconds. -// -// CONTRACT: this function must be called after every Commit on any TestChain. -func (coord *Coordinator) IncrementTime() { - coord.IncrementTimeBy(TimeIncrement) -} - -// IncrementTimeBy iterates through all the TestChain's and increments their current header time -// by specified time. -func (coord *Coordinator) IncrementTimeBy(increment time.Duration) { - coord.CurrentTime = coord.CurrentTime.Add(increment).UTC() - coord.UpdateTime() -} - -// UpdateTime updates all clocks for the TestChains to the current global time. -func (coord *Coordinator) UpdateTime() { - for _, chain := range coord.Chains { - coord.UpdateTimeForChain(chain) - } -} - -// UpdateTimeForChain updates the clock for a specific chain. -func (coord *Coordinator) UpdateTimeForChain(chain *TestChain) { - chain.CurrentHeader.Time = coord.CurrentTime.UTC() - chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader}) -} - -// Setup constructs a TM client, connection, and channel on both chains provided. It will -// fail if any error occurs. The clientID's, TestConnections, and TestChannels are returned -// for both chains. The channels created are connected to the ibc-transfer application. -func (coord *Coordinator) Setup(path *Path) { - coord.SetupConnections(path) - - // channels can also be referenced through the returned connections - coord.CreateChannels(path) -} - -// SetupClients is a helper function to create clients on both chains. It assumes the -// caller does not anticipate any errors. -func (coord *Coordinator) SetupClients(path *Path) { - err := path.EndpointA.CreateClient() - require.NoError(coord.t, err) - - err = path.EndpointB.CreateClient() - require.NoError(coord.t, err) -} - -// SetupClientConnections is a helper function to create clients and the appropriate -// connections on both the source and counterparty chain. It assumes the caller does not -// anticipate any errors. -func (coord *Coordinator) SetupConnections(path *Path) { - coord.SetupClients(path) - - coord.CreateConnections(path) -} - -// CreateConnection constructs and executes connection handshake messages in order to create -// OPEN channels on chainA and chainB. The connection information of for chainA and chainB -// are returned within a TestConnection struct. The function expects the connections to be -// successfully opened otherwise testing will fail. -func (coord *Coordinator) CreateConnections(path *Path) { - err := path.EndpointA.ConnOpenInit() - require.NoError(coord.t, err) - - err = path.EndpointB.ConnOpenTry() - require.NoError(coord.t, err) - - err = path.EndpointA.ConnOpenAck() - require.NoError(coord.t, err) - - err = path.EndpointB.ConnOpenConfirm() - require.NoError(coord.t, err) - - // ensure counterparty is up to date - err = path.EndpointA.UpdateClient() - require.NoError(coord.t, err) -} - -// CreateMockChannels constructs and executes channel handshake messages to create OPEN -// channels that use a mock application module that returns nil on all callbacks. This -// function is expects the channels to be successfully opened otherwise testing will -// fail. -func (coord *Coordinator) CreateMockChannels(path *Path) { - path.EndpointA.ChannelConfig.PortID = ibctesting.MockPort - path.EndpointB.ChannelConfig.PortID = ibctesting.MockPort - - coord.CreateChannels(path) -} - -// CreateTransferChannels constructs and executes channel handshake messages to create OPEN -// ibc-transfer channels on chainA and chainB. The function expects the channels to be -// successfully opened otherwise testing will fail. -func (coord *Coordinator) CreateTransferChannels(path *Path) { - path.EndpointA.ChannelConfig.PortID = ibctesting.TransferPort - path.EndpointB.ChannelConfig.PortID = ibctesting.TransferPort - - coord.CreateChannels(path) -} - -// CreateChannel constructs and executes channel handshake messages in order to create -// OPEN channels on chainA and chainB. The function expects the channels to be successfully -// opened otherwise testing will fail. -func (coord *Coordinator) CreateChannels(path *Path) { - err := path.EndpointA.ChanOpenInit() - require.NoError(coord.t, err) - - err = path.EndpointB.ChanOpenTry() - require.NoError(coord.t, err) - - err = path.EndpointA.ChanOpenAck() - require.NoError(coord.t, err) - - err = path.EndpointB.ChanOpenConfirm() - require.NoError(coord.t, err) - - // ensure counterparty is up to date - err = path.EndpointA.UpdateClient() - require.NoError(coord.t, err) -} - -// GetChain returns the TestChain using the given chainID and returns an error if it does -// not exist. -func (coord *Coordinator) GetChain(chainID string) *TestChain { - chain, found := coord.Chains[chainID] - require.True(coord.t, found, fmt.Sprintf("%s chain does not exist", chainID)) - return chain -} - -// GetChainID returns the chainID used for the provided index. -func GetChainID(index int) string { - return ibctesting.GetChainID(index) -} - -// CommitBlock commits a block on the provided indexes and then increments the global time. -// -// CONTRACT: the passed in list of indexes must not contain duplicates -func (coord *Coordinator) CommitBlock(chains ...*TestChain) { - for _, chain := range chains { - chain.NextBlock() - } - coord.IncrementTime() -} - -// CommitNBlocks commits n blocks to state and updates the block height by 1 for each commit. -func (coord *Coordinator) CommitNBlocks(chain *TestChain, n uint64) { - for i := uint64(0); i < n; i++ { - chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader}) - chain.NextBlock() - coord.IncrementTime() - } -} - -// ConnOpenInitOnBothChains initializes a connection on both endpoints with the state INIT -// using the OpenInit handshake call. -func (coord *Coordinator) ConnOpenInitOnBothChains(path *Path) error { - if err := path.EndpointA.ConnOpenInit(); err != nil { - return err - } - - if err := path.EndpointB.ConnOpenInit(); err != nil { - return err - } - - if err := path.EndpointA.UpdateClient(); err != nil { - return err - } - - err := path.EndpointB.UpdateClient() - - return err -} - -// ChanOpenInitOnBothChains initializes a channel on the source chain and counterparty chain -// with the state INIT using the OpenInit handshake call. -func (coord *Coordinator) ChanOpenInitOnBothChains(path *Path) error { - // NOTE: only creation of a capability for a transfer or mock port is supported - // Other applications must bind to the port in InitGenesis or modify this code. - - if err := path.EndpointA.ChanOpenInit(); err != nil { - return err - } - - if err := path.EndpointB.ChanOpenInit(); err != nil { - return err - } - - if err := path.EndpointA.UpdateClient(); err != nil { - return err - } - - err := path.EndpointB.UpdateClient() - - return err -} - -// RelayAndAckPendingPackets sends pending packages from path.EndpointA to the counterparty chain and acks -func (coord *Coordinator) RelayAndAckPendingPackets(path *Path) error { - // get all the packet to relay src->dest - src := path.EndpointA - coord.t.Logf("Relay: %d Packets A->B, %d Packets B->A\n", len(src.Chain.PendingSendPackets), len(path.EndpointB.Chain.PendingSendPackets)) - for i, v := range src.Chain.PendingSendPackets { - err := path.RelayPacket(v, nil) - if err != nil { - return err - } - src.Chain.PendingSendPackets = append(src.Chain.PendingSendPackets[0:i], src.Chain.PendingSendPackets[i+1:]...) - } - - src = path.EndpointB - for i, v := range src.Chain.PendingSendPackets { - err := path.RelayPacket(v, nil) - if err != nil { - return err - } - src.Chain.PendingSendPackets = append(src.Chain.PendingSendPackets[0:i], src.Chain.PendingSendPackets[i+1:]...) - } - return nil -} - -// TimeoutPendingPackets returns the package to source chain to let the IBC app revert any operation. -// from A to A -func (coord *Coordinator) TimeoutPendingPackets(path *Path) error { - src := path.EndpointA - dest := path.EndpointB - - toSend := src.Chain.PendingSendPackets - coord.t.Logf("Timeout %d Packets A->A\n", len(toSend)) - - if err := src.UpdateClient(); err != nil { - return err - } - // Increment time and commit block so that 5 second delay period passes between send and receive - coord.IncrementTime() - coord.CommitBlock(src.Chain, dest.Chain) - for _, packet := range toSend { - // get proof of packet unreceived on dest - packetKey := host.PacketReceiptKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - proofUnreceived, proofHeight := dest.QueryProof(packetKey) - timeoutMsg := channeltypes.NewMsgTimeout(packet, packet.Sequence, proofUnreceived, proofHeight, src.Chain.SenderAccount.GetAddress().String()) - err := src.Chain.sendMsgs(timeoutMsg) - if err != nil { - return err - } - } - src.Chain.PendingSendPackets = nil - return nil -} - -// CloseChannel close channel on both sides -func (coord *Coordinator) CloseChannel(path *Path) { - err := path.EndpointA.ChanCloseInit() - require.NoError(coord.t, err) - coord.IncrementTime() - err = path.EndpointB.UpdateClient() - require.NoError(coord.t, err) - err = path.EndpointB.ChanCloseConfirm() - require.NoError(coord.t, err) -} diff --git a/x/wasm/ibctesting/endpoint.go b/x/wasm/ibctesting/endpoint.go deleted file mode 100644 index 4eb47ba..0000000 --- a/x/wasm/ibctesting/endpoint.go +++ /dev/null @@ -1,657 +0,0 @@ -package ibctesting - -import ( - "fmt" - "strings" - - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - commitmenttypes "github.com/cosmos/ibc-go/v7/modules/core/23-commitment/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - "github.com/cosmos/ibc-go/v7/modules/core/exported" - ibctm "github.com/cosmos/ibc-go/v7/modules/light-clients/07-tendermint" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/require" -) - -// Endpoint is a which represents a channel endpoint and its associated -// client and connections. It contains client, connection, and channel -// configuration parameters. Endpoint functions will utilize the parameters -// set in the configuration structs when executing IBC messages. -type Endpoint struct { - Chain *TestChain - Counterparty *Endpoint - ClientID string - ConnectionID string - ChannelID string - - ClientConfig ibctesting.ClientConfig - ConnectionConfig *ibctesting.ConnectionConfig - ChannelConfig *ibctesting.ChannelConfig -} - -// NewEndpoint constructs a new endpoint without the counterparty. -// CONTRACT: the counterparty endpoint must be set by the caller. -func NewEndpoint( - chain *TestChain, clientConfig ibctesting.ClientConfig, - connectionConfig *ibctesting.ConnectionConfig, channelConfig *ibctesting.ChannelConfig, -) *Endpoint { - return &Endpoint{ - Chain: chain, - ClientConfig: clientConfig, - ConnectionConfig: connectionConfig, - ChannelConfig: channelConfig, - } -} - -// NewDefaultEndpoint constructs a new endpoint using default values. -// CONTRACT: the counterparty endpoitn must be set by the caller. -func NewDefaultEndpoint(chain *TestChain) *Endpoint { - return &Endpoint{ - Chain: chain, - ClientConfig: ibctesting.NewTendermintConfig(), - ConnectionConfig: ibctesting.NewConnectionConfig(), - ChannelConfig: ibctesting.NewChannelConfig(), - } -} - -// QueryProof queries proof associated with this endpoint using the lastest client state -// height on the counterparty chain. -func (endpoint *Endpoint) QueryProof(key []byte) ([]byte, clienttypes.Height) { - // obtain the counterparty client representing the chain associated with the endpoint - clientState := endpoint.Counterparty.Chain.GetClientState(endpoint.Counterparty.ClientID) - - // query proof on the counterparty using the latest height of the IBC client - return endpoint.QueryProofAtHeight(key, clientState.GetLatestHeight().GetRevisionHeight()) -} - -// QueryProofAtHeight queries proof associated with this endpoint using the proof height -// provided -func (endpoint *Endpoint) QueryProofAtHeight(key []byte, height uint64) ([]byte, clienttypes.Height) { - // query proof on the counterparty using the latest height of the IBC client - return endpoint.Chain.QueryProofAtHeight(key, int64(height)) -} - -// CreateClient creates an IBC client on the endpoint. It will update the -// clientID for the endpoint if the message is successfully executed. -// NOTE: a solo machine client will be created with an empty diversifier. -func (endpoint *Endpoint) CreateClient() (err error) { - // ensure counterparty has committed state - endpoint.Chain.Coordinator.CommitBlock(endpoint.Counterparty.Chain) - - var ( - clientState exported.ClientState - consensusState exported.ConsensusState - ) - - switch endpoint.ClientConfig.GetClientType() { - case exported.Tendermint: - tmConfig, ok := endpoint.ClientConfig.(*ibctesting.TendermintConfig) - require.True(endpoint.Chain.t, ok) - - height := endpoint.Counterparty.Chain.LastHeader.GetHeight().(clienttypes.Height) - clientState = ibctm.NewClientState( - endpoint.Counterparty.Chain.ChainID, tmConfig.TrustLevel, tmConfig.TrustingPeriod, tmConfig.UnbondingPeriod, tmConfig.MaxClockDrift, - height, commitmenttypes.GetSDKSpecs(), ibctesting.UpgradePath) - consensusState = endpoint.Counterparty.Chain.LastHeader.ConsensusState() - case exported.Solomachine: - // TODO - // solo := NewSolomachine(chain.t, endpoint.Chain.Codec, clientID, "", 1) - // clientState = solo.ClientState() - // consensusState = solo.ConsensusState() - - default: - err = fmt.Errorf("client type %s is not supported", endpoint.ClientConfig.GetClientType()) - } - - if err != nil { - return err - } - - msg, err := clienttypes.NewMsgCreateClient( - clientState, consensusState, endpoint.Chain.SenderAccount.GetAddress().String(), - ) - require.NoError(endpoint.Chain.t, err) - - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - endpoint.ClientID, err = ibctesting.ParseClientIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - - return nil -} - -// UpdateClient updates the IBC client associated with the endpoint. -func (endpoint *Endpoint) UpdateClient() (err error) { - // ensure counterparty has committed state - endpoint.Chain.Coordinator.CommitBlock(endpoint.Counterparty.Chain) - - var header exported.ClientMessage - - switch endpoint.ClientConfig.GetClientType() { - case exported.Tendermint: - header, err = endpoint.Chain.ConstructUpdateTMClientHeader(endpoint.Counterparty.Chain, endpoint.ClientID) - - default: - err = fmt.Errorf("client type %s is not supported", endpoint.ClientConfig.GetClientType()) - } - - if err != nil { - return err - } - - msg, err := clienttypes.NewMsgUpdateClient( - endpoint.ClientID, header, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - require.NoError(endpoint.Chain.t, err) - - return endpoint.Chain.sendMsgs(msg) -} - -// UpgradeChain will upgrade a chain's chainID to the next revision number. -// It will also update the counterparty client. -// TODO: implement actual upgrade chain functionality via scheduling an upgrade -// and upgrading the client via MsgUpgradeClient -// see reference https://github.com/cosmos/ibc-go/pull/1169 -func (endpoint *Endpoint) UpgradeChain() error { - if strings.TrimSpace(endpoint.Counterparty.ClientID) == "" { - return fmt.Errorf("cannot upgrade chain if there is no counterparty client") - } - - clientState := endpoint.Counterparty.GetClientState().(*ibctm.ClientState) - - // increment revision number in chainID - - oldChainID := clientState.ChainId - if !clienttypes.IsRevisionFormat(oldChainID) { - return fmt.Errorf("cannot upgrade chain which is not of revision format: %s", oldChainID) - } - - revisionNumber := clienttypes.ParseChainID(oldChainID) - newChainID, err := clienttypes.SetRevisionNumber(oldChainID, revisionNumber+1) - if err != nil { - return err - } - - // update chain - baseapp.SetChainID(newChainID)(endpoint.Chain.App.BaseApp) - endpoint.Chain.ChainID = newChainID - endpoint.Chain.CurrentHeader.ChainID = newChainID - endpoint.Chain.NextBlock() // commit changes - - // update counterparty client manually - clientState.ChainId = newChainID - clientState.LatestHeight = clienttypes.NewHeight(revisionNumber+1, clientState.LatestHeight.GetRevisionHeight()+1) - endpoint.Counterparty.SetClientState(clientState) - - consensusState := &ibctm.ConsensusState{ - Timestamp: endpoint.Chain.LastHeader.GetTime(), - Root: commitmenttypes.NewMerkleRoot(endpoint.Chain.LastHeader.Header.GetAppHash()), - NextValidatorsHash: endpoint.Chain.LastHeader.Header.NextValidatorsHash, - } - endpoint.Counterparty.SetConsensusState(consensusState, clientState.GetLatestHeight()) - - // ensure the next update isn't identical to the one set in state - endpoint.Chain.Coordinator.IncrementTime() - endpoint.Chain.NextBlock() - - if err = endpoint.Counterparty.UpdateClient(); err != nil { - return err - } - - return nil -} - -// ConnOpenInit will construct and execute a MsgConnectionOpenInit on the associated endpoint. -func (endpoint *Endpoint) ConnOpenInit() error { - msg := connectiontypes.NewMsgConnectionOpenInit( - endpoint.ClientID, - endpoint.Counterparty.ClientID, - endpoint.Counterparty.Chain.GetPrefix(), ibctesting.DefaultOpenInitVersion, endpoint.ConnectionConfig.DelayPeriod, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - endpoint.ConnectionID, err = ibctesting.ParseConnectionIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - - return nil -} - -// ConnOpenTry will construct and execute a MsgConnectionOpenTry on the associated endpoint. -func (endpoint *Endpoint) ConnOpenTry() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - counterpartyClient, proofClient, proofConsensus, consensusHeight, proofInit, proofHeight := endpoint.QueryConnectionHandshakeProof() - - msg := connectiontypes.NewMsgConnectionOpenTry( - endpoint.ClientID, endpoint.Counterparty.ConnectionID, endpoint.Counterparty.ClientID, - counterpartyClient, endpoint.Counterparty.Chain.GetPrefix(), []*connectiontypes.Version{ibctesting.ConnectionVersion}, endpoint.ConnectionConfig.DelayPeriod, - proofInit, proofClient, proofConsensus, - proofHeight, consensusHeight, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - if endpoint.ConnectionID == "" { - endpoint.ConnectionID, err = ibctesting.ParseConnectionIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - } - - return nil -} - -// ConnOpenAck will construct and execute a MsgConnectionOpenAck on the associated endpoint. -func (endpoint *Endpoint) ConnOpenAck() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - counterpartyClient, proofClient, proofConsensus, consensusHeight, proofTry, proofHeight := endpoint.QueryConnectionHandshakeProof() - - msg := connectiontypes.NewMsgConnectionOpenAck( - endpoint.ConnectionID, endpoint.Counterparty.ConnectionID, counterpartyClient, // testing doesn't use flexible selection - proofTry, proofClient, proofConsensus, - proofHeight, consensusHeight, - ibctesting.ConnectionVersion, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// ConnOpenConfirm will construct and execute a MsgConnectionOpenConfirm on the associated endpoint. -func (endpoint *Endpoint) ConnOpenConfirm() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - connectionKey := host.ConnectionKey(endpoint.Counterparty.ConnectionID) - proof, height := endpoint.Counterparty.Chain.QueryProof(connectionKey) - - msg := connectiontypes.NewMsgConnectionOpenConfirm( - endpoint.ConnectionID, - proof, height, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// QueryConnectionHandshakeProof returns all the proofs necessary to execute OpenTry or Open Ack of -// the connection handshakes. It returns the counterparty client state, proof of the counterparty -// client state, proof of the counterparty consensus state, the consensus state height, proof of -// the counterparty connection, and the proof height for all the proofs returned. -func (endpoint *Endpoint) QueryConnectionHandshakeProof() ( - clientState exported.ClientState, proofClient, - proofConsensus []byte, consensusHeight clienttypes.Height, - proofConnection []byte, proofHeight clienttypes.Height, -) { - // obtain the client state on the counterparty chain - clientState = endpoint.Counterparty.Chain.GetClientState(endpoint.Counterparty.ClientID) - - // query proof for the client state on the counterparty - clientKey := host.FullClientStateKey(endpoint.Counterparty.ClientID) - proofClient, proofHeight = endpoint.Counterparty.QueryProof(clientKey) - - consensusHeight = clientState.GetLatestHeight().(clienttypes.Height) - - // query proof for the consensus state on the counterparty - consensusKey := host.FullConsensusStateKey(endpoint.Counterparty.ClientID, consensusHeight) - proofConsensus, _ = endpoint.Counterparty.QueryProofAtHeight(consensusKey, proofHeight.GetRevisionHeight()) - - // query proof for the connection on the counterparty - connectionKey := host.ConnectionKey(endpoint.Counterparty.ConnectionID) - proofConnection, _ = endpoint.Counterparty.QueryProofAtHeight(connectionKey, proofHeight.GetRevisionHeight()) - - return -} - -// ChanOpenInit will construct and execute a MsgChannelOpenInit on the associated endpoint. -func (endpoint *Endpoint) ChanOpenInit() error { - msg := channeltypes.NewMsgChannelOpenInit( - endpoint.ChannelConfig.PortID, - endpoint.ChannelConfig.Version, endpoint.ChannelConfig.Order, []string{endpoint.ConnectionID}, - endpoint.Counterparty.ChannelConfig.PortID, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - endpoint.ChannelID, err = ibctesting.ParseChannelIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - - // update version to selected app version - // NOTE: this update must be performed after SendMsgs() - endpoint.ChannelConfig.Version = endpoint.GetChannel().Version - - return nil -} - -// ChanOpenTry will construct and execute a MsgChannelOpenTry on the associated endpoint. -func (endpoint *Endpoint) ChanOpenTry() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) - proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) - - msg := channeltypes.NewMsgChannelOpenTry( - endpoint.ChannelConfig.PortID, - endpoint.ChannelConfig.Version, endpoint.ChannelConfig.Order, []string{endpoint.ConnectionID}, - endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID, endpoint.Counterparty.ChannelConfig.Version, - proof, height, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - res, err := endpoint.Chain.SendMsgs(msg) - if err != nil { - return err - } - - if endpoint.ChannelID == "" { - endpoint.ChannelID, err = ibctesting.ParseChannelIDFromEvents(res.GetEvents()) - require.NoError(endpoint.Chain.t, err) - } - - // update version to selected app version - // NOTE: this update must be performed after the endpoint channelID is set - endpoint.ChannelConfig.Version = endpoint.GetChannel().Version - - return nil -} - -// ChanOpenAck will construct and execute a MsgChannelOpenAck on the associated endpoint. -func (endpoint *Endpoint) ChanOpenAck() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) - proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) - - msg := channeltypes.NewMsgChannelOpenAck( - endpoint.ChannelConfig.PortID, endpoint.ChannelID, - endpoint.Counterparty.ChannelID, endpoint.Counterparty.ChannelConfig.Version, // testing doesn't use flexible selection - proof, height, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - if err := endpoint.Chain.sendMsgs(msg); err != nil { - return err - } - - endpoint.ChannelConfig.Version = endpoint.GetChannel().Version - return nil -} - -// ChanOpenConfirm will construct and execute a MsgChannelOpenConfirm on the associated endpoint. -func (endpoint *Endpoint) ChanOpenConfirm() error { - err := endpoint.UpdateClient() - require.NoError(endpoint.Chain.t, err) - - channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) - proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey) - - msg := channeltypes.NewMsgChannelOpenConfirm( - endpoint.ChannelConfig.PortID, endpoint.ChannelID, - proof, height, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// ChanCloseInit will construct and execute a MsgChannelCloseInit on the associated endpoint. -// -// NOTE: does not work with ibc-transfer module -func (endpoint *Endpoint) ChanCloseInit() error { - msg := channeltypes.NewMsgChannelCloseInit( - endpoint.ChannelConfig.PortID, endpoint.ChannelID, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// ChanCloseConfirm will construct and execute a NewMsgChannelCloseConfirm on the associated endpoint. -func (endpoint *Endpoint) ChanCloseConfirm() error { - channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID) - proof, proofHeight := endpoint.Counterparty.QueryProof(channelKey) - - msg := channeltypes.NewMsgChannelCloseConfirm( - endpoint.ChannelConfig.PortID, endpoint.ChannelID, - proof, proofHeight, - endpoint.Chain.SenderAccount.GetAddress().String(), - ) - return endpoint.Chain.sendMsgs(msg) -} - -// SendPacket sends a packet through the channel keeper using the associated endpoint -// The counterparty client is updated so proofs can be sent to the counterparty chain. -// The packet sequence generated for the packet to be sent is returned. An error -// is returned if one occurs. -func (endpoint *Endpoint) SendPacket( - timeoutHeight clienttypes.Height, - timeoutTimestamp uint64, - data []byte, -) (uint64, error) { - channelCap := endpoint.Chain.GetChannelCapability(endpoint.ChannelConfig.PortID, endpoint.ChannelID) - - // no need to send message, acting as a module - sequence, err := endpoint.Chain.App.IBCKeeper.ChannelKeeper.SendPacket(endpoint.Chain.GetContext(), channelCap, endpoint.ChannelConfig.PortID, endpoint.ChannelID, timeoutHeight, timeoutTimestamp, data) - if err != nil { - return 0, err - } - - // commit changes since no message was sent - endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain) - - err = endpoint.Counterparty.UpdateClient() - if err != nil { - return 0, err - } - - return sequence, nil -} - -// RecvPacket receives a packet on the associated endpoint. -// The counterparty client is updated. -func (endpoint *Endpoint) RecvPacket(packet channeltypes.Packet) error { - _, err := endpoint.RecvPacketWithResult(packet) - if err != nil { - return err - } - - return nil -} - -// RecvPacketWithResult receives a packet on the associated endpoint and the result -// of the transaction is returned. The counterparty client is updated. -func (endpoint *Endpoint) RecvPacketWithResult(packet channeltypes.Packet) (*sdk.Result, error) { - // get proof of packet commitment on source - packetKey := host.PacketCommitmentKey(packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) - proof, proofHeight := endpoint.Counterparty.Chain.QueryProof(packetKey) - - recvMsg := channeltypes.NewMsgRecvPacket(packet, proof, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String()) - - // receive on counterparty and update source client - res, err := endpoint.Chain.SendMsgs(recvMsg) - if err != nil { - return nil, err - } - - if err := endpoint.Counterparty.UpdateClient(); err != nil { - return nil, err - } - - return res, nil -} - -// WriteAcknowledgement writes an acknowledgement on the channel associated with the endpoint. -// The counterparty client is updated. -func (endpoint *Endpoint) WriteAcknowledgement(ack exported.Acknowledgement, packet exported.PacketI) error { - channelCap := endpoint.Chain.GetChannelCapability(packet.GetDestPort(), packet.GetDestChannel()) - - // no need to send message, acting as a handler - err := endpoint.Chain.App.IBCKeeper.ChannelKeeper.WriteAcknowledgement(endpoint.Chain.GetContext(), channelCap, packet, ack) - if err != nil { - return err - } - - // commit changes since no message was sent - endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain) - - return endpoint.Counterparty.UpdateClient() -} - -// AcknowledgePacket sends a MsgAcknowledgement to the channel associated with the endpoint. -func (endpoint *Endpoint) AcknowledgePacket(packet channeltypes.Packet, ack []byte) error { - // get proof of acknowledgement on counterparty - packetKey := host.PacketAcknowledgementKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - proof, proofHeight := endpoint.Counterparty.QueryProof(packetKey) - - ackMsg := channeltypes.NewMsgAcknowledgement(packet, ack, proof, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String()) - - return endpoint.Chain.sendMsgs(ackMsg) -} - -// TimeoutPacket sends a MsgTimeout to the channel associated with the endpoint. -func (endpoint *Endpoint) TimeoutPacket(packet channeltypes.Packet) error { - // get proof for timeout based on channel order - var packetKey []byte - - switch endpoint.ChannelConfig.Order { - case channeltypes.ORDERED: - packetKey = host.NextSequenceRecvKey(packet.GetDestPort(), packet.GetDestChannel()) - case channeltypes.UNORDERED: - packetKey = host.PacketReceiptKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - default: - return fmt.Errorf("unsupported order type %s", endpoint.ChannelConfig.Order) - } - - proof, proofHeight := endpoint.Counterparty.QueryProof(packetKey) - nextSeqRecv, found := endpoint.Counterparty.Chain.App.IBCKeeper.ChannelKeeper.GetNextSequenceRecv(endpoint.Counterparty.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID) - require.True(endpoint.Chain.t, found) - - timeoutMsg := channeltypes.NewMsgTimeout( - packet, nextSeqRecv, - proof, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String(), - ) - - return endpoint.Chain.sendMsgs(timeoutMsg) -} - -// TimeoutOnClose sends a MsgTimeoutOnClose to the channel associated with the endpoint. -func (endpoint *Endpoint) TimeoutOnClose(packet channeltypes.Packet) error { - // get proof for timeout based on channel order - var packetKey []byte - - switch endpoint.ChannelConfig.Order { - case channeltypes.ORDERED: - packetKey = host.NextSequenceRecvKey(packet.GetDestPort(), packet.GetDestChannel()) - case channeltypes.UNORDERED: - packetKey = host.PacketReceiptKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence()) - default: - return fmt.Errorf("unsupported order type %s", endpoint.ChannelConfig.Order) - } - - proof, proofHeight := endpoint.Counterparty.QueryProof(packetKey) - - channelKey := host.ChannelKey(packet.GetDestPort(), packet.GetDestChannel()) - proofClosed, _ := endpoint.Counterparty.QueryProof(channelKey) - - nextSeqRecv, found := endpoint.Counterparty.Chain.App.IBCKeeper.ChannelKeeper.GetNextSequenceRecv(endpoint.Counterparty.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID) - require.True(endpoint.Chain.t, found) - - timeoutOnCloseMsg := channeltypes.NewMsgTimeoutOnClose( - packet, nextSeqRecv, - proof, proofClosed, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String(), - ) - - return endpoint.Chain.sendMsgs(timeoutOnCloseMsg) -} - -// SetChannelClosed sets a channel state to CLOSED. -func (endpoint *Endpoint) SetChannelClosed() error { - channel := endpoint.GetChannel() - - channel.State = channeltypes.CLOSED - endpoint.Chain.App.IBCKeeper.ChannelKeeper.SetChannel(endpoint.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID, channel) - - endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain) - - return endpoint.Counterparty.UpdateClient() -} - -// GetClientState retrieves the Client State for this endpoint. The -// client state is expected to exist otherwise testing will fail. -func (endpoint *Endpoint) GetClientState() exported.ClientState { - return endpoint.Chain.GetClientState(endpoint.ClientID) -} - -// SetClientState sets the client state for this endpoint. -func (endpoint *Endpoint) SetClientState(clientState exported.ClientState) { - endpoint.Chain.App.IBCKeeper.ClientKeeper.SetClientState(endpoint.Chain.GetContext(), endpoint.ClientID, clientState) -} - -// GetConsensusState retrieves the Consensus State for this endpoint at the provided height. -// The consensus state is expected to exist otherwise testing will fail. -func (endpoint *Endpoint) GetConsensusState(height exported.Height) exported.ConsensusState { - consensusState, found := endpoint.Chain.GetConsensusState(endpoint.ClientID, height) - require.True(endpoint.Chain.t, found) - - return consensusState -} - -// SetConsensusState sets the consensus state for this endpoint. -func (endpoint *Endpoint) SetConsensusState(consensusState exported.ConsensusState, height exported.Height) { - endpoint.Chain.App.IBCKeeper.ClientKeeper.SetClientConsensusState(endpoint.Chain.GetContext(), endpoint.ClientID, height, consensusState) -} - -// GetConnection retrieves an IBC Connection for the endpoint. The -// connection is expected to exist otherwise testing will fail. -func (endpoint *Endpoint) GetConnection() connectiontypes.ConnectionEnd { - connection, found := endpoint.Chain.App.IBCKeeper.ConnectionKeeper.GetConnection(endpoint.Chain.GetContext(), endpoint.ConnectionID) - require.True(endpoint.Chain.t, found) - - return connection -} - -// SetConnection sets the connection for this endpoint. -func (endpoint *Endpoint) SetConnection(connection connectiontypes.ConnectionEnd) { - endpoint.Chain.App.IBCKeeper.ConnectionKeeper.SetConnection(endpoint.Chain.GetContext(), endpoint.ConnectionID, connection) -} - -// GetChannel retrieves an IBC Channel for the endpoint. The channel -// is expected to exist otherwise testing will fail. -func (endpoint *Endpoint) GetChannel() channeltypes.Channel { - channel, found := endpoint.Chain.App.IBCKeeper.ChannelKeeper.GetChannel(endpoint.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID) - require.True(endpoint.Chain.t, found) - - return channel -} - -// SetChannel sets the channel for this endpoint. -func (endpoint *Endpoint) SetChannel(channel channeltypes.Channel) { - endpoint.Chain.App.IBCKeeper.ChannelKeeper.SetChannel(endpoint.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID, channel) -} - -// QueryClientStateProof performs and abci query for a client stat associated -// with this endpoint and returns the ClientState along with the proof. -func (endpoint *Endpoint) QueryClientStateProof() (exported.ClientState, []byte) { - // retrieve client state to provide proof for - clientState := endpoint.GetClientState() - - clientKey := host.FullClientStateKey(endpoint.ClientID) - proofClient, _ := endpoint.QueryProof(clientKey) - - return clientState, proofClient -} diff --git a/x/wasm/ibctesting/event_utils.go b/x/wasm/ibctesting/event_utils.go deleted file mode 100644 index a376901..0000000 --- a/x/wasm/ibctesting/event_utils.go +++ /dev/null @@ -1,118 +0,0 @@ -package ibctesting - -import ( - "encoding/hex" - "fmt" - "strconv" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" - - abci "github.com/cometbft/cometbft/abci/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" -) - -func getSendPackets(evts []abci.Event) []channeltypes.Packet { - var res []channeltypes.Packet - for _, evt := range evts { - if evt.Type == channeltypes.EventTypeSendPacket { - packet := parsePacketFromEvent(evt) - res = append(res, packet) - } - } - return res -} - -// Used for various debug statements above when needed... do not remove -// func showEvent(evt abci.Event) { -// fmt.Printf("evt.Type: %s\n", evt.Type) -// for _, attr := range evt.Attributes { -// fmt.Printf(" %s = %s\n", string(attr.Key), string(attr.Value)) -// } -//} - -func parsePacketFromEvent(evt abci.Event) channeltypes.Packet { - return channeltypes.Packet{ - Sequence: getUintField(evt, channeltypes.AttributeKeySequence), - SourcePort: getField(evt, channeltypes.AttributeKeySrcPort), - SourceChannel: getField(evt, channeltypes.AttributeKeySrcChannel), - DestinationPort: getField(evt, channeltypes.AttributeKeyDstPort), - DestinationChannel: getField(evt, channeltypes.AttributeKeyDstChannel), - Data: getHexField(evt, channeltypes.AttributeKeyDataHex), - TimeoutHeight: parseTimeoutHeight(getField(evt, channeltypes.AttributeKeyTimeoutHeight)), - TimeoutTimestamp: getUintField(evt, channeltypes.AttributeKeyTimeoutTimestamp), - } -} - -func getHexField(evt abci.Event, key string) []byte { - got := getField(evt, key) - if got == "" { - return nil - } - bz, err := hex.DecodeString(got) - if err != nil { - panic(err) - } - return bz -} - -// return the value for the attribute with the given name -func getField(evt abci.Event, key string) string { - for _, attr := range evt.Attributes { - if attr.Key == key { - return attr.Value - } - } - return "" -} - -func getUintField(evt abci.Event, key string) uint64 { - raw := getField(evt, key) - return toUint64(raw) -} - -func toUint64(raw string) uint64 { - if raw == "" { - return 0 - } - i, err := strconv.ParseUint(raw, 10, 64) - if err != nil { - panic(err) - } - return i -} - -func parseTimeoutHeight(raw string) clienttypes.Height { - chunks := strings.Split(raw, "-") - return clienttypes.Height{ - RevisionNumber: toUint64(chunks[0]), - RevisionHeight: toUint64(chunks[1]), - } -} - -func ParsePortIDFromEvents(events sdk.Events) (string, error) { - for _, ev := range events { - if ev.Type == channeltypes.EventTypeChannelOpenInit || ev.Type == channeltypes.EventTypeChannelOpenTry { - for _, attr := range ev.Attributes { - if attr.Key == channeltypes.AttributeKeyPortID { - return attr.Value, nil - } - } - } - } - return "", fmt.Errorf("port id event attribute not found") -} - -func ParseChannelVersionFromEvents(events sdk.Events) (string, error) { - for _, ev := range events { - if ev.Type == channeltypes.EventTypeChannelOpenInit || ev.Type == channeltypes.EventTypeChannelOpenTry { - for _, attr := range ev.Attributes { - if attr.Key == channeltypes.AttributeVersion { - return attr.Value, nil - } - } - } - } - return "", fmt.Errorf("version event attribute not found") -} diff --git a/x/wasm/ibctesting/faucet.go b/x/wasm/ibctesting/faucet.go deleted file mode 100644 index 46da6c3..0000000 --- a/x/wasm/ibctesting/faucet.go +++ /dev/null @@ -1,53 +0,0 @@ -package ibctesting - -import ( - "cosmossdk.io/math" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" -) - -// Fund an address with the given amount in default denom -func (chain *TestChain) Fund(addr sdk.AccAddress, amount math.Int) { - require.NoError(chain.t, chain.sendMsgs(&banktypes.MsgSend{ - FromAddress: chain.SenderAccount.GetAddress().String(), - ToAddress: addr.String(), - Amount: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amount)), - })) -} - -// SendNonDefaultSenderMsgs delivers a transaction through the application. It returns the result and error if one -// occurred. -func (chain *TestChain) SendNonDefaultSenderMsgs(senderPrivKey cryptotypes.PrivKey, msgs ...sdk.Msg) (*sdk.Result, error) { - require.NotEqual(chain.t, chain.SenderPrivKey, senderPrivKey, "use SendMsgs method") - - // ensure the chain has the latest time - chain.Coordinator.UpdateTimeForChain(chain) - - addr := sdk.AccAddress(senderPrivKey.PubKey().Address().Bytes()) - account := chain.App.AccountKeeper.GetAccount(chain.GetContext(), addr) - require.NotNil(chain.t, account) - _, r, err := app.SignAndDeliverWithoutCommit( - chain.t, - chain.TxConfig, - chain.App.BaseApp, - chain.GetContext().BlockHeader(), - msgs, - chain.ChainID, - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - senderPrivKey, - ) - - // SignAndDeliverWithoutCommit calls app.Commit() - chain.NextBlock() - chain.Coordinator.IncrementTime() - if err != nil { - return r, err - } - chain.CaptureIBCEvents(r) - return r, nil -} diff --git a/x/wasm/ibctesting/path.go b/x/wasm/ibctesting/path.go deleted file mode 100644 index c7f1af8..0000000 --- a/x/wasm/ibctesting/path.go +++ /dev/null @@ -1,109 +0,0 @@ -package ibctesting - -import ( - "bytes" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" -) - -// Path contains two endpoints representing two chains connected over IBC -type Path struct { - EndpointA *Endpoint - EndpointB *Endpoint -} - -// NewPath constructs an endpoint for each chain using the default values -// for the endpoints. Each endpoint is updated to have a pointer to the -// counterparty endpoint. -func NewPath(chainA, chainB *TestChain) *Path { - endpointA := NewDefaultEndpoint(chainA) - endpointB := NewDefaultEndpoint(chainB) - - endpointA.Counterparty = endpointB - endpointB.Counterparty = endpointA - - return &Path{ - EndpointA: endpointA, - EndpointB: endpointB, - } -} - -// SetChannelOrdered sets the channel order for both endpoints to ORDERED. -func (path *Path) SetChannelOrdered() { - path.EndpointA.ChannelConfig.Order = channeltypes.ORDERED - path.EndpointB.ChannelConfig.Order = channeltypes.ORDERED -} - -// RelayPacket attempts to relay the packet first on EndpointA and then on EndpointB -// if EndpointA does not contain a packet commitment for that packet. An error is returned -// if a relay step fails or the packet commitment does not exist on either endpoint. -func (path *Path) RelayPacket(packet channeltypes.Packet, _ []byte) error { - pc := path.EndpointA.Chain.App.IBCKeeper.ChannelKeeper.GetPacketCommitment(path.EndpointA.Chain.GetContext(), packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) - if bytes.Equal(pc, channeltypes.CommitPacket(path.EndpointA.Chain.App.AppCodec(), packet)) { - - // packet found, relay from A to B - if err := path.EndpointB.UpdateClient(); err != nil { - return err - } - - res, err := path.EndpointB.RecvPacketWithResult(packet) - if err != nil { - return err - } - - ack, err := ibctesting.ParseAckFromEvents(res.GetEvents()) - if err != nil { - return err - } - - err = path.EndpointA.AcknowledgePacket(packet, ack) - - return err - } - - pc = path.EndpointB.Chain.App.IBCKeeper.ChannelKeeper.GetPacketCommitment(path.EndpointB.Chain.GetContext(), packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) - if bytes.Equal(pc, channeltypes.CommitPacket(path.EndpointB.Chain.App.AppCodec(), packet)) { - - // packet found, relay B to A - if err := path.EndpointA.UpdateClient(); err != nil { - return err - } - - res, err := path.EndpointA.RecvPacketWithResult(packet) - if err != nil { - return err - } - - ack, err := ibctesting.ParseAckFromEvents(res.GetEvents()) - if err != nil { - return err - } - - err = path.EndpointB.AcknowledgePacket(packet, ack) - return err - } - - return fmt.Errorf("packet commitment does not exist on either endpoint for provided packet") -} - -// SendMsg delivers the provided messages to the chain. The counterparty -// client is updated with the new source consensus state. -func (path *Path) SendMsg(msgs ...sdk.Msg) error { - if err := path.EndpointA.Chain.sendMsgs(msgs...); err != nil { - return err - } - if err := path.EndpointA.UpdateClient(); err != nil { - return err - } - return path.EndpointB.UpdateClient() -} - -func (path *Path) Invert() *Path { - return &Path{ - EndpointA: path.EndpointB, - EndpointB: path.EndpointA, - } -} diff --git a/x/wasm/ibctesting/wasm.go b/x/wasm/ibctesting/wasm.go deleted file mode 100644 index d8e5b50..0000000 --- a/x/wasm/ibctesting/wasm.go +++ /dev/null @@ -1,129 +0,0 @@ -package ibctesting - -import ( - "bytes" - "compress/gzip" - "encoding/json" - "fmt" - "os" - "strings" - - ibctesting "github.com/cosmos/ibc-go/v7/testing" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/rand" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var wasmIdent = []byte("\x00\x61\x73\x6D") - -// SeedNewContractInstance stores some wasm code and instantiates a new contract on this chain. -// This method can be called to prepare the store with some valid CodeInfo and ContractInfo. The returned -// Address is the contract address for this instance. Test should make use of this data and/or use NewIBCContractMockWasmer -// for using a contract mock in Go. -func (chain *TestChain) SeedNewContractInstance() sdk.AccAddress { - pInstResp := chain.StoreCode(append(wasmIdent, rand.Bytes(10)...)) - codeID := pInstResp.CodeID - - anyAddressStr := chain.SenderAccount.GetAddress().String() - initMsg := []byte(fmt.Sprintf(`{"verifier": %q, "beneficiary": %q}`, anyAddressStr, anyAddressStr)) - return chain.InstantiateContract(codeID, initMsg) -} - -func (chain *TestChain) StoreCodeFile(filename string) types.MsgStoreCodeResponse { - wasmCode, err := os.ReadFile(filename) - require.NoError(chain.t, err) - if strings.HasSuffix(filename, "wasm") { // compress for gas limit - var buf bytes.Buffer - gz := gzip.NewWriter(&buf) - _, err := gz.Write(wasmCode) - require.NoError(chain.t, err) - err = gz.Close() - require.NoError(chain.t, err) - wasmCode = buf.Bytes() - } - return chain.StoreCode(wasmCode) -} - -func (chain *TestChain) StoreCode(byteCode []byte) types.MsgStoreCodeResponse { - storeMsg := &types.MsgStoreCode{ - Sender: chain.SenderAccount.GetAddress().String(), - WASMByteCode: byteCode, - } - r, err := chain.SendMsgs(storeMsg) - require.NoError(chain.t, err) - // unmarshal protobuf response from data - require.Len(chain.t, r.MsgResponses, 1) - require.NotEmpty(chain.t, r.MsgResponses[0].GetCachedValue()) - pInstResp := r.MsgResponses[0].GetCachedValue().(*types.MsgStoreCodeResponse) - require.NotEmpty(chain.t, pInstResp.CodeID) - require.NotEmpty(chain.t, pInstResp.Checksum) - return *pInstResp -} - -func (chain *TestChain) InstantiateContract(codeID uint64, initMsg []byte) sdk.AccAddress { - instantiateMsg := &types.MsgInstantiateContract{ - Sender: chain.SenderAccount.GetAddress().String(), - Admin: chain.SenderAccount.GetAddress().String(), - CodeID: codeID, - Label: "ibc-test", - Msg: initMsg, - Funds: sdk.Coins{ibctesting.TestCoin}, - } - - r, err := chain.SendMsgs(instantiateMsg) - require.NoError(chain.t, err) - require.Len(chain.t, r.MsgResponses, 1) - require.NotEmpty(chain.t, r.MsgResponses[0].GetCachedValue()) - pExecResp := r.MsgResponses[0].GetCachedValue().(*types.MsgInstantiateContractResponse) - a, err := sdk.AccAddressFromBech32(pExecResp.Address) - require.NoError(chain.t, err) - return a -} - -// SmartQuery This will serialize the query message and submit it to the contract. -// The response is parsed into the provided interface. -// Usage: SmartQuery(addr, QueryMsg{Foo: 1}, &response) -func (chain *TestChain) SmartQuery(contractAddr string, queryMsg interface{}, response interface{}) error { - msg, err := json.Marshal(queryMsg) - if err != nil { - return err - } - - req := types.QuerySmartContractStateRequest{ - Address: contractAddr, - QueryData: msg, - } - reqBin, err := proto.Marshal(&req) - if err != nil { - return err - } - - // TODO: what is the query? - res := chain.App.Query(abci.RequestQuery{ - Path: "/cosmwasm.wasm.v1.Query/SmartContractState", - Data: reqBin, - }) - - if res.Code != 0 { - return fmt.Errorf("query failed: (%d) %s", res.Code, res.Log) - } - - // unpack protobuf - var resp types.QuerySmartContractStateResponse - err = proto.Unmarshal(res.Value, &resp) - if err != nil { - return err - } - // unpack json content - return json.Unmarshal(resp.Data, response) -} - -// ContractInfo is a helper function to returns the ContractInfo for the given contract address -func (chain *TestChain) ContractInfo(contractAddr sdk.AccAddress) *types.ContractInfo { - return chain.App.WasmKeeper.GetContractInfo(chain.GetContext(), contractAddr) -} diff --git a/x/wasm/ioutils/ioutil.go b/x/wasm/ioutils/ioutil.go deleted file mode 100644 index 93adb4f..0000000 --- a/x/wasm/ioutils/ioutil.go +++ /dev/null @@ -1,41 +0,0 @@ -package ioutils - -import ( - "bytes" - "compress/gzip" - "io" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// Uncompress expects a valid gzip source to unpack or fails. See IsGzip -func Uncompress(gzipSrc []byte, limit uint64) ([]byte, error) { - if uint64(len(gzipSrc)) > limit { - return nil, types.ErrLimit - } - zr, err := gzip.NewReader(bytes.NewReader(gzipSrc)) - if err != nil { - return nil, err - } - zr.Multistream(false) - defer zr.Close() - return io.ReadAll(LimitReader(zr, int64(limit))) -} - -// LimitReader returns a Reader that reads from r -// but stops with types.ErrLimit after n bytes. -// The underlying implementation is a *io.LimitedReader. -func LimitReader(r io.Reader, n int64) io.Reader { - return &LimitedReader{r: &io.LimitedReader{R: r, N: n}} -} - -type LimitedReader struct { - r *io.LimitedReader -} - -func (l *LimitedReader) Read(p []byte) (n int, err error) { - if l.r.N <= 0 { - return 0, types.ErrLimit - } - return l.r.Read(p) -} diff --git a/x/wasm/ioutils/ioutil_test.go b/x/wasm/ioutils/ioutil_test.go deleted file mode 100644 index 50f1a81..0000000 --- a/x/wasm/ioutils/ioutil_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package ioutils - -import ( - "bytes" - "compress/gzip" - "errors" - "io" - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestUncompress(t *testing.T) { - wasmRaw, err := os.ReadFile("../keeper/testdata/hackatom.wasm") - require.NoError(t, err) - - wasmGzipped, err := os.ReadFile("../keeper/testdata/hackatom.wasm.gzip") - require.NoError(t, err) - - const maxSize = 400_000 - - specs := map[string]struct { - src []byte - expError error - expResult []byte - }{ - "handle wasm compressed": { - src: wasmGzipped, - expResult: wasmRaw, - }, - "handle gzip identifier only": { - src: gzipIdent, - expError: io.ErrUnexpectedEOF, - }, - "handle broken gzip": { - src: append(gzipIdent, byte(0x1)), - expError: io.ErrUnexpectedEOF, - }, - "handle incomplete gzip": { - src: wasmGzipped[:len(wasmGzipped)-5], - expError: io.ErrUnexpectedEOF, - }, - "handle limit gzip output": { - src: asGzip(bytes.Repeat([]byte{0x1}, maxSize)), - expResult: bytes.Repeat([]byte{0x1}, maxSize), - }, - "handle big gzip output": { - src: asGzip(bytes.Repeat([]byte{0x1}, maxSize+1)), - expError: types.ErrLimit, - }, - "handle other big gzip output": { - src: asGzip(bytes.Repeat([]byte{0x1}, 2*maxSize)), - expError: types.ErrLimit, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - r, err := Uncompress(spec.src, maxSize) - require.True(t, errors.Is(spec.expError, err), "exp %v got %+v", spec.expError, err) - if spec.expError != nil { - return - } - assert.Equal(t, spec.expResult, r) - }) - } -} - -func asGzip(src []byte) []byte { - var buf bytes.Buffer - zipper := gzip.NewWriter(&buf) - if _, err := io.Copy(zipper, bytes.NewReader(src)); err != nil { - panic(err) - } - if err := zipper.Close(); err != nil { - panic(err) - } - return buf.Bytes() -} diff --git a/x/wasm/ioutils/utils.go b/x/wasm/ioutils/utils.go deleted file mode 100644 index 9c9cd38..0000000 --- a/x/wasm/ioutils/utils.go +++ /dev/null @@ -1,45 +0,0 @@ -package ioutils - -import ( - "bytes" - "compress/gzip" -) - -// Note: []byte can never be const as they are inherently mutable -var ( - // magic bytes to identify gzip. - // See https://www.ietf.org/rfc/rfc1952.txt - // and https://github.com/golang/go/blob/master/src/net/http/sniff.go#L186 - gzipIdent = []byte("\x1F\x8B\x08") - - // magic number for Wasm is "\0asm" - // See https://webassembly.github.io/spec/core/binary/modules.html#binary-module - wasmIdent = []byte("\x00\x61\x73\x6D") -) - -// IsGzip returns checks if the file contents are gzip compressed -func IsGzip(input []byte) bool { - return len(input) >= 3 && bytes.Equal(gzipIdent, input[0:3]) -} - -// IsWasm checks if the file contents are of wasm binary -func IsWasm(input []byte) bool { - return bytes.Equal(input[:4], wasmIdent) -} - -// GzipIt compresses the input ([]byte) -func GzipIt(input []byte) ([]byte, error) { - // Create gzip writer. - var b bytes.Buffer - w := gzip.NewWriter(&b) - _, err := w.Write(input) - if err != nil { - return nil, err - } - err = w.Close() // You must close this first to flush the bytes to the buffer. - if err != nil { - return nil, err - } - - return b.Bytes(), nil -} diff --git a/x/wasm/ioutils/utils_test.go b/x/wasm/ioutils/utils_test.go deleted file mode 100644 index 2dea0c5..0000000 --- a/x/wasm/ioutils/utils_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package ioutils - -import ( - "os" - "testing" - - "github.com/stretchr/testify/require" -) - -func GetTestData() ([]byte, []byte, []byte, error) { - wasmCode, err := os.ReadFile("../keeper/testdata/hackatom.wasm") - if err != nil { - return nil, nil, nil, err - } - - gzipData, err := GzipIt(wasmCode) - if err != nil { - return nil, nil, nil, err - } - - someRandomStr := []byte("hello world") - - return wasmCode, someRandomStr, gzipData, nil -} - -func TestIsWasm(t *testing.T) { - wasmCode, someRandomStr, gzipData, err := GetTestData() - require.NoError(t, err) - - t.Log("should return false for some random string data") - require.False(t, IsWasm(someRandomStr)) - t.Log("should return false for gzip data") - require.False(t, IsWasm(gzipData)) - t.Log("should return true for exact wasm") - require.True(t, IsWasm(wasmCode)) -} - -func TestIsGzip(t *testing.T) { - wasmCode, someRandomStr, gzipData, err := GetTestData() - require.NoError(t, err) - - require.False(t, IsGzip(wasmCode)) - require.False(t, IsGzip(someRandomStr)) - require.False(t, IsGzip(nil)) - require.True(t, IsGzip(gzipData[0:3])) - require.True(t, IsGzip(gzipData)) -} - -func TestGzipIt(t *testing.T) { - wasmCode, someRandomStr, _, err := GetTestData() - originalGzipData := []byte{ - 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 202, 72, 205, 201, 201, 87, 40, 207, 47, 202, 73, 1, - 4, 0, 0, 255, 255, 133, 17, 74, 13, 11, 0, 0, 0, - } - - require.NoError(t, err) - - t.Log("gzip wasm with no error") - _, err = GzipIt(wasmCode) - require.NoError(t, err) - - t.Log("gzip of a string should return exact gzip data") - strToGzip, err := GzipIt(someRandomStr) - - require.True(t, IsGzip(strToGzip)) - require.NoError(t, err) - require.Equal(t, originalGzipData, strToGzip) -} diff --git a/x/wasm/keeper/addresses.go b/x/wasm/keeper/addresses.go deleted file mode 100644 index 80f8ab5..0000000 --- a/x/wasm/keeper/addresses.go +++ /dev/null @@ -1,76 +0,0 @@ -package keeper - -import ( - "encoding/binary" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// AddressGenerator abstract address generator to be used for a single contract address -type AddressGenerator func(ctx sdk.Context, codeID uint64, checksum []byte) sdk.AccAddress - -// ClassicAddressGenerator generates a contract address using codeID and instanceID sequence -func (k Keeper) ClassicAddressGenerator() AddressGenerator { - return func(ctx sdk.Context, codeID uint64, _ []byte) sdk.AccAddress { - instanceID := k.autoIncrementID(ctx, types.KeyLastInstanceID) - return BuildContractAddressClassic(codeID, instanceID) - } -} - -// PredicableAddressGenerator generates a predictable contract address -func PredicableAddressGenerator(creator sdk.AccAddress, salt []byte, msg []byte, fixMsg bool) AddressGenerator { - return func(ctx sdk.Context, _ uint64, checksum []byte) sdk.AccAddress { - if !fixMsg { // clear msg to not be included in the address generation - msg = []byte{} - } - return BuildContractAddressPredictable(checksum, creator, salt, msg) - } -} - -// BuildContractAddressClassic builds an sdk account address for a contract. -func BuildContractAddressClassic(codeID, instanceID uint64) sdk.AccAddress { - contractID := make([]byte, 16) - binary.BigEndian.PutUint64(contractID[:8], codeID) - binary.BigEndian.PutUint64(contractID[8:], instanceID) - return address.Module(types.ModuleName, contractID)[:types.ContractAddrLen] -} - -// BuildContractAddressPredictable generates a contract address for the wasm module with len = types.ContractAddrLen using the -// Cosmos SDK address.Module function. -// Internally a key is built containing: -// (len(checksum) | checksum | len(sender_address) | sender_address | len(salt) | salt| len(initMsg) | initMsg). -// -// All method parameter values must be valid and not nil. -func BuildContractAddressPredictable(checksum []byte, creator sdk.AccAddress, salt, initMsg types.RawContractMessage) sdk.AccAddress { - if len(checksum) != 32 { - panic("invalid checksum") - } - if err := sdk.VerifyAddressFormat(creator); err != nil { - panic(fmt.Sprintf("creator: %s", err)) - } - if err := types.ValidateSalt(salt); err != nil { - panic(fmt.Sprintf("salt: %s", err)) - } - if err := initMsg.ValidateBasic(); len(initMsg) != 0 && err != nil { - panic(fmt.Sprintf("initMsg: %s", err)) - } - checksum = UInt64LengthPrefix(checksum) - creator = UInt64LengthPrefix(creator) - salt = UInt64LengthPrefix(salt) - initMsg = UInt64LengthPrefix(initMsg) - key := make([]byte, len(checksum)+len(creator)+len(salt)+len(initMsg)) - copy(key[0:], checksum) - copy(key[len(checksum):], creator) - copy(key[len(checksum)+len(creator):], salt) - copy(key[len(checksum)+len(creator)+len(salt):], initMsg) - return address.Module(types.ModuleName, key)[:types.ContractAddrLen] -} - -// UInt64LengthPrefix prepend big endian encoded byte length -func UInt64LengthPrefix(bz []byte) []byte { - return append(sdk.Uint64ToBigEndian(uint64(len(bz))), bz...) -} diff --git a/x/wasm/keeper/addresses_test.go b/x/wasm/keeper/addresses_test.go deleted file mode 100644 index 399c3e7..0000000 --- a/x/wasm/keeper/addresses_test.go +++ /dev/null @@ -1,432 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - "testing" - - tmbytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" -) - -func TestBuildContractAddress(t *testing.T) { - x, y := sdk.GetConfig().GetBech32AccountAddrPrefix(), sdk.GetConfig().GetBech32AccountPubPrefix() - t.Cleanup(func() { - sdk.GetConfig().SetBech32PrefixForAccount(x, y) - }) - sdk.GetConfig().SetBech32PrefixForAccount("purple", "purple") - - // test vectors generated via cosmjs: https://github.com/cosmos/cosmjs/pull/1253/files - type Spec struct { - In struct { - Checksum tmbytes.HexBytes `json:"checksum"` - Creator sdk.AccAddress `json:"creator"` - Salt tmbytes.HexBytes `json:"salt"` - Msg string `json:"msg"` - } `json:"in"` - Out struct { - Address sdk.AccAddress `json:"address"` - } `json:"out"` - } - var specs []Spec - require.NoError(t, json.Unmarshal([]byte(goldenMasterPredictableContractAddr), &specs)) - require.NotEmpty(t, specs) - for i, spec := range specs { - t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) { - // when - gotAddr := BuildContractAddressPredictable(spec.In.Checksum, spec.In.Creator, spec.In.Salt.Bytes(), []byte(spec.In.Msg)) - - require.Equal(t, spec.Out.Address.String(), gotAddr.String()) - require.NoError(t, sdk.VerifyAddressFormat(gotAddr)) - }) - } -} - -const goldenMasterPredictableContractAddr = `[ - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": null - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000001610000000000000000", - "addressData": "5e865d3e45ad3e961f77fd77d46543417ced44d924dc3e079b5415ff6775f847" - }, - "out": { - "address": "purple1t6r960j945lfv8mhl4mage2rg97w63xeynwrupum2s2l7em4lprs9ce5hk" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc00000000000000016100000000000000027b7d", - "addressData": "0995499608947a5281e2c7ebd71bdb26a1ad981946dad57f6c4d3ee35de77835" - }, - "out": { - "address": "purple1px25n9sgj3a99q0zcl4awx7my6s6mxqegmdd2lmvf5lwxh080q6suttktr" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc000000000000000161000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "83326e554723b15bac664ceabc8a5887e27003abe9fbd992af8c7bcea4745167" - }, - "out": { - "address": "purple1svexu428ywc4htrxfn4tezjcsl38qqata8aany4033auafr529ns4v254c" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": null - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae0000000000000000", - "addressData": "9384c6248c0bb171e306fd7da0993ec1e20eba006452a3a9e078883eb3594564" - }, - "out": { - "address": "purple1jwzvvfyvpwchrccxl476pxf7c83qawsqv3f2820q0zyrav6eg4jqdcq7gc" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae00000000000000027b7d", - "addressData": "9a8d5f98fb186825401a26206158e7a1213311a9b6a87944469913655af52ffb" - }, - "out": { - "address": "purple1n2x4lx8mrp5z2sq6ycsxzk885ysnxydfk658j3zxnyfk2kh49lasesxf6j" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "932f07bc53f7d0b0b43cb5a54ac3e245b205e6ae6f7c1d991dc6af4a2ff9ac18" - }, - "out": { - "address": "purple1jvhs00zn7lgtpdpukkj54slzgkeqte4wda7pmxgac6h55tle4svq8cmp60" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": null - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000001610000000000000000", - "addressData": "9725e94f528d8b78d33c25f3dfcd60e6142d8be60ab36f6a5b59036fd51560db" - }, - "out": { - "address": "purple1juj7jn6j3k9h35euyhealntquc2zmzlxp2ek76jmtypkl4g4vrdsfwmwxk" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff00000000000000016100000000000000027b7d", - "addressData": "b056e539bbaf447ba18f3f13b792970111fc78933eb6700f4d227b5216d63658" - }, - "out": { - "address": "purple1kptw2wdm4az8hgv08ufm0y5hqyglc7yn86m8qr6dyfa4y9kkxevqmkm9q3" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff000000000000000161000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "6c98434180f052294ff89fb6d2dae34f9f4468b0b8e6e7c002b2a44adee39abd" - }, - "out": { - "address": "purple1djvyxsvq7pfzjnlcn7md9khrf705g69shrnw0sqzk2jy4hhrn27sjh2ysy" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": null - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae0000000000000000", - "addressData": "0aaf1c31c5d529d21d898775bc35b3416f47bfd99188c334c6c716102cbd3101" - }, - "out": { - "address": "purple1p2h3cvw9655ay8vfsa6mcddng9h5007ejxyvxdxxcutpqt9axyqsagmmay" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae00000000000000027b7d", - "addressData": "36fe6ab732187cdfed46290b448b32eb7f4798e7a4968b0537de8a842cbf030e" - }, - "out": { - "address": "purple1xmlx4dejrp7dlm2x9y95fzejadl50x885jtgkpfhm69ggt9lqv8qk3vn4f" - } - }, - { - "in": { - "checksum": "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d00000000000000002013a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a500000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "a0d0c942adac6f3e5e7c23116c4c42a24e96e0ab75f53690ec2d3de16067c751" - }, - "out": { - "address": "purple15rgvjs4d43hnuhnuyvgkcnzz5f8fdc9twh6ndy8v9577zcr8cags40l9dt" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": null - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000001610000000000000000", - "addressData": "b95c467218d408a0f93046f227b6ece7fe18133ff30113db4d2a7becdfeca141" - }, - "out": { - "address": "purple1h9wyvusc6sy2p7fsgmez0dhvullpsyel7vq38k6d9fa7ehlv59qsvnyh36" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc00000000000000016100000000000000027b7d", - "addressData": "23fe45dbbd45dc6cd25244a74b6e99e7a65bf0bac2f2842a05049d37555a3ae6" - }, - "out": { - "address": "purple1y0lytkaaghwxe5jjgjn5km5eu7n9hu96ctegg2s9qjwnw4268tnqxhg60a" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "61", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc000000000000000161000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "6faea261ed63baa65b05726269e83b217fa6205dc7d9fb74f9667d004a69c082" - }, - "out": { - "address": "purple1d7h2yc0dvwa2vkc9wf3xn6pmy9l6vgzaclvlka8eve7sqjnfczpqqsdnwu" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": null - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae0000000000000000", - "addressData": "67a3ab6384729925fdb144574628ce96836fe098d2c6be4e84ac106b2728d96c" - }, - "out": { - "address": "purple1v736kcuyw2vjtld3g3t5v2xwj6pklcyc6trtun5y4sgxkfegm9kq7vgpnt" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae00000000000000027b7d", - "addressData": "23a121263bfce05c144f4af86f3d8a9f87dc56f9dc48dbcffc8c5a614da4c661" - }, - "out": { - "address": "purple1ywsjzf3mlns9c9z0ftux70v2n7rac4hem3ydhnlu33dxzndycesssc7x2m" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvhxf2py", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbcccccccccc", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000149999999999aaaaaaaaaabbbbbbbbbbcccccccccc0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "dd90dba6d6fcd5fb9c9c8f536314eb1bb29cb5aa084b633c5806b926a5636b58" - }, - "out": { - "address": "purple1mkgdhfkkln2lh8yu3afkx98trwefedd2pp9kx0zcq6ujdftrddvq50esay" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": null - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000001610000000000000000", - "addressData": "547a743022f4f1af05b102f57bf1c1c7d7ee81bae427dc20d36b2c4ec57612ae" - }, - "out": { - "address": "purple123a8gvpz7nc67pd3qt6hhuwpclt7aqd6usnacgxndvkya3tkz2hq5hz38f" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff00000000000000016100000000000000027b7d", - "addressData": "416e169110e4b411bc53162d7503b2bbf14d6b36b1413a4f4c9af622696e9665" - }, - "out": { - "address": "purple1g9hpdygsuj6pr0znzckh2qajh0c566ekk9qn5n6vntmzy6twjejsrl9alk" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "61", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff000000000000000161000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "619a0988b92d8796cea91dea63cbb1f1aefa4a6b6ee5c5d1e937007252697220" - }, - "out": { - "address": "purple1vxdqnz9e9kredn4frh4x8ja37xh05jntdmjut50fxuq8y5nfwgsquu9mxh" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": null - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae0000000000000000", - "addressData": "d8af856a6a04852d19b647ad6d4336eb26e077f740aef1a0331db34d299a885a" - }, - "out": { - "address": "purple1mzhc26n2qjzj6xdkg7kk6sekavnwqalhgzh0rgpnrke562v63pdq8grp8q" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae00000000000000027b7d", - "addressData": "c7fb7bea96daab23e416c4fcf328215303005e1d0d5424257335568e5381e33c" - }, - "out": { - "address": "purple1clahh65km24j8eqkcn70x2pp2vpsqhsap42zgftnx4tgu5upuv7q9ywjws" - } - }, - { - "in": { - "checksum": "1da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b", - "creator": "purple1nxvenxve42424242hwamhwamenxvenxvmhwamhwaamhwamhwlllsatsy6m", - "creatorData": "9999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff", - "salt": "aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae", - "msg": "{\"some\":123,\"structure\":{\"nested\":[\"ok\",true]}}" - }, - "intermediate": { - "key": "7761736d0000000000000000201da6c16de2cbaf7ad8cbb66f0925ba33f5c278cb2491762d04658c1480ea229b00000000000000209999999999aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffff0000000000000040aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbccddeeffffeeddbbccddaa66551155aaaabbcc787878789900aabbbbcc221100acadae000000000000002f7b22736f6d65223a3132332c22737472756374757265223a7b226e6573746564223a5b226f6b222c747275655d7d7d", - "addressData": "ccdf9dea141a6c2475870529ab38fae9dec30df28e005894fe6578b66133ab4a" - }, - "out": { - "address": "purple1en0em6s5rfkzgav8q556kw86a80vxr0j3cq93987v4utvcfn4d9q0tql4w" - } - } -] -` diff --git a/x/wasm/keeper/ante.go b/x/wasm/keeper/ante.go deleted file mode 100644 index 27dd580..0000000 --- a/x/wasm/keeper/ante.go +++ /dev/null @@ -1,97 +0,0 @@ -package keeper - -import ( - "encoding/binary" - - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// CountTXDecorator ante handler to count the tx position in a block. -type CountTXDecorator struct { - storeKey storetypes.StoreKey -} - -// NewCountTXDecorator constructor -func NewCountTXDecorator(storeKey storetypes.StoreKey) *CountTXDecorator { - return &CountTXDecorator{storeKey: storeKey} -} - -// AnteHandle handler stores a tx counter with current height encoded in the store to let the app handle -// global rollback behavior instead of keeping state in the handler itself. -// The ante handler passes the counter value via sdk.Context upstream. See `types.TXCounter(ctx)` to read the value. -// Simulations don't get a tx counter value assigned. -func (a CountTXDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - if simulate { - return next(ctx, tx, simulate) - } - store := ctx.KVStore(a.storeKey) - currentHeight := ctx.BlockHeight() - - var txCounter uint32 // start with 0 - // load counter when exists - if bz := store.Get(types.TXCounterPrefix); bz != nil { - lastHeight, val := decodeHeightCounter(bz) - if currentHeight == lastHeight { - // then use stored counter - txCounter = val - } // else use `0` from above to start with - } - // store next counter value for current height - store.Set(types.TXCounterPrefix, encodeHeightCounter(currentHeight, txCounter+1)) - - return next(types.WithTXCounter(ctx, txCounter), tx, simulate) -} - -func encodeHeightCounter(height int64, counter uint32) []byte { - b := make([]byte, 4) - binary.BigEndian.PutUint32(b, counter) - return append(sdk.Uint64ToBigEndian(uint64(height)), b...) -} - -func decodeHeightCounter(bz []byte) (int64, uint32) { - return int64(sdk.BigEndianToUint64(bz[0:8])), binary.BigEndian.Uint32(bz[8:]) -} - -// LimitSimulationGasDecorator ante decorator to limit gas in simulation calls -type LimitSimulationGasDecorator struct { - gasLimit *sdk.Gas -} - -// NewLimitSimulationGasDecorator constructor accepts nil value to fallback to block gas limit. -func NewLimitSimulationGasDecorator(gasLimit *sdk.Gas) *LimitSimulationGasDecorator { - if gasLimit != nil && *gasLimit == 0 { - panic("gas limit must not be zero") - } - return &LimitSimulationGasDecorator{gasLimit: gasLimit} -} - -// AnteHandle that limits the maximum gas available in simulations only. -// A custom max value can be configured and will be applied when set. The value should not -// exceed the max block gas limit. -// Different values on nodes are not consensus breaking as they affect only -// simulations but may have effect on client user experience. -// -// When no custom value is set then the max block gas is used as default limit. -func (d LimitSimulationGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - if !simulate { - // Wasm code is not executed in checkTX so that we don't need to limit it further. - // Tendermint rejects the TX afterwards when the tx.gas > max block gas. - // On deliverTX we rely on the tendermint/sdk mechanics that ensure - // tx has gas set and gas < max block gas - return next(ctx, tx, simulate) - } - - // apply custom node gas limit - if d.gasLimit != nil { - return next(ctx.WithGasMeter(sdk.NewGasMeter(*d.gasLimit)), tx, simulate) - } - - // default to max block gas when set, to be on the safe side - if maxGas := ctx.ConsensusParams().GetBlock().MaxGas; maxGas > 0 { - return next(ctx.WithGasMeter(sdk.NewGasMeter(sdk.Gas(maxGas))), tx, simulate) - } - return next(ctx, tx, simulate) -} diff --git a/x/wasm/keeper/ante_test.go b/x/wasm/keeper/ante_test.go deleted file mode 100644 index 0fa3221..0000000 --- a/x/wasm/keeper/ante_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package keeper_test - -import ( - "testing" - "time" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestCountTxDecorator(t *testing.T) { - keyWasm := sdk.NewKVStoreKey(types.StoreKey) - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyWasm, storetypes.StoreTypeIAVL, db) - require.NoError(t, ms.LoadLatestVersion()) - const myCurrentBlockHeight = 100 - - specs := map[string]struct { - setupDB func(t *testing.T, ctx sdk.Context) - simulate bool - nextAssertAnte func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) - expErr bool - }{ - "no initial counter set": { - setupDB: func(t *testing.T, ctx sdk.Context) {}, - nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - gotCounter, ok := types.TXCounter(ctx) - require.True(t, ok) - assert.Equal(t, uint32(0), gotCounter) - // and stored +1 - bz := ctx.MultiStore().GetKVStore(keyWasm).Get(types.TXCounterPrefix) - assert.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, myCurrentBlockHeight, 0, 0, 0, 1}, bz) - return ctx, nil - }, - }, - "persistent counter incremented - big endian": { - setupDB: func(t *testing.T, ctx sdk.Context) { - bz := []byte{0, 0, 0, 0, 0, 0, 0, myCurrentBlockHeight, 1, 0, 0, 2} - ctx.MultiStore().GetKVStore(keyWasm).Set(types.TXCounterPrefix, bz) - }, - nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - gotCounter, ok := types.TXCounter(ctx) - require.True(t, ok) - assert.Equal(t, uint32(1<<24+2), gotCounter) - // and stored +1 - bz := ctx.MultiStore().GetKVStore(keyWasm).Get(types.TXCounterPrefix) - assert.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, myCurrentBlockHeight, 1, 0, 0, 3}, bz) - return ctx, nil - }, - }, - "old height counter replaced": { - setupDB: func(t *testing.T, ctx sdk.Context) { - previousHeight := byte(myCurrentBlockHeight - 1) - bz := []byte{0, 0, 0, 0, 0, 0, 0, previousHeight, 0, 0, 0, 1} - ctx.MultiStore().GetKVStore(keyWasm).Set(types.TXCounterPrefix, bz) - }, - nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - gotCounter, ok := types.TXCounter(ctx) - require.True(t, ok) - assert.Equal(t, uint32(0), gotCounter) - // and stored +1 - bz := ctx.MultiStore().GetKVStore(keyWasm).Get(types.TXCounterPrefix) - assert.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, myCurrentBlockHeight, 0, 0, 0, 1}, bz) - return ctx, nil - }, - }, - "simulation not persisted": { - setupDB: func(t *testing.T, ctx sdk.Context) { - }, - simulate: true, - nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - _, ok := types.TXCounter(ctx) - assert.False(t, ok) - require.True(t, simulate) - // and not stored - assert.False(t, ctx.MultiStore().GetKVStore(keyWasm).Has(types.TXCounterPrefix)) - return ctx, nil - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx := sdk.NewContext(ms.CacheMultiStore(), tmproto.Header{ - Height: myCurrentBlockHeight, - Time: time.Date(2021, time.September, 27, 12, 0, 0, 0, time.UTC), - }, false, log.NewNopLogger()) - - spec.setupDB(t, ctx) - var anyTx sdk.Tx - - // when - ante := keeper.NewCountTXDecorator(keyWasm) - _, gotErr := ante.AnteHandle(ctx, anyTx, spec.simulate, spec.nextAssertAnte) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestLimitSimulationGasDecorator(t *testing.T) { - var ( - hundred sdk.Gas = 100 - zero sdk.Gas = 0 - ) - specs := map[string]struct { - customLimit *sdk.Gas - consumeGas sdk.Gas - maxBlockGas int64 - simulation bool - expErr interface{} - }{ - "custom limit set": { - customLimit: &hundred, - consumeGas: hundred + 1, - maxBlockGas: -1, - simulation: true, - expErr: sdk.ErrorOutOfGas{Descriptor: "testing"}, - }, - "block limit set": { - maxBlockGas: 100, - consumeGas: hundred + 1, - simulation: true, - expErr: sdk.ErrorOutOfGas{Descriptor: "testing"}, - }, - "no limits set": { - maxBlockGas: -1, - consumeGas: hundred + 1, - simulation: true, - }, - "both limits set, custom applies": { - customLimit: &hundred, - consumeGas: hundred - 1, - maxBlockGas: 10, - simulation: true, - }, - "not a simulation": { - customLimit: &hundred, - consumeGas: hundred + 1, - simulation: false, - }, - "zero custom limit": { - customLimit: &zero, - simulation: true, - expErr: "gas limit must not be zero", - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - nextAnte := consumeGasAnteHandler(spec.consumeGas) - ctx := sdk.Context{}. - WithGasMeter(sdk.NewInfiniteGasMeter()). - WithConsensusParams(&tmproto.ConsensusParams{ - Block: &tmproto.BlockParams{MaxGas: spec.maxBlockGas}, - }) - // when - if spec.expErr != nil { - require.PanicsWithValue(t, spec.expErr, func() { - ante := keeper.NewLimitSimulationGasDecorator(spec.customLimit) - _, err := ante.AnteHandle(ctx, nil, spec.simulation, nextAnte) - require.NoError(t, err) - }) - return - } - ante := keeper.NewLimitSimulationGasDecorator(spec.customLimit) - _, err := ante.AnteHandle(ctx, nil, spec.simulation, nextAnte) - require.NoError(t, err) - }) - } -} - -func consumeGasAnteHandler(gasToConsume sdk.Gas) sdk.AnteHandler { - return func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { - ctx.GasMeter().ConsumeGas(gasToConsume, "testing") - return ctx, nil - } -} diff --git a/x/wasm/keeper/api.go b/x/wasm/keeper/api.go deleted file mode 100644 index 88f3b82..0000000 --- a/x/wasm/keeper/api.go +++ /dev/null @@ -1,43 +0,0 @@ -package keeper - -import ( - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // DefaultGasCostHumanAddress is how much SDK gas we charge to convert to a human address format - DefaultGasCostHumanAddress = 5 - // DefaultGasCostCanonicalAddress is how much SDK gas we charge to convert to a canonical address format - DefaultGasCostCanonicalAddress = 4 - - // DefaultDeserializationCostPerByte The formula should be `len(data) * deserializationCostPerByte` - DefaultDeserializationCostPerByte = 1 -) - -var ( - costHumanize = DefaultGasCostHumanAddress * DefaultGasMultiplier - costCanonical = DefaultGasCostCanonicalAddress * DefaultGasMultiplier - costJSONDeserialization = wasmvmtypes.UFraction{ - Numerator: DefaultDeserializationCostPerByte * DefaultGasMultiplier, - Denominator: 1, - } -) - -func humanAddress(canon []byte) (string, uint64, error) { - if err := sdk.VerifyAddressFormat(canon); err != nil { - return "", costHumanize, err - } - return sdk.AccAddress(canon).String(), costHumanize, nil -} - -func canonicalAddress(human string) ([]byte, uint64, error) { - bz, err := sdk.AccAddressFromBech32(human) - return bz, costCanonical, err -} - -var cosmwasmAPI = wasmvm.GoAPI{ - HumanAddress: humanAddress, - CanonicalAddress: canonicalAddress, -} diff --git a/x/wasm/keeper/authz_policy.go b/x/wasm/keeper/authz_policy.go deleted file mode 100644 index 36308a7..0000000 --- a/x/wasm/keeper/authz_policy.go +++ /dev/null @@ -1,63 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// ChainAccessConfigs chain settings -type ChainAccessConfigs struct { - Upload types.AccessConfig - Instantiate types.AccessConfig -} - -// NewChainAccessConfigs constructor -func NewChainAccessConfigs(upload types.AccessConfig, instantiate types.AccessConfig) ChainAccessConfigs { - return ChainAccessConfigs{Upload: upload, Instantiate: instantiate} -} - -type AuthorizationPolicy interface { - CanCreateCode(chainConfigs ChainAccessConfigs, actor sdk.AccAddress, contractConfig types.AccessConfig) bool - CanInstantiateContract(c types.AccessConfig, actor sdk.AccAddress) bool - CanModifyContract(admin, actor sdk.AccAddress) bool - CanModifyCodeAccessConfig(creator, actor sdk.AccAddress, isSubset bool) bool -} - -type DefaultAuthorizationPolicy struct{} - -func (p DefaultAuthorizationPolicy) CanCreateCode(chainConfigs ChainAccessConfigs, actor sdk.AccAddress, contractConfig types.AccessConfig) bool { - return chainConfigs.Upload.Allowed(actor) && - contractConfig.IsSubset(chainConfigs.Instantiate) -} - -func (p DefaultAuthorizationPolicy) CanInstantiateContract(config types.AccessConfig, actor sdk.AccAddress) bool { - return config.Allowed(actor) -} - -func (p DefaultAuthorizationPolicy) CanModifyContract(admin, actor sdk.AccAddress) bool { - return admin != nil && admin.Equals(actor) -} - -func (p DefaultAuthorizationPolicy) CanModifyCodeAccessConfig(creator, actor sdk.AccAddress, isSubset bool) bool { - return creator != nil && creator.Equals(actor) && isSubset -} - -type GovAuthorizationPolicy struct{} - -// CanCreateCode implements AuthorizationPolicy.CanCreateCode to allow gov actions. Always returns true. -func (p GovAuthorizationPolicy) CanCreateCode(ChainAccessConfigs, sdk.AccAddress, types.AccessConfig) bool { - return true -} - -func (p GovAuthorizationPolicy) CanInstantiateContract(types.AccessConfig, sdk.AccAddress) bool { - return true -} - -func (p GovAuthorizationPolicy) CanModifyContract(sdk.AccAddress, sdk.AccAddress) bool { - return true -} - -func (p GovAuthorizationPolicy) CanModifyCodeAccessConfig(sdk.AccAddress, sdk.AccAddress, bool) bool { - return true -} diff --git a/x/wasm/keeper/authz_policy_test.go b/x/wasm/keeper/authz_policy_test.go deleted file mode 100644 index 0e9c725..0000000 --- a/x/wasm/keeper/authz_policy_test.go +++ /dev/null @@ -1,345 +0,0 @@ -package keeper - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestDefaultAuthzPolicyCanCreateCode(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - specs := map[string]struct { - chainConfigs ChainAccessConfigs - contractInstConf types.AccessConfig - actor sdk.AccAddress - exp bool - panics bool - }{ - "upload nobody": { - chainConfigs: NewChainAccessConfigs(types.AllowNobody, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: false, - }, - "upload everybody": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: true, - }, - "upload only address - same": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeOnlyAddress.With(myActorAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: true, - }, - "upload only address - different": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeOnlyAddress.With(otherAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: false, - }, - "upload any address - included": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeAnyOfAddresses.With(otherAddress, myActorAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: true, - }, - "upload any address - not included": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeAnyOfAddresses.With(otherAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - exp: false, - }, - "contract config - subtype": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowEverybody), - contractInstConf: types.AccessTypeAnyOfAddresses.With(myActorAddress), - exp: true, - }, - "contract config - not subtype": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowNobody), - contractInstConf: types.AllowEverybody, - exp: false, - }, - "upload undefined config - panics": { - chainConfigs: NewChainAccessConfigs(types.AccessConfig{}, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - panics: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := DefaultAuthorizationPolicy{} - if !spec.panics { - got := policy.CanCreateCode(spec.chainConfigs, myActorAddress, spec.contractInstConf) - assert.Equal(t, spec.exp, got) - return - } - assert.Panics(t, func() { - policy.CanCreateCode(spec.chainConfigs, myActorAddress, spec.contractInstConf) - }) - }) - } -} - -func TestDefaultAuthzPolicyCanInstantiateContract(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - specs := map[string]struct { - config types.AccessConfig - actor sdk.AccAddress - exp bool - panics bool - }{ - "nobody": { - config: types.AllowNobody, - exp: false, - }, - "everybody": { - config: types.AllowEverybody, - exp: true, - }, - "only address - same": { - config: types.AccessTypeOnlyAddress.With(myActorAddress), - exp: true, - }, - "only address - different": { - config: types.AccessTypeOnlyAddress.With(otherAddress), - exp: false, - }, - "any address - included": { - config: types.AccessTypeAnyOfAddresses.With(otherAddress, myActorAddress), - exp: true, - }, - "any address - not included": { - config: types.AccessTypeAnyOfAddresses.With(otherAddress), - exp: false, - }, - "undefined config - panics": { - config: types.AccessConfig{}, - panics: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := DefaultAuthorizationPolicy{} - if !spec.panics { - got := policy.CanInstantiateContract(spec.config, myActorAddress) - assert.Equal(t, spec.exp, got) - return - } - assert.Panics(t, func() { - policy.CanInstantiateContract(spec.config, myActorAddress) - }) - }) - } -} - -func TestDefaultAuthzPolicyCanModifyContract(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - - specs := map[string]struct { - admin sdk.AccAddress - exp bool - }{ - "same as actor": { - admin: myActorAddress, - exp: true, - }, - "different admin": { - admin: otherAddress, - exp: false, - }, - "no admin": { - exp: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := DefaultAuthorizationPolicy{} - got := policy.CanModifyContract(spec.admin, myActorAddress) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestDefaultAuthzPolicyCanModifyCodeAccessConfig(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - - specs := map[string]struct { - admin sdk.AccAddress - subset bool - exp bool - }{ - "same as actor - subset": { - admin: myActorAddress, - subset: true, - exp: true, - }, - "same as actor - not subset": { - admin: myActorAddress, - subset: false, - exp: false, - }, - "different admin": { - admin: otherAddress, - exp: false, - }, - "no admin": { - exp: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := DefaultAuthorizationPolicy{} - got := policy.CanModifyCodeAccessConfig(spec.admin, myActorAddress, spec.subset) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestGovAuthzPolicyCanCreateCode(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - specs := map[string]struct { - chainConfigs ChainAccessConfigs - contractInstConf types.AccessConfig - actor sdk.AccAddress - }{ - "upload nobody": { - chainConfigs: NewChainAccessConfigs(types.AllowNobody, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload everybody": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload only address - same": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeOnlyAddress.With(myActorAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload only address - different": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeOnlyAddress.With(otherAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload any address - included": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeAnyOfAddresses.With(otherAddress, myActorAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "upload any address - not included": { - chainConfigs: NewChainAccessConfigs(types.AccessTypeAnyOfAddresses.With(otherAddress), types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - "contract config - subtype": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowEverybody), - contractInstConf: types.AccessTypeAnyOfAddresses.With(myActorAddress), - }, - "contract config - not subtype": { - chainConfigs: NewChainAccessConfigs(types.AllowEverybody, types.AllowNobody), - contractInstConf: types.AllowEverybody, - }, - "upload undefined config - not panics": { - chainConfigs: NewChainAccessConfigs(types.AccessConfig{}, types.AllowEverybody), - contractInstConf: types.AllowEverybody, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := GovAuthorizationPolicy{} - got := policy.CanCreateCode(spec.chainConfigs, myActorAddress, spec.contractInstConf) - assert.True(t, got) - }) - } -} - -func TestGovAuthzPolicyCanInstantiateContract(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - specs := map[string]struct { - config types.AccessConfig - actor sdk.AccAddress - }{ - "nobody": { - config: types.AllowNobody, - }, - "everybody": { - config: types.AllowEverybody, - }, - "only address - same": { - config: types.AccessTypeOnlyAddress.With(myActorAddress), - }, - "only address - different": { - config: types.AccessTypeOnlyAddress.With(otherAddress), - }, - "any address - included": { - config: types.AccessTypeAnyOfAddresses.With(otherAddress, myActorAddress), - }, - "any address - not included": { - config: types.AccessTypeAnyOfAddresses.With(otherAddress), - }, - "undefined config - panics": { - config: types.AccessConfig{}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := GovAuthorizationPolicy{} - got := policy.CanInstantiateContract(spec.config, myActorAddress) - assert.True(t, got) - }) - } -} - -func TestGovAuthzPolicyCanModifyContract(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - - specs := map[string]struct { - admin sdk.AccAddress - }{ - "same as actor": { - admin: myActorAddress, - }, - "different admin": { - admin: otherAddress, - }, - "no admin": {}, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := GovAuthorizationPolicy{} - got := policy.CanModifyContract(spec.admin, myActorAddress) - assert.True(t, got) - }) - } -} - -func TestGovAuthzPolicyCanModifyCodeAccessConfig(t *testing.T) { - myActorAddress := RandomAccountAddress(t) - otherAddress := RandomAccountAddress(t) - - specs := map[string]struct { - admin sdk.AccAddress - subset bool - }{ - "same as actor - subset": { - admin: myActorAddress, - subset: true, - }, - "same as actor - not subset": { - admin: myActorAddress, - subset: false, - }, - "different admin": { - admin: otherAddress, - }, - "no admin": {}, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - policy := GovAuthorizationPolicy{} - got := policy.CanModifyCodeAccessConfig(spec.admin, myActorAddress, spec.subset) - assert.True(t, got) - }) - } -} diff --git a/x/wasm/keeper/bench_test.go b/x/wasm/keeper/bench_test.go deleted file mode 100644 index 2780665..0000000 --- a/x/wasm/keeper/bench_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package keeper - -import ( - "os" - "testing" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// BenchmarkVerification benchmarks secp256k1 verification which is 1000 gas based on cpu time. -// -// Just this function is copied from -// https://github.com/cosmos/cosmos-sdk/blob/90e9370bd80d9a3d41f7203ddb71166865561569/crypto/keys/internal/benchmarking/bench.go#L48-L62 -// And thus under the GO license (BSD style) -func BenchmarkGasNormalization(b *testing.B) { - priv := secp256k1.GenPrivKey() - pub := priv.PubKey() - - // use a short message, so this time doesn't get dominated by hashing. - message := []byte("Hello, world!") - signature, err := priv.Sign(message) - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - pub.VerifySignature(message, signature) - } -} - -// By comparing the timing for queries on pinned vs unpinned, the difference gives us the overhead of -// instantiating an unpinned contract. That value can be used to determine a reasonable gas price -// for the InstantiationCost -func BenchmarkInstantiationOverhead(b *testing.B) { - specs := map[string]struct { - pinned bool - db func() dbm.DB - }{ - "unpinned, memory db": { - db: func() dbm.DB { return dbm.NewMemDB() }, - }, - "pinned, memory db": { - db: func() dbm.DB { return dbm.NewMemDB() }, - pinned: true, - }, - } - for name, spec := range specs { - b.Run(name, func(b *testing.B) { - wasmConfig := types.WasmConfig{MemoryCacheSize: 0} - ctx, keepers := createTestInput(b, false, AvailableCapabilities, wasmConfig, spec.db()) - example := InstantiateHackatomExampleContract(b, ctx, keepers) - if spec.pinned { - require.NoError(b, keepers.ContractKeeper.PinCode(ctx, example.CodeID)) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := keepers.WasmKeeper.QuerySmart(ctx, example.Contract, []byte(`{"verifier":{}}`)) - require.NoError(b, err) - } - }) - } -} - -// Calculate the time it takes to compile some wasm code the first time. -// This will help us adjust pricing for UploadCode -func BenchmarkCompilation(b *testing.B) { - specs := map[string]struct { - wasmFile string - }{ - "hackatom": { - wasmFile: "./testdata/hackatom.wasm", - }, - "burner": { - wasmFile: "./testdata/burner.wasm", - }, - "ibc_reflect": { - wasmFile: "./testdata/ibc_reflect.wasm", - }, - } - - for name, spec := range specs { - b.Run(name, func(b *testing.B) { - wasmConfig := types.WasmConfig{MemoryCacheSize: 0} - db := dbm.NewMemDB() - ctx, keepers := createTestInput(b, false, AvailableCapabilities, wasmConfig, db) - - // print out code size for comparisons - code, err := os.ReadFile(spec.wasmFile) - require.NoError(b, err) - b.Logf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b(size: %d) ", len(code)) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = StoreExampleContract(b, ctx, keepers, spec.wasmFile) - } - }) - } -} diff --git a/x/wasm/keeper/contract_keeper.go b/x/wasm/keeper/contract_keeper.go deleted file mode 100644 index 2a74039..0000000 --- a/x/wasm/keeper/contract_keeper.go +++ /dev/null @@ -1,130 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.ContractOpsKeeper = PermissionedKeeper{} - -// decoratedKeeper contains a subset of the wasm keeper that are already or can be guarded by an authorization policy in the future -type decoratedKeeper interface { - create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *types.AccessConfig, authZ AuthorizationPolicy) (codeID uint64, checksum []byte, err error) - - instantiate( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - addressGenerator AddressGenerator, - authZ AuthorizationPolicy, - ) (sdk.AccAddress, []byte, error) - - migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newCodeID uint64, msg []byte, authZ AuthorizationPolicy) ([]byte, error) - setContractAdmin(ctx sdk.Context, contractAddress, caller, newAdmin sdk.AccAddress, authZ AuthorizationPolicy) error - pinCode(ctx sdk.Context, codeID uint64) error - unpinCode(ctx sdk.Context, codeID uint64) error - execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) - Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) - setContractInfoExtension(ctx sdk.Context, contract sdk.AccAddress, extra types.ContractInfoExtension) error - setAccessConfig(ctx sdk.Context, codeID uint64, caller sdk.AccAddress, newConfig types.AccessConfig, autz AuthorizationPolicy) error - ClassicAddressGenerator() AddressGenerator -} - -type PermissionedKeeper struct { - authZPolicy AuthorizationPolicy - nested decoratedKeeper -} - -func NewPermissionedKeeper(nested decoratedKeeper, authZPolicy AuthorizationPolicy) *PermissionedKeeper { - return &PermissionedKeeper{authZPolicy: authZPolicy, nested: nested} -} - -func NewGovPermissionKeeper(nested decoratedKeeper) *PermissionedKeeper { - return NewPermissionedKeeper(nested, GovAuthorizationPolicy{}) -} - -func NewDefaultPermissionKeeper(nested decoratedKeeper) *PermissionedKeeper { - return NewPermissionedKeeper(nested, DefaultAuthorizationPolicy{}) -} - -func (p PermissionedKeeper) Create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *types.AccessConfig) (codeID uint64, checksum []byte, err error) { - return p.nested.create(ctx, creator, wasmCode, instantiateAccess, p.authZPolicy) -} - -// Instantiate creates an instance of a WASM contract using the classic sequence based address generator -func (p PermissionedKeeper) Instantiate( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, -) (sdk.AccAddress, []byte, error) { - return p.nested.instantiate(ctx, codeID, creator, admin, initMsg, label, deposit, p.nested.ClassicAddressGenerator(), p.authZPolicy) -} - -// Instantiate2 creates an instance of a WASM contract using the predictable address generator -func (p PermissionedKeeper) Instantiate2( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - salt []byte, - fixMsg bool, -) (sdk.AccAddress, []byte, error) { - return p.nested.instantiate( - ctx, - codeID, - creator, - admin, - initMsg, - label, - deposit, - PredicableAddressGenerator(creator, salt, initMsg, fixMsg), - p.authZPolicy, - ) -} - -func (p PermissionedKeeper) Execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) { - return p.nested.execute(ctx, contractAddress, caller, msg, coins) -} - -func (p PermissionedKeeper) Migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newCodeID uint64, msg []byte) ([]byte, error) { - return p.nested.migrate(ctx, contractAddress, caller, newCodeID, msg, p.authZPolicy) -} - -func (p PermissionedKeeper) Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) { - return p.nested.Sudo(ctx, contractAddress, msg) -} - -func (p PermissionedKeeper) UpdateContractAdmin(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newAdmin sdk.AccAddress) error { - return p.nested.setContractAdmin(ctx, contractAddress, caller, newAdmin, p.authZPolicy) -} - -func (p PermissionedKeeper) ClearContractAdmin(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress) error { - return p.nested.setContractAdmin(ctx, contractAddress, caller, nil, p.authZPolicy) -} - -func (p PermissionedKeeper) PinCode(ctx sdk.Context, codeID uint64) error { - return p.nested.pinCode(ctx, codeID) -} - -func (p PermissionedKeeper) UnpinCode(ctx sdk.Context, codeID uint64) error { - return p.nested.unpinCode(ctx, codeID) -} - -// SetContractInfoExtension updates the extra attributes that can be stored with the contract info -func (p PermissionedKeeper) SetContractInfoExtension(ctx sdk.Context, contract sdk.AccAddress, extra types.ContractInfoExtension) error { - return p.nested.setContractInfoExtension(ctx, contract, extra) -} - -// SetAccessConfig updates the access config of a code id. -func (p PermissionedKeeper) SetAccessConfig(ctx sdk.Context, codeID uint64, caller sdk.AccAddress, newConfig types.AccessConfig) error { - return p.nested.setAccessConfig(ctx, codeID, caller, newConfig, p.authZPolicy) -} diff --git a/x/wasm/keeper/contract_keeper_test.go b/x/wasm/keeper/contract_keeper_test.go deleted file mode 100644 index aa660d1..0000000 --- a/x/wasm/keeper/contract_keeper_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - "math" - "strings" - "testing" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestInstantiate2(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - parentCtx = parentCtx.WithGasMeter(sdk.NewInfiniteGasMeter()) - - example := StoreHackatomExampleContract(t, parentCtx, keepers) - otherExample := StoreReflectContract(t, parentCtx, keepers) - mock := &wasmtesting.MockWasmer{} - wasmtesting.MakeInstantiable(mock) - keepers.WasmKeeper.wasmVM = mock // set mock to not fail on contract init message - - verifierAddr := RandomAccountAddress(t) - beneficiaryAddr := RandomAccountAddress(t) - initMsg := mustMarshal(t, HackatomExampleInitMsg{Verifier: verifierAddr, Beneficiary: beneficiaryAddr}) - otherAddr := keepers.Faucet.NewFundedRandomAccount(parentCtx, sdk.NewInt64Coin("denom", 1_000_000_000)) - - const ( - mySalt = "my salt" - myLabel = "my label" - ) - // create instances for duplicate checks - exampleContract := func(t *testing.T, ctx sdk.Context, fixMsg bool) { - _, _, err := keepers.ContractKeeper.Instantiate2( - ctx, - example.CodeID, - example.CreatorAddr, - nil, - initMsg, - myLabel, - sdk.NewCoins(sdk.NewInt64Coin("denom", 1)), - []byte(mySalt), - fixMsg, - ) - require.NoError(t, err) - } - exampleWithFixMsg := func(t *testing.T, ctx sdk.Context) { - exampleContract(t, ctx, true) - } - exampleWithoutFixMsg := func(t *testing.T, ctx sdk.Context) { - exampleContract(t, ctx, false) - } - specs := map[string]struct { - setup func(t *testing.T, ctx sdk.Context) - codeID uint64 - sender sdk.AccAddress - salt []byte - initMsg json.RawMessage - fixMsg bool - expErr error - }{ - "fix msg - generates different address than without fixMsg": { - setup: exampleWithoutFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: initMsg, - fixMsg: true, - }, - "fix msg - different sender": { - setup: exampleWithFixMsg, - codeID: example.CodeID, - sender: otherAddr, - salt: []byte(mySalt), - initMsg: initMsg, - fixMsg: true, - }, - "fix msg - different code": { - setup: exampleWithFixMsg, - codeID: otherExample.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: []byte(`{}`), - fixMsg: true, - }, - "fix msg - different salt": { - setup: exampleWithFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte("other salt"), - initMsg: initMsg, - fixMsg: true, - }, - "fix msg - different init msg": { - setup: exampleWithFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: mustMarshal(t, HackatomExampleInitMsg{Verifier: otherAddr, Beneficiary: beneficiaryAddr}), - fixMsg: true, - }, - "different sender": { - setup: exampleWithoutFixMsg, - codeID: example.CodeID, - sender: otherAddr, - salt: []byte(mySalt), - initMsg: initMsg, - }, - "different code": { - setup: exampleWithoutFixMsg, - codeID: otherExample.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: []byte(`{}`), - }, - "different salt": { - setup: exampleWithoutFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte(`other salt`), - initMsg: initMsg, - }, - "different init msg - reject same address": { - setup: exampleWithoutFixMsg, - codeID: example.CodeID, - sender: example.CreatorAddr, - salt: []byte(mySalt), - initMsg: mustMarshal(t, HackatomExampleInitMsg{Verifier: otherAddr, Beneficiary: beneficiaryAddr}), - expErr: types.ErrDuplicate, - }, - "fix msg - long msg": { - setup: exampleWithFixMsg, - codeID: example.CodeID, - sender: otherAddr, - salt: []byte(mySalt), - initMsg: []byte(fmt.Sprintf(`{"foo":%q}`, strings.Repeat("b", math.MaxInt16+1))), // too long kills CI - fixMsg: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - spec.setup(t, ctx) - gotAddr, _, gotErr := keepers.ContractKeeper.Instantiate2( - ctx, - spec.codeID, - spec.sender, - nil, - spec.initMsg, - myLabel, - sdk.NewCoins(sdk.NewInt64Coin("denom", 2)), - spec.salt, - spec.fixMsg, - ) - if spec.expErr != nil { - assert.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.NotEmpty(t, gotAddr) - }) - } -} diff --git a/x/wasm/keeper/events.go b/x/wasm/keeper/events.go deleted file mode 100644 index 47068aa..0000000 --- a/x/wasm/keeper/events.go +++ /dev/null @@ -1,68 +0,0 @@ -package keeper - -import ( - "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// newWasmModuleEvent creates with wasm module event for interacting with the given contract. Adds custom attributes -// to this event. -func newWasmModuleEvent(customAttributes []wasmvmtypes.EventAttribute, contractAddr sdk.AccAddress) (sdk.Events, error) { - attrs, err := contractSDKEventAttributes(customAttributes, contractAddr) - if err != nil { - return nil, err - } - - // each wasm invocation always returns one sdk.Event - return sdk.Events{sdk.NewEvent(types.WasmModuleEventType, attrs...)}, nil -} - -const eventTypeMinLength = 2 - -// newCustomEvents converts wasmvm events from a contract response to sdk type events -func newCustomEvents(evts wasmvmtypes.Events, contractAddr sdk.AccAddress) (sdk.Events, error) { - events := make(sdk.Events, 0, len(evts)) - for _, e := range evts { - typ := strings.TrimSpace(e.Type) - if len(typ) <= eventTypeMinLength { - return nil, errorsmod.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Event type too short: '%s'", typ)) - } - attributes, err := contractSDKEventAttributes(e.Attributes, contractAddr) - if err != nil { - return nil, err - } - events = append(events, sdk.NewEvent(fmt.Sprintf("%s%s", types.CustomContractEventPrefix, typ), attributes...)) - } - return events, nil -} - -// convert and add contract address issuing this event -func contractSDKEventAttributes(customAttributes []wasmvmtypes.EventAttribute, contractAddr sdk.AccAddress) ([]sdk.Attribute, error) { - attrs := []sdk.Attribute{sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddr.String())} - // append attributes from wasm to the sdk.Event - for _, l := range customAttributes { - // ensure key and value are non-empty (and trim what is there) - key := strings.TrimSpace(l.Key) - if len(key) == 0 { - return nil, errorsmod.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Empty attribute key. Value: %s", l.Value)) - } - value := strings.TrimSpace(l.Value) - // TODO: check if this is legal in the SDK - if it is, we can remove this check - if len(value) == 0 { - return nil, errorsmod.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Empty attribute value. Key: %s", key)) - } - // and reserve all _* keys for our use (not contract) - if strings.HasPrefix(key, types.AttributeReservedPrefix) { - return nil, errorsmod.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Attribute key starts with reserved prefix %s: '%s'", types.AttributeReservedPrefix, key)) - } - attrs = append(attrs, sdk.NewAttribute(key, value)) - } - return attrs, nil -} diff --git a/x/wasm/keeper/events_test.go b/x/wasm/keeper/events_test.go deleted file mode 100644 index 5320b28..0000000 --- a/x/wasm/keeper/events_test.go +++ /dev/null @@ -1,290 +0,0 @@ -package keeper - -import ( - "context" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestHasWasmModuleEvent(t *testing.T) { - myContractAddr := RandomAccountAddress(t) - specs := map[string]struct { - srcEvents []sdk.Event - exp bool - }{ - "event found": { - srcEvents: []sdk.Event{ - sdk.NewEvent(types.WasmModuleEventType, sdk.NewAttribute("_contract_address", myContractAddr.String())), - }, - exp: true, - }, - "different event: not found": { - srcEvents: []sdk.Event{ - sdk.NewEvent(types.CustomContractEventPrefix, sdk.NewAttribute("_contract_address", myContractAddr.String())), - }, - exp: false, - }, - "event with different address: not found": { - srcEvents: []sdk.Event{ - sdk.NewEvent(types.WasmModuleEventType, sdk.NewAttribute("_contract_address", RandomBech32AccountAddress(t))), - }, - exp: false, - }, - "no event": { - srcEvents: []sdk.Event{}, - exp: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - em := sdk.NewEventManager() - em.EmitEvents(spec.srcEvents) - ctx := sdk.Context{}.WithContext(context.Background()).WithEventManager(em) - - got := hasWasmModuleEvent(ctx, myContractAddr) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestNewCustomEvents(t *testing.T) { - myContract := RandomAccountAddress(t) - specs := map[string]struct { - src wasmvmtypes.Events - exp sdk.Events - isError bool - }{ - "all good": { - src: wasmvmtypes.Events{{ - Type: "foo", - Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myVal"}}, - }}, - exp: sdk.Events{sdk.NewEvent("wasm-foo", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal"))}, - }, - "multiple attributes": { - src: wasmvmtypes.Events{{ - Type: "foo", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "myKey", Value: "myVal"}, - {Key: "myOtherKey", Value: "myOtherVal"}, - }, - }}, - exp: sdk.Events{sdk.NewEvent("wasm-foo", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal"), - sdk.NewAttribute("myOtherKey", "myOtherVal"))}, - }, - "multiple events": { - src: wasmvmtypes.Events{{ - Type: "foo", - Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myVal"}}, - }, { - Type: "bar", - Attributes: []wasmvmtypes.EventAttribute{{Key: "otherKey", Value: "otherVal"}}, - }}, - exp: sdk.Events{ - sdk.NewEvent("wasm-foo", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal")), - sdk.NewEvent("wasm-bar", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("otherKey", "otherVal")), - }, - }, - "without attributes": { - src: wasmvmtypes.Events{{ - Type: "foo", - }}, - exp: sdk.Events{sdk.NewEvent("wasm-foo", - sdk.NewAttribute("_contract_address", myContract.String()))}, - }, - "error on short event type": { - src: wasmvmtypes.Events{{ - Type: "f", - }}, - isError: true, - }, - "error on _contract_address": { - src: wasmvmtypes.Events{{ - Type: "foo", - Attributes: []wasmvmtypes.EventAttribute{{Key: "_contract_address", Value: RandomBech32AccountAddress(t)}}, - }}, - isError: true, - }, - "error on reserved prefix": { - src: wasmvmtypes.Events{{ - Type: "wasm", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "_reserved", Value: "is skipped"}, - {Key: "normal", Value: "is used"}, - }, - }}, - isError: true, - }, - "error on empty value": { - src: wasmvmtypes.Events{{ - Type: "boom", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - {Key: "key", Value: ""}, - }, - }}, - isError: true, - }, - "error on empty key": { - src: wasmvmtypes.Events{{ - Type: "boom", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - {Key: "", Value: "value"}, - }, - }}, - isError: true, - }, - "error on whitespace type": { - src: wasmvmtypes.Events{{ - Type: " f ", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - }, - }}, - isError: true, - }, - "error on only whitespace key": { - src: wasmvmtypes.Events{{ - Type: "boom", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - {Key: "\n\n\n\n", Value: "value"}, - }, - }}, - isError: true, - }, - "error on only whitespace value": { - src: wasmvmtypes.Events{{ - Type: "boom", - Attributes: []wasmvmtypes.EventAttribute{ - {Key: "some", Value: "data"}, - {Key: "myKey", Value: " \t\r\n"}, - }, - }}, - isError: true, - }, - "strip out whitespace": { - src: wasmvmtypes.Events{{ - Type: " food\n", - Attributes: []wasmvmtypes.EventAttribute{{Key: "my Key", Value: "\tmyVal"}}, - }}, - exp: sdk.Events{sdk.NewEvent("wasm-food", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("my Key", "myVal"))}, - }, - "empty event elements": { - src: make(wasmvmtypes.Events, 10), - isError: true, - }, - "nil": { - exp: sdk.Events{}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotEvent, err := newCustomEvents(spec.src, myContract) - if spec.isError { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, spec.exp, gotEvent) - } - }) - } -} - -func TestNewWasmModuleEvent(t *testing.T) { - myContract := RandomAccountAddress(t) - specs := map[string]struct { - src []wasmvmtypes.EventAttribute - exp sdk.Events - isError bool - }{ - "all good": { - src: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myVal"}}, - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal"))}, - }, - "multiple attributes": { - src: []wasmvmtypes.EventAttribute{ - {Key: "myKey", Value: "myVal"}, - {Key: "myOtherKey", Value: "myOtherVal"}, - }, - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("myKey", "myVal"), - sdk.NewAttribute("myOtherKey", "myOtherVal"))}, - }, - "without attributes": { - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()))}, - }, - "error on _contract_address": { - src: []wasmvmtypes.EventAttribute{{Key: "_contract_address", Value: RandomBech32AccountAddress(t)}}, - isError: true, - }, - "error on whitespace key": { - src: []wasmvmtypes.EventAttribute{{Key: " ", Value: "value"}}, - isError: true, - }, - "error on whitespace value": { - src: []wasmvmtypes.EventAttribute{{Key: "key", Value: "\n\n\n"}}, - isError: true, - }, - "strip whitespace": { - src: []wasmvmtypes.EventAttribute{{Key: " my-real-key ", Value: "\n\n\nsome-val\t\t\t"}}, - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()), - sdk.NewAttribute("my-real-key", "some-val"))}, - }, - "empty elements": { - src: make([]wasmvmtypes.EventAttribute, 10), - isError: true, - }, - "nil": { - exp: sdk.Events{sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", myContract.String()), - )}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotEvent, err := newWasmModuleEvent(spec.src, myContract) - if spec.isError { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, spec.exp, gotEvent) - } - }) - } -} - -// returns true when a wasm module event was emitted for this contract already -func hasWasmModuleEvent(ctx sdk.Context, contractAddr sdk.AccAddress) bool { - for _, e := range ctx.EventManager().Events() { - if e.Type == types.WasmModuleEventType { - for _, a := range e.Attributes { - if a.Key == types.AttributeKeyContractAddr && a.Value == contractAddr.String() { - return true - } - } - } - } - return false -} diff --git a/x/wasm/keeper/gas_register.go b/x/wasm/keeper/gas_register.go deleted file mode 100644 index e26a19a..0000000 --- a/x/wasm/keeper/gas_register.go +++ /dev/null @@ -1,253 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - // DefaultGasMultiplier is how many CosmWasm gas points = 1 Cosmos SDK gas point. - // - // CosmWasm gas strategy is documented in https://github.com/CosmWasm/cosmwasm/blob/v1.0.0-beta/docs/GAS.md. - // Cosmos SDK reference costs can be found here: https://github.com/cosmos/cosmos-sdk/blob/v0.42.10/store/types/gas.go#L198-L209. - // - // The original multiplier of 100 up to CosmWasm 0.16 was based on - // "A write at ~3000 gas and ~200us = 10 gas per us (microsecond) cpu/io - // Rough timing have 88k gas at 90us, which is equal to 1k sdk gas... (one read)" - // as well as manual Wasmer benchmarks from 2019. This was then multiplied by 150_000 - // in the 0.16 -> 1.0 upgrade (https://github.com/CosmWasm/cosmwasm/pull/1120). - // - // The multiplier deserves more reproducible benchmarking and a strategy that allows easy adjustments. - // This is tracked in https://github.com/terpnetwork/terp-core/issues/566 and https://github.com/terpnetwork/terp-core/issues/631. - // Gas adjustments are consensus breaking but may happen in any release marked as consensus breaking. - // Do not make assumptions on how much gas an operation will consume in places that are hard to adjust, - // such as hardcoding them in contracts. - // - // Please note that all gas prices returned to wasmvm should have this multiplied. - // Benchmarks and numbers were discussed in: https://github.com/terpnetwork/terp-core/pull/634#issuecomment-938055852 - DefaultGasMultiplier uint64 = 140_000_000 - // DefaultInstanceCost is how much SDK gas we charge each time we load a WASM instance. - // Creating a new instance is costly, and this helps put a recursion limit to contracts calling contracts. - // Benchmarks and numbers were discussed in: https://github.com/terpnetwork/terp-core/pull/634#issuecomment-938056803 - DefaultInstanceCost uint64 = 60_000 - // DefaultCompileCost is how much SDK gas is charged *per byte* for compiling WASM code. - // Benchmarks and numbers were discussed in: https://github.com/terpnetwork/terp-core/pull/634#issuecomment-938056803 - DefaultCompileCost uint64 = 3 - // DefaultEventAttributeDataCost is how much SDK gas is charged *per byte* for attribute data in events. - // This is used with len(key) + len(value) - DefaultEventAttributeDataCost uint64 = 1 - // DefaultContractMessageDataCost is how much SDK gas is charged *per byte* of the message that goes to the contract - // This is used with len(msg). Note that the message is deserialized in the receiving contract and this is charged - // with wasm gas already. The derserialization of results is also charged in wasmvm. I am unsure if we need to add - // additional costs here. - // Note: also used for error fields on reply, and data on reply. Maybe these should be pulled out to a different (non-zero) field - DefaultContractMessageDataCost uint64 = 0 - // DefaultPerAttributeCost is how much SDK gas we charge per attribute count. - DefaultPerAttributeCost uint64 = 10 - // DefaultPerCustomEventCost is how much SDK gas we charge per event count. - DefaultPerCustomEventCost uint64 = 20 - // DefaultEventAttributeDataFreeTier number of bytes of total attribute data we do not charge. - DefaultEventAttributeDataFreeTier = 100 -) - -// default: 0.15 gas. -// see https://github.com/terpnetwork/terp-core/pull/898#discussion_r937727200 -var defaultPerByteUncompressCost = wasmvmtypes.UFraction{ - Numerator: 15, - Denominator: 100, -} - -// DefaultPerByteUncompressCost is how much SDK gas we charge per source byte to unpack -func DefaultPerByteUncompressCost() wasmvmtypes.UFraction { - return defaultPerByteUncompressCost -} - -// GasRegister abstract source for gas costs -type GasRegister interface { - // NewContractInstanceCosts costs to create a new contract instance from code - NewContractInstanceCosts(pinned bool, msgLen int) sdk.Gas - // CompileCosts costs to persist and "compile" a new wasm contract - CompileCosts(byteLength int) sdk.Gas - // UncompressCosts costs to unpack a new wasm contract - UncompressCosts(byteLength int) sdk.Gas - // InstantiateContractCosts costs when interacting with a wasm contract - InstantiateContractCosts(pinned bool, msgLen int) sdk.Gas - // ReplyCosts costs to to handle a message reply - ReplyCosts(pinned bool, reply wasmvmtypes.Reply) sdk.Gas - // EventCosts costs to persist an event - EventCosts(attrs []wasmvmtypes.EventAttribute, events wasmvmtypes.Events) sdk.Gas - // ToWasmVMGas converts from sdk gas to wasmvm gas - ToWasmVMGas(source sdk.Gas) uint64 - // FromWasmVMGas converts from wasmvm gas to sdk gas - FromWasmVMGas(source uint64) sdk.Gas -} - -// WasmGasRegisterConfig config type -type WasmGasRegisterConfig struct { - // InstanceCost costs when interacting with a wasm contract - InstanceCost sdk.Gas - // CompileCosts costs to persist and "compile" a new wasm contract - CompileCost sdk.Gas - // UncompressCost costs per byte to unpack a contract - UncompressCost wasmvmtypes.UFraction - // GasMultiplier is how many cosmwasm gas points = 1 sdk gas point - // SDK reference costs can be found here: https://github.com/cosmos/cosmos-sdk/blob/02c6c9fafd58da88550ab4d7d494724a477c8a68/store/types/gas.go#L153-L164 - GasMultiplier sdk.Gas - // EventPerAttributeCost is how much SDK gas is charged *per byte* for attribute data in events. - // This is used with len(key) + len(value) - EventPerAttributeCost sdk.Gas - // EventAttributeDataCost is how much SDK gas is charged *per byte* for attribute data in events. - // This is used with len(key) + len(value) - EventAttributeDataCost sdk.Gas - // EventAttributeDataFreeTier number of bytes of total attribute data that is free of charge - EventAttributeDataFreeTier uint64 - // ContractMessageDataCost SDK gas charged *per byte* of the message that goes to the contract - // This is used with len(msg) - ContractMessageDataCost sdk.Gas - // CustomEventCost cost per custom event - CustomEventCost uint64 -} - -// DefaultGasRegisterConfig default values -func DefaultGasRegisterConfig() WasmGasRegisterConfig { - return WasmGasRegisterConfig{ - InstanceCost: DefaultInstanceCost, - CompileCost: DefaultCompileCost, - GasMultiplier: DefaultGasMultiplier, - EventPerAttributeCost: DefaultPerAttributeCost, - CustomEventCost: DefaultPerCustomEventCost, - EventAttributeDataCost: DefaultEventAttributeDataCost, - EventAttributeDataFreeTier: DefaultEventAttributeDataFreeTier, - ContractMessageDataCost: DefaultContractMessageDataCost, - UncompressCost: DefaultPerByteUncompressCost(), - } -} - -// WasmGasRegister implements GasRegister interface -type WasmGasRegister struct { - c WasmGasRegisterConfig -} - -// NewDefaultWasmGasRegister creates instance with default values -func NewDefaultWasmGasRegister() WasmGasRegister { - return NewWasmGasRegister(DefaultGasRegisterConfig()) -} - -// NewWasmGasRegister constructor -func NewWasmGasRegister(c WasmGasRegisterConfig) WasmGasRegister { - if c.GasMultiplier == 0 { - panic(errorsmod.Wrap(sdkerrors.ErrLogic, "GasMultiplier can not be 0")) - } - return WasmGasRegister{ - c: c, - } -} - -// NewContractInstanceCosts costs to create a new contract instance from code -func (g WasmGasRegister) NewContractInstanceCosts(pinned bool, msgLen int) storetypes.Gas { - return g.InstantiateContractCosts(pinned, msgLen) -} - -// CompileCosts costs to persist and "compile" a new wasm contract -func (g WasmGasRegister) CompileCosts(byteLength int) storetypes.Gas { - if byteLength < 0 { - panic(errorsmod.Wrap(types.ErrInvalid, "negative length")) - } - return g.c.CompileCost * uint64(byteLength) -} - -// UncompressCosts costs to unpack a new wasm contract -func (g WasmGasRegister) UncompressCosts(byteLength int) sdk.Gas { - if byteLength < 0 { - panic(errorsmod.Wrap(types.ErrInvalid, "negative length")) - } - return g.c.UncompressCost.Mul(uint64(byteLength)).Floor() -} - -// InstantiateContractCosts costs when interacting with a wasm contract -func (g WasmGasRegister) InstantiateContractCosts(pinned bool, msgLen int) sdk.Gas { - if msgLen < 0 { - panic(errorsmod.Wrap(types.ErrInvalid, "negative length")) - } - dataCosts := sdk.Gas(msgLen) * g.c.ContractMessageDataCost - if pinned { - return dataCosts - } - return g.c.InstanceCost + dataCosts -} - -// ReplyCosts costs to to handle a message reply -func (g WasmGasRegister) ReplyCosts(pinned bool, reply wasmvmtypes.Reply) sdk.Gas { - var eventGas sdk.Gas - msgLen := len(reply.Result.Err) - if reply.Result.Ok != nil { - msgLen += len(reply.Result.Ok.Data) - var attrs []wasmvmtypes.EventAttribute - for _, e := range reply.Result.Ok.Events { - eventGas += sdk.Gas(len(e.Type)) * g.c.EventAttributeDataCost - attrs = append(attrs, e.Attributes...) - } - // apply free tier on the whole set not per event - eventGas += g.EventCosts(attrs, nil) - } - return eventGas + g.InstantiateContractCosts(pinned, msgLen) -} - -// EventCosts costs to persist an event -func (g WasmGasRegister) EventCosts(attrs []wasmvmtypes.EventAttribute, events wasmvmtypes.Events) sdk.Gas { - gas, remainingFreeTier := g.eventAttributeCosts(attrs, g.c.EventAttributeDataFreeTier) - for _, e := range events { - gas += g.c.CustomEventCost - gas += sdk.Gas(len(e.Type)) * g.c.EventAttributeDataCost // no free tier with event type - var attrCost sdk.Gas - attrCost, remainingFreeTier = g.eventAttributeCosts(e.Attributes, remainingFreeTier) - gas += attrCost - } - return gas -} - -func (g WasmGasRegister) eventAttributeCosts(attrs []wasmvmtypes.EventAttribute, freeTier uint64) (sdk.Gas, uint64) { - if len(attrs) == 0 { - return 0, freeTier - } - var storedBytes uint64 - for _, l := range attrs { - storedBytes += uint64(len(l.Key)) + uint64(len(l.Value)) - } - storedBytes, freeTier = calcWithFreeTier(storedBytes, freeTier) - // total Length * costs + attribute count * costs - r := sdk.NewIntFromUint64(g.c.EventAttributeDataCost).Mul(sdk.NewIntFromUint64(storedBytes)). - Add(sdk.NewIntFromUint64(g.c.EventPerAttributeCost).Mul(sdk.NewIntFromUint64(uint64(len(attrs))))) - if !r.IsUint64() { - panic(sdk.ErrorOutOfGas{Descriptor: "overflow"}) - } - return r.Uint64(), freeTier -} - -// apply free tier -func calcWithFreeTier(storedBytes uint64, freeTier uint64) (uint64, uint64) { - if storedBytes <= freeTier { - return 0, freeTier - storedBytes - } - storedBytes -= freeTier - return storedBytes, 0 -} - -// ToWasmVMGas convert to wasmVM contract runtime gas unit -func (g WasmGasRegister) ToWasmVMGas(source storetypes.Gas) uint64 { - x := source * g.c.GasMultiplier - if x < source { - panic(sdk.ErrorOutOfGas{Descriptor: "overflow"}) - } - return x -} - -// FromWasmVMGas converts to SDK gas unit -func (g WasmGasRegister) FromWasmVMGas(source uint64) sdk.Gas { - return source / g.c.GasMultiplier -} diff --git a/x/wasm/keeper/gas_register_test.go b/x/wasm/keeper/gas_register_test.go deleted file mode 100644 index 3a29e07..0000000 --- a/x/wasm/keeper/gas_register_test.go +++ /dev/null @@ -1,472 +0,0 @@ -package keeper - -import ( - "math" - "strings" - "testing" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" -) - -func TestCompileCosts(t *testing.T) { - specs := map[string]struct { - srcLen int - srcConfig WasmGasRegisterConfig - exp sdk.Gas - expPanic bool - }{ - "one byte": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(3), // DefaultCompileCost - }, - "zero byte": { - srcLen: 0, - srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(0), - }, - "negative len": { - srcLen: -1, - srcConfig: DefaultGasRegisterConfig(), - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - NewWasmGasRegister(spec.srcConfig).CompileCosts(spec.srcLen) - }) - return - } - gotGas := NewWasmGasRegister(spec.srcConfig).CompileCosts(spec.srcLen) - assert.Equal(t, spec.exp, gotGas) - }) - } -} - -func TestNewContractInstanceCosts(t *testing.T) { - specs := map[string]struct { - srcLen int - srcConfig WasmGasRegisterConfig - pinned bool - exp sdk.Gas - expPanic bool - }{ - "small msg - pinned": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: DefaultContractMessageDataCost, - }, - "big msg - pinned": { - srcLen: math.MaxUint32, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: DefaultContractMessageDataCost * sdk.Gas(math.MaxUint32), - }, - "empty msg - pinned": { - srcLen: 0, - pinned: true, - srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(0), - }, - "small msg - unpinned": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultContractMessageDataCost + DefaultInstanceCost, - }, - "big msg - unpinned": { - srcLen: math.MaxUint32, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultContractMessageDataCost*math.MaxUint32 + DefaultInstanceCost, - }, - "empty msg - unpinned": { - srcLen: 0, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost, - }, - - "negative len": { - srcLen: -1, - srcConfig: DefaultGasRegisterConfig(), - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - NewWasmGasRegister(spec.srcConfig).NewContractInstanceCosts(spec.pinned, spec.srcLen) - }) - return - } - gotGas := NewWasmGasRegister(spec.srcConfig).NewContractInstanceCosts(spec.pinned, spec.srcLen) - assert.Equal(t, spec.exp, gotGas) - }) - } -} - -func TestContractInstanceCosts(t *testing.T) { - // same as TestNewContractInstanceCosts currently - specs := map[string]struct { - srcLen int - srcConfig WasmGasRegisterConfig - pinned bool - exp sdk.Gas - expPanic bool - }{ - "small msg - pinned": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: DefaultContractMessageDataCost, - }, - "big msg - pinned": { - srcLen: math.MaxUint32, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: DefaultContractMessageDataCost * math.MaxUint32, - }, - "empty msg - pinned": { - srcLen: 0, - pinned: true, - srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(0), - }, - "small msg - unpinned": { - srcLen: 1, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultContractMessageDataCost + DefaultInstanceCost, - }, - "big msg - unpinned": { - srcLen: math.MaxUint32, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultContractMessageDataCost*math.MaxUint32 + DefaultInstanceCost, - }, - "empty msg - unpinned": { - srcLen: 0, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost, - }, - - "negative len": { - srcLen: -1, - srcConfig: DefaultGasRegisterConfig(), - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - NewWasmGasRegister(spec.srcConfig).InstantiateContractCosts(spec.pinned, spec.srcLen) - }) - return - } - gotGas := NewWasmGasRegister(spec.srcConfig).InstantiateContractCosts(spec.pinned, spec.srcLen) - assert.Equal(t, spec.exp, gotGas) - }) - } -} - -func TestReplyCost(t *testing.T) { - specs := map[string]struct { - src wasmvmtypes.Reply - srcConfig WasmGasRegisterConfig - pinned bool - exp sdk.Gas - expPanic bool - }{ - "subcall response with events and data - pinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myData"}}}, - }, - Data: []byte{0x1}, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost + DefaultContractMessageDataCost, // 3 == len("foo") - }, - "subcall response with events - pinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myData"}}}, - }, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost, // 3 == len("foo") - }, - "subcall response with events exceeds free tier- pinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: strings.Repeat("x", DefaultEventAttributeDataFreeTier), Value: "myData"}}}, - }, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: (3+6)*DefaultEventAttributeDataCost + DefaultPerAttributeCost, // 3 == len("foo"), 6 == len("myData") - }, - "subcall response error - pinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Err: "foo", - }, - }, - srcConfig: DefaultGasRegisterConfig(), - pinned: true, - exp: 3 * DefaultContractMessageDataCost, - }, - "subcall response with events and data - unpinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myData"}}}, - }, - Data: []byte{0x1}, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost + 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost + DefaultContractMessageDataCost, - }, - "subcall response with events - unpinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: "myKey", Value: "myData"}}}, - }, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost + 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost, - }, - "subcall response with events exceeds free tier- unpinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: []wasmvmtypes.Event{ - {Type: "foo", Attributes: []wasmvmtypes.EventAttribute{{Key: strings.Repeat("x", DefaultEventAttributeDataFreeTier), Value: "myData"}}}, - }, - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost + (3+6)*DefaultEventAttributeDataCost + DefaultPerAttributeCost, // 3 == len("foo"), 6 == len("myData") - }, - "subcall response error - unpinned": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Err: "foo", - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost + 3*DefaultContractMessageDataCost, - }, - "subcall response with empty events": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: make([]wasmvmtypes.Event, 10), - }, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost, - }, - "subcall response with events unset": { - src: wasmvmtypes.Reply{ - Result: wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{}, - }, - }, - srcConfig: DefaultGasRegisterConfig(), - exp: DefaultInstanceCost, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - NewWasmGasRegister(spec.srcConfig).ReplyCosts(spec.pinned, spec.src) - }) - return - } - gotGas := NewWasmGasRegister(spec.srcConfig).ReplyCosts(spec.pinned, spec.src) - assert.Equal(t, spec.exp, gotGas) - }) - } -} - -func TestEventCosts(t *testing.T) { - // most cases are covered in TestReplyCost already. This ensures some edge cases - specs := map[string]struct { - srcAttrs []wasmvmtypes.EventAttribute - srcEvents wasmvmtypes.Events - expGas sdk.Gas - }{ - "empty events": { - srcEvents: make([]wasmvmtypes.Event, 1), - expGas: DefaultPerCustomEventCost, - }, - "empty attributes": { - srcAttrs: make([]wasmvmtypes.EventAttribute, 1), - expGas: DefaultPerAttributeCost, - }, - "both nil": { - expGas: 0, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotGas := NewDefaultWasmGasRegister().EventCosts(spec.srcAttrs, spec.srcEvents) - assert.Equal(t, spec.expGas, gotGas) - }) - } -} - -func TestToWasmVMGasConversion(t *testing.T) { - specs := map[string]struct { - src storetypes.Gas - srcConfig WasmGasRegisterConfig - exp uint64 - expPanic bool - }{ - "0": { - src: 0, - exp: 0, - srcConfig: DefaultGasRegisterConfig(), - }, - "max": { - srcConfig: WasmGasRegisterConfig{ - GasMultiplier: 1, - }, - src: math.MaxUint64, - exp: math.MaxUint64, - }, - "overflow": { - srcConfig: WasmGasRegisterConfig{ - GasMultiplier: 2, - }, - src: math.MaxUint64, - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - r := NewWasmGasRegister(spec.srcConfig) - _ = r.ToWasmVMGas(spec.src) - }) - return - } - r := NewWasmGasRegister(spec.srcConfig) - got := r.ToWasmVMGas(spec.src) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestFromWasmVMGasConversion(t *testing.T) { - specs := map[string]struct { - src uint64 - exp storetypes.Gas - srcConfig WasmGasRegisterConfig - expPanic bool - }{ - "0": { - src: 0, - exp: 0, - srcConfig: DefaultGasRegisterConfig(), - }, - "max": { - srcConfig: WasmGasRegisterConfig{ - GasMultiplier: 1, - }, - src: math.MaxUint64, - exp: math.MaxUint64, - }, - "missconfigured": { - srcConfig: WasmGasRegisterConfig{ - GasMultiplier: 0, - }, - src: 1, - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { - r := NewWasmGasRegister(spec.srcConfig) - _ = r.FromWasmVMGas(spec.src) - }) - return - } - r := NewWasmGasRegister(spec.srcConfig) - got := r.FromWasmVMGas(spec.src) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestUncompressCosts(t *testing.T) { - specs := map[string]struct { - lenIn int - exp sdk.Gas - expPanic bool - }{ - "0": { - exp: 0, - }, - "even": { - lenIn: 100, - exp: 15, - }, - "round down when uneven": { - lenIn: 19, - exp: 2, - }, - "max len": { - lenIn: types.MaxWasmSize, - exp: 122880, - }, - "invalid len": { - lenIn: -1, - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if spec.expPanic { - assert.Panics(t, func() { NewDefaultWasmGasRegister().UncompressCosts(spec.lenIn) }) - return - } - got := NewDefaultWasmGasRegister().UncompressCosts(spec.lenIn) - assert.Equal(t, spec.exp, got) - }) - } -} diff --git a/x/wasm/keeper/genesis.go b/x/wasm/keeper/genesis.go deleted file mode 100644 index 0e467ea..0000000 --- a/x/wasm/keeper/genesis.go +++ /dev/null @@ -1,120 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// ValidatorSetSource is a subset of the staking keeper -type ValidatorSetSource interface { - ApplyAndReturnValidatorSetUpdates(sdk.Context) (updates []abci.ValidatorUpdate, err error) -} - -// InitGenesis sets supply information for genesis. -// -// CONTRACT: all types of accounts must have been already initialized/created -func InitGenesis(ctx sdk.Context, keeper *Keeper, data types.GenesisState) ([]abci.ValidatorUpdate, error) { - contractKeeper := NewGovPermissionKeeper(keeper) - err := keeper.SetParams(ctx, data.Params) - if err != nil { - return nil, errorsmod.Wrapf(err, "set params") - } - - var maxCodeID uint64 - for i, code := range data.Codes { - err := keeper.importCode(ctx, code.CodeID, code.CodeInfo, code.CodeBytes) - if err != nil { - return nil, errorsmod.Wrapf(err, "code %d with id: %d", i, code.CodeID) - } - if code.CodeID > maxCodeID { - maxCodeID = code.CodeID - } - if code.Pinned { - if err := contractKeeper.PinCode(ctx, code.CodeID); err != nil { - return nil, errorsmod.Wrapf(err, "contract number %d", i) - } - } - } - - var maxContractID int - for i, contract := range data.Contracts { - contractAddr, err := sdk.AccAddressFromBech32(contract.ContractAddress) - if err != nil { - return nil, errorsmod.Wrapf(err, "address in contract number %d", i) - } - err = keeper.importContract(ctx, contractAddr, &contract.ContractInfo, contract.ContractState, contract.ContractCodeHistory) - if err != nil { - return nil, errorsmod.Wrapf(err, "contract number %d", i) - } - maxContractID = i + 1 // not ideal but max(contractID) is not persisted otherwise - } - - for i, seq := range data.Sequences { - err := keeper.importAutoIncrementID(ctx, seq.IDKey, seq.Value) - if err != nil { - return nil, errorsmod.Wrapf(err, "sequence number %d", i) - } - } - - // sanity check seq values - seqVal := keeper.PeekAutoIncrementID(ctx, types.KeyLastCodeID) - if seqVal <= maxCodeID { - return nil, errorsmod.Wrapf(types.ErrInvalid, "seq %s with value: %d must be greater than: %d ", string(types.KeyLastCodeID), seqVal, maxCodeID) - } - seqVal = keeper.PeekAutoIncrementID(ctx, types.KeyLastInstanceID) - if seqVal <= uint64(maxContractID) { - return nil, errorsmod.Wrapf(types.ErrInvalid, "seq %s with value: %d must be greater than: %d ", string(types.KeyLastInstanceID), seqVal, maxContractID) - } - return nil, nil -} - -// ExportGenesis returns a GenesisState for a given context and keeper. -func ExportGenesis(ctx sdk.Context, keeper *Keeper) *types.GenesisState { - var genState types.GenesisState - - genState.Params = keeper.GetParams(ctx) - - keeper.IterateCodeInfos(ctx, func(codeID uint64, info types.CodeInfo) bool { - bytecode, err := keeper.GetByteCode(ctx, codeID) - if err != nil { - panic(err) - } - genState.Codes = append(genState.Codes, types.Code{ - CodeID: codeID, - CodeInfo: info, - CodeBytes: bytecode, - Pinned: keeper.IsPinnedCode(ctx, codeID), - }) - return false - }) - - keeper.IterateContractInfo(ctx, func(addr sdk.AccAddress, contract types.ContractInfo) bool { - var state []types.Model - keeper.IterateContractState(ctx, addr, func(key, value []byte) bool { - state = append(state, types.Model{Key: key, Value: value}) - return false - }) - - contractCodeHistory := keeper.GetContractHistory(ctx, addr) - - genState.Contracts = append(genState.Contracts, types.Contract{ - ContractAddress: addr.String(), - ContractInfo: contract, - ContractState: state, - ContractCodeHistory: contractCodeHistory, - }) - return false - }) - - for _, k := range [][]byte{types.KeyLastCodeID, types.KeyLastInstanceID} { - genState.Sequences = append(genState.Sequences, types.Sequence{ - IDKey: k, - Value: keeper.PeekAutoIncrementID(ctx, k), - }) - } - - return &genState -} diff --git a/x/wasm/keeper/genesis_test.go b/x/wasm/keeper/genesis_test.go deleted file mode 100644 index 6be1689..0000000 --- a/x/wasm/keeper/genesis_test.go +++ /dev/null @@ -1,705 +0,0 @@ -package keeper - -import ( - "crypto/sha256" - "encoding/base64" - "fmt" - "math/rand" - "os" - "testing" - "time" - - abci "github.com/cometbft/cometbft/abci/types" - - "github.com/cosmos/cosmos-sdk/baseapp" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - fuzz "github.com/google/gofuzz" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const firstCodeID = 1 - -func TestGenesisExportImport(t *testing.T) { - wasmKeeper, srcCtx := setupKeeper(t) - contractKeeper := NewGovPermissionKeeper(wasmKeeper) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - // store some test data - f := fuzz.New().Funcs(ModelFuzzers...) - - err = wasmKeeper.SetParams(srcCtx, types.DefaultParams()) - require.NoError(t, err) - - for i := 0; i < 25; i++ { - var ( - codeInfo types.CodeInfo - contract types.ContractInfo - stateModels []types.Model - history []types.ContractCodeHistoryEntry - pinned bool - contractExtension bool - ) - f.Fuzz(&codeInfo) - f.Fuzz(&contract) - f.Fuzz(&stateModels) - f.NilChance(0).Fuzz(&history) - f.Fuzz(&pinned) - f.Fuzz(&contractExtension) - - creatorAddr, err := sdk.AccAddressFromBech32(codeInfo.Creator) - require.NoError(t, err) - codeID, _, err := contractKeeper.Create(srcCtx, creatorAddr, wasmCode, &codeInfo.InstantiateConfig) - require.NoError(t, err) - if pinned { - err = contractKeeper.PinCode(srcCtx, codeID) - require.NoError(t, err) - } - if contractExtension { - anyTime := time.Now().UTC() - var nestedType v1beta1.TextProposal - f.NilChance(0).Fuzz(&nestedType) - myExtension, err := v1beta1.NewProposal(&nestedType, 1, anyTime, anyTime) - require.NoError(t, err) - err = contract.SetExtension(&myExtension) - require.NoError(t, err) - } - - contract.CodeID = codeID - contractAddr := wasmKeeper.ClassicAddressGenerator()(srcCtx, codeID, nil) - wasmKeeper.storeContractInfo(srcCtx, contractAddr, &contract) - wasmKeeper.appendToContractHistory(srcCtx, contractAddr, history...) - err = wasmKeeper.importContractState(srcCtx, contractAddr, stateModels) - require.NoError(t, err) - } - var wasmParams types.Params - f.NilChance(0).Fuzz(&wasmParams) - err = wasmKeeper.SetParams(srcCtx, wasmParams) - require.NoError(t, err) - - // export - exportedState := ExportGenesis(srcCtx, wasmKeeper) - // order should not matter - rand.Shuffle(len(exportedState.Codes), func(i, j int) { - exportedState.Codes[i], exportedState.Codes[j] = exportedState.Codes[j], exportedState.Codes[i] - }) - rand.Shuffle(len(exportedState.Contracts), func(i, j int) { - exportedState.Contracts[i], exportedState.Contracts[j] = exportedState.Contracts[j], exportedState.Contracts[i] - }) - rand.Shuffle(len(exportedState.Sequences), func(i, j int) { - exportedState.Sequences[i], exportedState.Sequences[j] = exportedState.Sequences[j], exportedState.Sequences[i] - }) - exportedGenesis, err := wasmKeeper.cdc.MarshalJSON(exportedState) - require.NoError(t, err) - - // setup new instances - dstKeeper, dstCtx := setupKeeper(t) - - // reset contract code index in source DB for comparison with dest DB - wasmKeeper.IterateContractInfo(srcCtx, func(address sdk.AccAddress, info types.ContractInfo) bool { - creatorAddress := sdk.MustAccAddressFromBech32(info.Creator) - history := wasmKeeper.GetContractHistory(srcCtx, address) - - wasmKeeper.addToContractCodeSecondaryIndex(srcCtx, address, history[len(history)-1]) - wasmKeeper.addToContractCreatorSecondaryIndex(srcCtx, creatorAddress, history[0].Updated, address) - return false - }) - - // re-import - var importState types.GenesisState - err = dstKeeper.cdc.UnmarshalJSON(exportedGenesis, &importState) - require.NoError(t, err) - _, err = InitGenesis(dstCtx, dstKeeper, importState) - require.NoError(t, err) - - // compare whole DB - - srcIT := srcCtx.KVStore(wasmKeeper.storeKey).Iterator(nil, nil) - dstIT := dstCtx.KVStore(dstKeeper.storeKey).Iterator(nil, nil) - - for i := 0; srcIT.Valid(); i++ { - require.True(t, dstIT.Valid(), "[%s] destination DB has less elements than source. Missing: %x", wasmKeeper.storeKey.Name(), srcIT.Key()) - require.Equal(t, srcIT.Key(), dstIT.Key(), i) - require.Equal(t, srcIT.Value(), dstIT.Value(), "[%s] element (%d): %X", wasmKeeper.storeKey.Name(), i, srcIT.Key()) - dstIT.Next() - srcIT.Next() - } - if !assert.False(t, dstIT.Valid()) { - t.Fatalf("dest Iterator still has key :%X", dstIT.Key()) - } - srcIT.Close() - dstIT.Close() -} - -func TestGenesisInit(t *testing.T) { - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - myCodeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - specs := map[string]struct { - src types.GenesisState - expSuccess bool - }{ - "happy path: code info correct": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 2}, - {IDKey: types.KeyLastInstanceID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "happy path: code ids can contain gaps": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }, { - CodeID: 3, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 10}, - {IDKey: types.KeyLastInstanceID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "happy path: code order does not matter": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: 2, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }, { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: nil, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 3}, - {IDKey: types.KeyLastInstanceID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "prevent code hash mismatch": {src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: types.CodeInfoFixture(func(i *types.CodeInfo) { i.CodeHash = make([]byte, sha256.Size) }), - CodeBytes: wasmCode, - }}, - Params: types.DefaultParams(), - }}, - "prevent duplicate codeIDs": {src: types.GenesisState{ - Codes: []types.Code{ - { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }, - { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }, - }, - Params: types.DefaultParams(), - }}, - "codes with same checksum can be pinned": { - src: types.GenesisState{ - Codes: []types.Code{ - { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - Pinned: true, - }, - { - CodeID: 2, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - Pinned: true, - }, - }, - Params: types.DefaultParams(), - }, - }, - "happy path: code id in info and contract do match": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{}`), - }, - }, - }, - }, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 2}, - {IDKey: types.KeyLastInstanceID, Value: 2}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "happy path: code info with two contracts": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{}`), - }, - }, - }, { - ContractAddress: BuildContractAddressClassic(1, 2).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"foo":"bar"}`), - }, - }, - }, - }, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 2}, - {IDKey: types.KeyLastInstanceID, Value: 3}, - }, - Params: types.DefaultParams(), - }, - expSuccess: true, - }, - "prevent contracts that points to non existing codeID": { - src: types.GenesisState{ - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"foo":"bar"}`), - }, - }, - }, - }, - Params: types.DefaultParams(), - }, - }, - "prevent duplicate contract address": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"foo":"bar"}`), - }, - }, - }, { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"other":"value"}`), - }, - }, - }, - }, - Params: types.DefaultParams(), - }, - }, - "prevent duplicate contract model keys": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractState: []types.Model{ - { - Key: []byte{0x1}, - Value: []byte("foo"), - }, - { - Key: []byte{0x1}, - Value: []byte("bar"), - }, - }, - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{"foo":"bar"}`), - }, - }, - }, - }, - Params: types.DefaultParams(), - }, - }, - "prevent duplicate sequences": { - src: types.GenesisState{ - Sequences: []types.Sequence{ - {IDKey: []byte("foo"), Value: 1}, - {IDKey: []byte("foo"), Value: 9999}, - }, - Params: types.DefaultParams(), - }, - }, - "prevent code id seq init value == max codeID used": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: 2, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - }, - "prevent contract id seq init value == count contracts": { - src: types.GenesisState{ - Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodeBytes: wasmCode, - }}, - Contracts: []types.Contract{ - { - ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), - ContractCodeHistory: []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 1, - Updated: &types.AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()}, - Msg: []byte(`{}`), - }, - }, - }, - }, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: 2}, - {IDKey: types.KeyLastInstanceID, Value: 1}, - }, - Params: types.DefaultParams(), - }, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - keeper, ctx := setupKeeper(t) - - require.NoError(t, types.ValidateGenesis(spec.src)) - _, gotErr := InitGenesis(ctx, keeper, spec.src) - if !spec.expSuccess { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - - for _, c := range spec.src.Codes { - assert.Equal(t, c.Pinned, keeper.IsPinnedCode(ctx, c.CodeID)) - } - }) - } -} - -func TestImportContractWithCodeHistoryPreserved(t *testing.T) { - genesisTemplate := ` -{ - "params":{ - "code_upload_access": { - "permission": "Everybody" - }, - "instantiate_default_permission": "Everybody" - }, - "codes": [ - { - "code_id": "1", - "code_info": { - "code_hash": %q, - "creator": "cosmos1qtu5n0cnhfkjj6l2rq97hmky9fd89gwca9yarx", - "instantiate_config": { - "permission": "OnlyAddress", - "address": "cosmos1qtu5n0cnhfkjj6l2rq97hmky9fd89gwca9yarx" - } - }, - "code_bytes": %q - } - ], - "contracts": [ - { - "contract_address": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "contract_info": { - "code_id": "1", - "creator": "cosmos13x849jzd03vne42ynpj25hn8npjecxqrjghd8x", - "admin": "cosmos1h5t8zxmjr30e9dqghtlpl40f2zz5cgey6esxtn", - "label": "ȀĴnZV芢毤", - "created": { - "block_height" : "100", - "tx_index" : "10" - } - }, - "contract_code_history": [ - { - "operation": "CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT", - "code_id": "1", - "updated": { - "block_height" : "100", - "tx_index" : "10" - }, - "msg": {"foo": "bar"} - }, - { - "operation": "CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE", - "code_id": "1", - "updated": { - "block_height" : "200", - "tx_index" : "10" - }, - "msg": {"other": "msg"} - } - ] - } - ], - "sequences": [ - {"id_key": "BGxhc3RDb2RlSWQ=", "value": "2"}, - {"id_key": "BGxhc3RDb250cmFjdElk", "value": "3"} - ] -}` - keeper, ctx := setupKeeper(t) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - wasmCodeHash := sha256.Sum256(wasmCode) - enc64 := base64.StdEncoding.EncodeToString - genesisStr := fmt.Sprintf(genesisTemplate, enc64(wasmCodeHash[:]), enc64(wasmCode)) - - var importState types.GenesisState - err = keeper.cdc.UnmarshalJSON([]byte(genesisStr), &importState) - require.NoError(t, err) - require.NoError(t, importState.ValidateBasic(), genesisStr) - - ctx = ctx.WithBlockHeight(0).WithGasMeter(sdk.NewInfiniteGasMeter()) - - // when - _, err = InitGenesis(ctx, keeper, importState) - require.NoError(t, err) - - // verify wasm code - gotWasmCode, err := keeper.GetByteCode(ctx, 1) - require.NoError(t, err) - assert.Equal(t, wasmCode, gotWasmCode, "byte code does not match") - - // verify code info - gotCodeInfo := keeper.GetCodeInfo(ctx, 1) - require.NotNil(t, gotCodeInfo) - codeCreatorAddr := "cosmos1qtu5n0cnhfkjj6l2rq97hmky9fd89gwca9yarx" - expCodeInfo := types.CodeInfo{ - CodeHash: wasmCodeHash[:], - Creator: codeCreatorAddr, - InstantiateConfig: types.AccessConfig{ - Permission: types.AccessTypeOnlyAddress, - Address: codeCreatorAddr, - }, - } - assert.Equal(t, expCodeInfo, *gotCodeInfo) - - // verify contract - contractAddr, _ := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") - gotContractInfo := keeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, gotContractInfo) - contractCreatorAddr := "cosmos13x849jzd03vne42ynpj25hn8npjecxqrjghd8x" - adminAddr := "cosmos1h5t8zxmjr30e9dqghtlpl40f2zz5cgey6esxtn" - - expContractInfo := types.ContractInfo{ - CodeID: firstCodeID, - Creator: contractCreatorAddr, - Admin: adminAddr, - Label: "ȀĴnZV芢毤", - Created: &types.AbsoluteTxPosition{BlockHeight: 100, TxIndex: 10}, - } - assert.Equal(t, expContractInfo, *gotContractInfo) - - expHistory := []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{ - BlockHeight: 100, - TxIndex: 10, - }, - Msg: []byte(`{"foo": "bar"}`), - }, - { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{ - BlockHeight: 200, - TxIndex: 10, - }, - Msg: []byte(`{"other": "msg"}`), - }, - } - assert.Equal(t, expHistory, keeper.GetContractHistory(ctx, contractAddr)) - assert.Equal(t, uint64(2), keeper.PeekAutoIncrementID(ctx, types.KeyLastCodeID)) - assert.Equal(t, uint64(3), keeper.PeekAutoIncrementID(ctx, types.KeyLastInstanceID)) -} - -func setupKeeper(t *testing.T) (*Keeper, sdk.Context) { - t.Helper() - tempDir, err := os.MkdirTemp("", "wasm") - require.NoError(t, err) - t.Cleanup(func() { os.RemoveAll(tempDir) }) - - keyWasm := sdk.NewKVStoreKey(types.StoreKey) - - db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyWasm, storetypes.StoreTypeIAVL, db) - require.NoError(t, ms.LoadLatestVersion()) - - ctx := sdk.NewContext(ms, tmproto.Header{ - Height: 1234567, - Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC), - }, false, log.NewNopLogger()) - - encodingConfig := MakeEncodingConfig(t) - // register an example extension. must be protobuf - encodingConfig.InterfaceRegistry.RegisterImplementations( - (*types.ContractInfoExtension)(nil), - &v1beta1.Proposal{}, - ) - // also registering gov interfaces for nested Any type - v1beta1.RegisterInterfaces(encodingConfig.InterfaceRegistry) - - wasmConfig := types.DefaultWasmConfig() - - srcKeeper := NewKeeper( - encodingConfig.Marshaler, - keyWasm, - authkeeper.AccountKeeper{}, - &bankkeeper.BaseKeeper{}, - stakingkeeper.Keeper{}, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - tempDir, - wasmConfig, - AvailableCapabilities, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - return &srcKeeper, ctx -} - -type StakingKeeperMock struct { - err error - validatorUpdate []abci.ValidatorUpdate - gotCalls int -} - -func (s *StakingKeeperMock) ApplyAndReturnValidatorSetUpdates(_ sdk.Context) ([]abci.ValidatorUpdate, error) { - s.gotCalls++ - return s.validatorUpdate, s.err -} - -var _ MessageRouter = &MockMsgHandler{} - -type MockMsgHandler struct { - result *sdk.Result - err error - expCalls int //nolint:unused - gotCalls int - expMsg sdk.Msg //nolint:unused - gotMsg sdk.Msg -} - -func (m *MockMsgHandler) Handler(msg sdk.Msg) baseapp.MsgServiceHandler { - return m.Handle -} - -func (m *MockMsgHandler) Handle(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - m.gotCalls++ - m.gotMsg = msg - return m.result, m.err -} diff --git a/x/wasm/keeper/handler_plugin.go b/x/wasm/keeper/handler_plugin.go deleted file mode 100644 index beba71a..0000000 --- a/x/wasm/keeper/handler_plugin.go +++ /dev/null @@ -1,219 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - - errorsmod "cosmossdk.io/errors" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/baseapp" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// msgEncoder is an extension point to customize encodings -type msgEncoder interface { - // Encode converts wasmvm message to n cosmos message types - Encode(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Msg, error) -} - -// MessageRouter ADR 031 request type routing -type MessageRouter interface { - Handler(msg sdk.Msg) baseapp.MsgServiceHandler -} - -// SDKMessageHandler can handles messages that can be encoded into sdk.Message types and routed. -type SDKMessageHandler struct { - router MessageRouter - encoders msgEncoder -} - -func NewDefaultMessageHandler( - router MessageRouter, - channelKeeper types.ChannelKeeper, - capabilityKeeper types.CapabilityKeeper, - bankKeeper types.Burner, - unpacker codectypes.AnyUnpacker, - portSource types.ICS20TransferPortSource, - customEncoders ...*MessageEncoders, -) Messenger { - encoders := DefaultEncoders(unpacker, portSource) - for _, e := range customEncoders { - encoders = encoders.Merge(e) - } - return NewMessageHandlerChain( - NewSDKMessageHandler(router, encoders), - NewIBCRawPacketHandler(channelKeeper, capabilityKeeper), - NewBurnCoinMessageHandler(bankKeeper), - ) -} - -func NewSDKMessageHandler(router MessageRouter, encoders msgEncoder) SDKMessageHandler { - return SDKMessageHandler{ - router: router, - encoders: encoders, - } -} - -func (h SDKMessageHandler) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - sdkMsgs, err := h.encoders.Encode(ctx, contractAddr, contractIBCPortID, msg) - if err != nil { - return nil, nil, err - } - for _, sdkMsg := range sdkMsgs { - res, err := h.handleSdkMessage(ctx, contractAddr, sdkMsg) - if err != nil { - return nil, nil, err - } - // append data - data = append(data, res.Data) - // append events - sdkEvents := make([]sdk.Event, len(res.Events)) - for i := range res.Events { - sdkEvents[i] = sdk.Event(res.Events[i]) - } - events = append(events, sdkEvents...) - } - return -} - -func (h SDKMessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Address, msg sdk.Msg) (*sdk.Result, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - // make sure this account can send it - for _, acct := range msg.GetSigners() { - if !acct.Equals(contractAddr) { - return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "contract doesn't have permission") - } - } - - // find the handler and execute it - if handler := h.router.Handler(msg); handler != nil { - // ADR 031 request type routing - msgResult, err := handler(ctx, msg) - return msgResult, err - } - // legacy sdk.Msg routing - // Assuming that the app developer has migrated all their Msgs to - // proto messages and has registered all `Msg services`, then this - // path should never be called, because all those Msgs should be - // registered within the `msgServiceRouter` already. - return nil, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "can't route message %+v", msg) -} - -// MessageHandlerChain defines a chain of handlers that are called one by one until it can be handled. -type MessageHandlerChain struct { - handlers []Messenger -} - -func NewMessageHandlerChain(first Messenger, others ...Messenger) *MessageHandlerChain { - r := &MessageHandlerChain{handlers: append([]Messenger{first}, others...)} - for i := range r.handlers { - if r.handlers[i] == nil { - panic(fmt.Sprintf("handler must not be nil at position : %d", i)) - } - } - return r -} - -// DispatchMsg dispatch message and calls chained handlers one after another in -// order to find the right one to process given message. If a handler cannot -// process given message (returns ErrUnknownMsg), its result is ignored and the -// next handler is executed. -func (m MessageHandlerChain) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Event, [][]byte, error) { - for _, h := range m.handlers { - events, data, err := h.DispatchMsg(ctx, contractAddr, contractIBCPortID, msg) - switch { - case err == nil: - return events, data, nil - case errors.Is(err, types.ErrUnknownMsg): - continue - default: - return events, data, err - } - } - return nil, nil, errorsmod.Wrap(types.ErrUnknownMsg, "no handler found") -} - -// IBCRawPacketHandler handels IBC.SendPacket messages which are published to an IBC channel. -type IBCRawPacketHandler struct { - channelKeeper types.ChannelKeeper - capabilityKeeper types.CapabilityKeeper -} - -func NewIBCRawPacketHandler(chk types.ChannelKeeper, cak types.CapabilityKeeper) IBCRawPacketHandler { - return IBCRawPacketHandler{channelKeeper: chk, capabilityKeeper: cak} -} - -// DispatchMsg publishes a raw IBC packet onto the channel. -func (h IBCRawPacketHandler) DispatchMsg(ctx sdk.Context, _ sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Event, [][]byte, error) { - if msg.IBC == nil || msg.IBC.SendPacket == nil { - return nil, nil, types.ErrUnknownMsg - } - if contractIBCPortID == "" { - return nil, nil, errorsmod.Wrapf(types.ErrUnsupportedForContract, "ibc not supported") - } - contractIBCChannelID := msg.IBC.SendPacket.ChannelID - if contractIBCChannelID == "" { - return nil, nil, errorsmod.Wrapf(types.ErrEmpty, "ibc channel") - } - - channelCap, ok := h.capabilityKeeper.GetCapability(ctx, host.ChannelCapabilityPath(contractIBCPortID, contractIBCChannelID)) - if !ok { - return nil, nil, errorsmod.Wrap(channeltypes.ErrChannelCapabilityNotFound, "module does not own channel capability") - } - seq, err := h.channelKeeper.SendPacket(ctx, channelCap, contractIBCPortID, contractIBCChannelID, ConvertWasmIBCTimeoutHeightToCosmosHeight(msg.IBC.SendPacket.Timeout.Block), msg.IBC.SendPacket.Timeout.Timestamp, msg.IBC.SendPacket.Data) - if err != nil { - return nil, nil, errorsmod.Wrap(err, "channel") - } - moduleLogger(ctx).Debug("ibc packet set", "seq", seq) - - resp := &types.MsgIBCSendResponse{Sequence: seq} - val, err := resp.Marshal() - if err != nil { - return nil, nil, errorsmod.Wrap(err, "failed to marshal IBC send response") - } - - return nil, [][]byte{val}, nil -} - -var _ Messenger = MessageHandlerFunc(nil) - -// MessageHandlerFunc is a helper to construct a function based message handler. -type MessageHandlerFunc func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) - -// DispatchMsg delegates dispatching of provided message into the MessageHandlerFunc. -func (m MessageHandlerFunc) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return m(ctx, contractAddr, contractIBCPortID, msg) -} - -// NewBurnCoinMessageHandler handles wasmvm.BurnMsg messages -func NewBurnCoinMessageHandler(burner types.Burner) MessageHandlerFunc { - return func(ctx sdk.Context, contractAddr sdk.AccAddress, _ string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - if msg.Bank != nil && msg.Bank.Burn != nil { - coins, err := ConvertWasmCoinsToSdkCoins(msg.Bank.Burn.Amount) - if err != nil { - return nil, nil, err - } - if coins.IsZero() { - return nil, nil, types.ErrEmpty.Wrap("amount") - } - if err := burner.SendCoinsFromAccountToModule(ctx, contractAddr, types.ModuleName, coins); err != nil { - return nil, nil, errorsmod.Wrap(err, "transfer to module") - } - if err := burner.BurnCoins(ctx, types.ModuleName, coins); err != nil { - return nil, nil, errorsmod.Wrap(err, "burn coins") - } - moduleLogger(ctx).Info("Burned", "amount", coins) - return nil, nil, nil - } - return nil, nil, types.ErrUnknownMsg - } -} diff --git a/x/wasm/keeper/handler_plugin_encoders.go b/x/wasm/keeper/handler_plugin_encoders.go deleted file mode 100644 index e6883e1..0000000 --- a/x/wasm/keeper/handler_plugin_encoders.go +++ /dev/null @@ -1,395 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - - errorsmod "cosmossdk.io/errors" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - ibcclienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type ( - BankEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) - CustomEncoder func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) - DistributionEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.DistributionMsg) ([]sdk.Msg, error) - StakingEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.StakingMsg) ([]sdk.Msg, error) - StargateEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.StargateMsg) ([]sdk.Msg, error) - WasmEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, error) - IBCEncoder func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *wasmvmtypes.IBCMsg) ([]sdk.Msg, error) -) - -type MessageEncoders struct { - Bank func(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) - Custom func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) - Distribution func(sender sdk.AccAddress, msg *wasmvmtypes.DistributionMsg) ([]sdk.Msg, error) - IBC func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *wasmvmtypes.IBCMsg) ([]sdk.Msg, error) - Staking func(sender sdk.AccAddress, msg *wasmvmtypes.StakingMsg) ([]sdk.Msg, error) - Stargate func(sender sdk.AccAddress, msg *wasmvmtypes.StargateMsg) ([]sdk.Msg, error) - Wasm func(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, error) - Gov func(sender sdk.AccAddress, msg *wasmvmtypes.GovMsg) ([]sdk.Msg, error) -} - -func DefaultEncoders(unpacker codectypes.AnyUnpacker, portSource types.ICS20TransferPortSource) MessageEncoders { - return MessageEncoders{ - Bank: EncodeBankMsg, - Custom: NoCustomMsg, - Distribution: EncodeDistributionMsg, - IBC: EncodeIBCMsg(portSource), - Staking: EncodeStakingMsg, - Stargate: EncodeStargateMsg(unpacker), - Wasm: EncodeWasmMsg, - Gov: EncodeGovMsg, - } -} - -func (e MessageEncoders) Merge(o *MessageEncoders) MessageEncoders { - if o == nil { - return e - } - if o.Bank != nil { - e.Bank = o.Bank - } - if o.Custom != nil { - e.Custom = o.Custom - } - if o.Distribution != nil { - e.Distribution = o.Distribution - } - if o.IBC != nil { - e.IBC = o.IBC - } - if o.Staking != nil { - e.Staking = o.Staking - } - if o.Stargate != nil { - e.Stargate = o.Stargate - } - if o.Wasm != nil { - e.Wasm = o.Wasm - } - if o.Gov != nil { - e.Gov = o.Gov - } - return e -} - -func (e MessageEncoders) Encode(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Msg, error) { - switch { - case msg.Bank != nil: - return e.Bank(contractAddr, msg.Bank) - case msg.Custom != nil: - return e.Custom(contractAddr, msg.Custom) - case msg.Distribution != nil: - return e.Distribution(contractAddr, msg.Distribution) - case msg.IBC != nil: - return e.IBC(ctx, contractAddr, contractIBCPortID, msg.IBC) - case msg.Staking != nil: - return e.Staking(contractAddr, msg.Staking) - case msg.Stargate != nil: - return e.Stargate(contractAddr, msg.Stargate) - case msg.Wasm != nil: - return e.Wasm(contractAddr, msg.Wasm) - case msg.Gov != nil: - return EncodeGovMsg(contractAddr, msg.Gov) - } - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Wasm") -} - -func EncodeBankMsg(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) { - if msg.Send == nil { - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Bank") - } - if len(msg.Send.Amount) == 0 { - return nil, nil - } - toSend, err := ConvertWasmCoinsToSdkCoins(msg.Send.Amount) - if err != nil { - return nil, err - } - sdkMsg := banktypes.MsgSend{ - FromAddress: sender.String(), - ToAddress: msg.Send.ToAddress, - Amount: toSend, - } - return []sdk.Msg{&sdkMsg}, nil -} - -func NoCustomMsg(_ sdk.AccAddress, _ json.RawMessage) ([]sdk.Msg, error) { - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "custom variant not supported") -} - -func EncodeDistributionMsg(sender sdk.AccAddress, msg *wasmvmtypes.DistributionMsg) ([]sdk.Msg, error) { - switch { - case msg.SetWithdrawAddress != nil: - setMsg := distributiontypes.MsgSetWithdrawAddress{ - DelegatorAddress: sender.String(), - WithdrawAddress: msg.SetWithdrawAddress.Address, - } - return []sdk.Msg{&setMsg}, nil - case msg.WithdrawDelegatorReward != nil: - withdrawMsg := distributiontypes.MsgWithdrawDelegatorReward{ - DelegatorAddress: sender.String(), - ValidatorAddress: msg.WithdrawDelegatorReward.Validator, - } - return []sdk.Msg{&withdrawMsg}, nil - default: - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Distribution") - } -} - -func EncodeStakingMsg(sender sdk.AccAddress, msg *wasmvmtypes.StakingMsg) ([]sdk.Msg, error) { - switch { - case msg.Delegate != nil: - coin, err := ConvertWasmCoinToSdkCoin(msg.Delegate.Amount) - if err != nil { - return nil, err - } - sdkMsg := stakingtypes.MsgDelegate{ - DelegatorAddress: sender.String(), - ValidatorAddress: msg.Delegate.Validator, - Amount: coin, - } - return []sdk.Msg{&sdkMsg}, nil - - case msg.Redelegate != nil: - coin, err := ConvertWasmCoinToSdkCoin(msg.Redelegate.Amount) - if err != nil { - return nil, err - } - sdkMsg := stakingtypes.MsgBeginRedelegate{ - DelegatorAddress: sender.String(), - ValidatorSrcAddress: msg.Redelegate.SrcValidator, - ValidatorDstAddress: msg.Redelegate.DstValidator, - Amount: coin, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.Undelegate != nil: - coin, err := ConvertWasmCoinToSdkCoin(msg.Undelegate.Amount) - if err != nil { - return nil, err - } - sdkMsg := stakingtypes.MsgUndelegate{ - DelegatorAddress: sender.String(), - ValidatorAddress: msg.Undelegate.Validator, - Amount: coin, - } - return []sdk.Msg{&sdkMsg}, nil - default: - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Staking") - } -} - -func EncodeStargateMsg(unpacker codectypes.AnyUnpacker) StargateEncoder { - return func(sender sdk.AccAddress, msg *wasmvmtypes.StargateMsg) ([]sdk.Msg, error) { - codecAny := codectypes.Any{ - TypeUrl: msg.TypeURL, - Value: msg.Value, - } - var sdkMsg sdk.Msg - if err := unpacker.UnpackAny(&codecAny, &sdkMsg); err != nil { - return nil, errorsmod.Wrap(types.ErrInvalidMsg, fmt.Sprintf("Cannot unpack proto message with type URL: %s", msg.TypeURL)) - } - if err := codectypes.UnpackInterfaces(sdkMsg, unpacker); err != nil { - return nil, errorsmod.Wrap(types.ErrInvalidMsg, fmt.Sprintf("UnpackInterfaces inside msg: %s", err)) - } - return []sdk.Msg{sdkMsg}, nil - } -} - -func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, error) { - switch { - case msg.Execute != nil: - coins, err := ConvertWasmCoinsToSdkCoins(msg.Execute.Funds) - if err != nil { - return nil, err - } - - sdkMsg := types.MsgExecuteContract{ - Sender: sender.String(), - Contract: msg.Execute.ContractAddr, - Msg: msg.Execute.Msg, - Funds: coins, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.Instantiate != nil: - coins, err := ConvertWasmCoinsToSdkCoins(msg.Instantiate.Funds) - if err != nil { - return nil, err - } - - sdkMsg := types.MsgInstantiateContract{ - Sender: sender.String(), - CodeID: msg.Instantiate.CodeID, - Label: msg.Instantiate.Label, - Msg: msg.Instantiate.Msg, - Admin: msg.Instantiate.Admin, - Funds: coins, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.Instantiate2 != nil: - coins, err := ConvertWasmCoinsToSdkCoins(msg.Instantiate2.Funds) - if err != nil { - return nil, err - } - - sdkMsg := types.MsgInstantiateContract2{ - Sender: sender.String(), - Admin: msg.Instantiate2.Admin, - CodeID: msg.Instantiate2.CodeID, - Label: msg.Instantiate2.Label, - Msg: msg.Instantiate2.Msg, - Funds: coins, - Salt: msg.Instantiate2.Salt, - // FixMsg is discouraged, see: https://medium.com/cosmwasm/dev-note-3-limitations-of-instantiate2-and-how-to-deal-with-them-a3f946874230 - FixMsg: false, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.Migrate != nil: - sdkMsg := types.MsgMigrateContract{ - Sender: sender.String(), - Contract: msg.Migrate.ContractAddr, - CodeID: msg.Migrate.NewCodeID, - Msg: msg.Migrate.Msg, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.ClearAdmin != nil: - sdkMsg := types.MsgClearAdmin{ - Sender: sender.String(), - Contract: msg.ClearAdmin.ContractAddr, - } - return []sdk.Msg{&sdkMsg}, nil - case msg.UpdateAdmin != nil: - sdkMsg := types.MsgUpdateAdmin{ - Sender: sender.String(), - Contract: msg.UpdateAdmin.ContractAddr, - NewAdmin: msg.UpdateAdmin.Admin, - } - return []sdk.Msg{&sdkMsg}, nil - default: - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Wasm") - } -} - -func EncodeIBCMsg(portSource types.ICS20TransferPortSource) func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *wasmvmtypes.IBCMsg) ([]sdk.Msg, error) { - return func(ctx sdk.Context, sender sdk.AccAddress, contractIBCPortID string, msg *wasmvmtypes.IBCMsg) ([]sdk.Msg, error) { - switch { - case msg.CloseChannel != nil: - return []sdk.Msg{&channeltypes.MsgChannelCloseInit{ - PortId: PortIDForContract(sender), - ChannelId: msg.CloseChannel.ChannelID, - Signer: sender.String(), - }}, nil - case msg.Transfer != nil: - amount, err := ConvertWasmCoinToSdkCoin(msg.Transfer.Amount) - if err != nil { - return nil, errorsmod.Wrap(err, "amount") - } - msg := &ibctransfertypes.MsgTransfer{ - SourcePort: portSource.GetPort(ctx), - SourceChannel: msg.Transfer.ChannelID, - Token: amount, - Sender: sender.String(), - Receiver: msg.Transfer.ToAddress, - TimeoutHeight: ConvertWasmIBCTimeoutHeightToCosmosHeight(msg.Transfer.Timeout.Block), - TimeoutTimestamp: msg.Transfer.Timeout.Timestamp, - } - return []sdk.Msg{msg}, nil - default: - return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of IBC") - } - } -} - -func EncodeGovMsg(sender sdk.AccAddress, msg *wasmvmtypes.GovMsg) ([]sdk.Msg, error) { - switch { - case msg.Vote != nil: - voteOption, err := convertVoteOption(msg.Vote.Vote) - if err != nil { - return nil, errorsmod.Wrap(err, "vote option") - } - m := v1.NewMsgVote(sender, msg.Vote.ProposalId, voteOption, "") - return []sdk.Msg{m}, nil - case msg.VoteWeighted != nil: - opts := make([]*v1.WeightedVoteOption, len(msg.VoteWeighted.Options)) - for i, v := range msg.VoteWeighted.Options { - weight, err := sdk.NewDecFromStr(v.Weight) - if err != nil { - return nil, errorsmod.Wrapf(err, "weight for vote %d", i+1) - } - voteOption, err := convertVoteOption(v.Option) - if err != nil { - return nil, errorsmod.Wrap(err, "vote option") - } - opts[i] = &v1.WeightedVoteOption{Option: voteOption, Weight: weight.String()} - } - m := v1.NewMsgVoteWeighted(sender, msg.VoteWeighted.ProposalId, opts, "") - return []sdk.Msg{m}, nil - - default: - return nil, types.ErrUnknownMsg.Wrap("unknown variant of gov") - } -} - -func convertVoteOption(s interface{}) (v1.VoteOption, error) { - var option v1.VoteOption - switch s { - case wasmvmtypes.Yes: - option = v1.OptionYes - case wasmvmtypes.No: - option = v1.OptionNo - case wasmvmtypes.NoWithVeto: - option = v1.OptionNoWithVeto - case wasmvmtypes.Abstain: - option = v1.OptionAbstain - default: - return v1.OptionEmpty, types.ErrInvalid - } - return option, nil -} - -// ConvertWasmIBCTimeoutHeightToCosmosHeight converts a wasmvm type ibc timeout height to ibc module type height -func ConvertWasmIBCTimeoutHeightToCosmosHeight(ibcTimeoutBlock *wasmvmtypes.IBCTimeoutBlock) ibcclienttypes.Height { - if ibcTimeoutBlock == nil { - return ibcclienttypes.NewHeight(0, 0) - } - return ibcclienttypes.NewHeight(ibcTimeoutBlock.Revision, ibcTimeoutBlock.Height) -} - -// ConvertWasmCoinsToSdkCoins converts the wasm vm type coins to sdk type coins -func ConvertWasmCoinsToSdkCoins(coins []wasmvmtypes.Coin) (sdk.Coins, error) { - var toSend sdk.Coins - for _, coin := range coins { - c, err := ConvertWasmCoinToSdkCoin(coin) - if err != nil { - return nil, err - } - toSend = toSend.Add(c) - } - return toSend.Sort(), nil -} - -// ConvertWasmCoinToSdkCoin converts a wasm vm type coin to sdk type coin -func ConvertWasmCoinToSdkCoin(coin wasmvmtypes.Coin) (sdk.Coin, error) { - amount, ok := sdk.NewIntFromString(coin.Amount) - if !ok { - return sdk.Coin{}, errorsmod.Wrap(sdkerrors.ErrInvalidCoins, coin.Amount+coin.Denom) - } - r := sdk.Coin{ - Denom: coin.Denom, - Amount: amount, - } - return r, r.Validate() -} diff --git a/x/wasm/keeper/handler_plugin_encoders_test.go b/x/wasm/keeper/handler_plugin_encoders_test.go deleted file mode 100644 index 9d19721..0000000 --- a/x/wasm/keeper/handler_plugin_encoders_test.go +++ /dev/null @@ -1,933 +0,0 @@ -package keeper - -import ( - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/cosmos/gogoproto/proto" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestEncoding(t *testing.T) { - var ( - addr1 = RandomAccountAddress(t) - addr2 = RandomAccountAddress(t) - addr3 = RandomAccountAddress(t) - invalidAddr = "xrnd1d02kd90n38qvr3qb9qof83fn2d2" - ) - valAddr := make(sdk.ValAddress, types.SDKAddrLen) - valAddr[0] = 12 - valAddr2 := make(sdk.ValAddress, types.SDKAddrLen) - valAddr2[1] = 123 - - jsonMsg := types.RawContractMessage(`{"foo": 123}`) - - bankMsg := &banktypes.MsgSend{ - FromAddress: addr2.String(), - ToAddress: addr1.String(), - Amount: sdk.Coins{ - sdk.NewInt64Coin("uatom", 12345), - sdk.NewInt64Coin("utgd", 54321), - }, - } - bankMsgBin, err := proto.Marshal(bankMsg) - require.NoError(t, err) - - content, err := codectypes.NewAnyWithValue(types.StoreCodeProposalFixture()) - require.NoError(t, err) - - proposalMsg := &v1beta1.MsgSubmitProposal{ - Proposer: addr1.String(), - InitialDeposit: sdk.NewCoins(sdk.NewInt64Coin("uatom", 12345)), - Content: content, - } - proposalMsgBin, err := proto.Marshal(proposalMsg) - require.NoError(t, err) - - cases := map[string]struct { - sender sdk.AccAddress - srcMsg wasmvmtypes.CosmosMsg - srcContractIBCPort string - transferPortSource types.ICS20TransferPortSource - // set if valid - output []sdk.Msg - // set if expect mapping fails - expError bool - // set if sdk validate basic should fail - expInvalid bool - }{ - "simple send": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: addr2.String(), - Amount: []wasmvmtypes.Coin{ - { - Denom: "uatom", - Amount: "12345", - }, - { - Denom: "usdt", - Amount: "54321", - }, - }, - }, - }, - }, - output: []sdk.Msg{ - &banktypes.MsgSend{ - FromAddress: addr1.String(), - ToAddress: addr2.String(), - Amount: sdk.Coins{ - sdk.NewInt64Coin("uatom", 12345), - sdk.NewInt64Coin("usdt", 54321), - }, - }, - }, - }, - "invalid send amount": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: addr2.String(), - Amount: []wasmvmtypes.Coin{ - { - Denom: "uatom", - Amount: "123.456", - }, - }, - }, - }, - }, - expError: true, - }, - "invalid address": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: invalidAddr, - Amount: []wasmvmtypes.Coin{ - { - Denom: "uatom", - Amount: "7890", - }, - }, - }, - }, - }, - expError: false, // addresses are checked in the handler - expInvalid: true, - output: []sdk.Msg{ - &banktypes.MsgSend{ - FromAddress: addr1.String(), - ToAddress: invalidAddr, - Amount: sdk.Coins{ - sdk.NewInt64Coin("uatom", 7890), - }, - }, - }, - }, - "wasm execute": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Execute: &wasmvmtypes.ExecuteMsg{ - ContractAddr: addr2.String(), - Msg: jsonMsg, - Funds: []wasmvmtypes.Coin{ - wasmvmtypes.NewCoin(12, "eth"), - }, - }, - }, - }, - output: []sdk.Msg{ - &types.MsgExecuteContract{ - Sender: addr1.String(), - Contract: addr2.String(), - Msg: jsonMsg, - Funds: sdk.NewCoins(sdk.NewInt64Coin("eth", 12)), - }, - }, - }, - "wasm instantiate": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Instantiate: &wasmvmtypes.InstantiateMsg{ - CodeID: 7, - Msg: jsonMsg, - Funds: []wasmvmtypes.Coin{ - wasmvmtypes.NewCoin(123, "eth"), - }, - Label: "myLabel", - Admin: addr2.String(), - }, - }, - }, - output: []sdk.Msg{ - &types.MsgInstantiateContract{ - Sender: addr1.String(), - CodeID: 7, - Label: "myLabel", - Msg: jsonMsg, - Funds: sdk.NewCoins(sdk.NewInt64Coin("eth", 123)), - Admin: addr2.String(), - }, - }, - }, - "wasm instantiate2": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Instantiate2: &wasmvmtypes.Instantiate2Msg{ - CodeID: 7, - Msg: jsonMsg, - Funds: []wasmvmtypes.Coin{ - wasmvmtypes.NewCoin(123, "eth"), - }, - Label: "myLabel", - Admin: addr2.String(), - Salt: []byte("mySalt"), - }, - }, - }, - output: []sdk.Msg{ - &types.MsgInstantiateContract2{ - Sender: addr1.String(), - Admin: addr2.String(), - CodeID: 7, - Label: "myLabel", - Msg: jsonMsg, - Funds: sdk.NewCoins(sdk.NewInt64Coin("eth", 123)), - Salt: []byte("mySalt"), - FixMsg: false, - }, - }, - }, - "wasm migrate": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Migrate: &wasmvmtypes.MigrateMsg{ - ContractAddr: addr1.String(), - NewCodeID: 12, - Msg: jsonMsg, - }, - }, - }, - output: []sdk.Msg{ - &types.MsgMigrateContract{ - Sender: addr2.String(), - Contract: addr1.String(), - CodeID: 12, - Msg: jsonMsg, - }, - }, - }, - "wasm update admin": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - UpdateAdmin: &wasmvmtypes.UpdateAdminMsg{ - ContractAddr: addr1.String(), - Admin: addr3.String(), - }, - }, - }, - output: []sdk.Msg{ - &types.MsgUpdateAdmin{ - Sender: addr2.String(), - Contract: addr1.String(), - NewAdmin: addr3.String(), - }, - }, - }, - "wasm clear admin": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - ClearAdmin: &wasmvmtypes.ClearAdminMsg{ - ContractAddr: addr1.String(), - }, - }, - }, - output: []sdk.Msg{ - &types.MsgClearAdmin{ - Sender: addr2.String(), - Contract: addr1.String(), - }, - }, - }, - "staking delegate": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Delegate: &wasmvmtypes.DelegateMsg{ - Validator: valAddr.String(), - Amount: wasmvmtypes.NewCoin(777, "stake"), - }, - }, - }, - output: []sdk.Msg{ - &stakingtypes.MsgDelegate{ - DelegatorAddress: addr1.String(), - ValidatorAddress: valAddr.String(), - Amount: sdk.NewInt64Coin("stake", 777), - }, - }, - }, - "staking delegate to non-validator": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Delegate: &wasmvmtypes.DelegateMsg{ - Validator: addr2.String(), - Amount: wasmvmtypes.NewCoin(777, "stake"), - }, - }, - }, - expError: false, // fails in the handler - expInvalid: true, - output: []sdk.Msg{ - &stakingtypes.MsgDelegate{ - DelegatorAddress: addr1.String(), - ValidatorAddress: addr2.String(), - Amount: sdk.NewInt64Coin("stake", 777), - }, - }, - }, - "staking undelegate": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Undelegate: &wasmvmtypes.UndelegateMsg{ - Validator: valAddr.String(), - Amount: wasmvmtypes.NewCoin(555, "stake"), - }, - }, - }, - output: []sdk.Msg{ - &stakingtypes.MsgUndelegate{ - DelegatorAddress: addr1.String(), - ValidatorAddress: valAddr.String(), - Amount: sdk.NewInt64Coin("stake", 555), - }, - }, - }, - "staking redelegate": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Staking: &wasmvmtypes.StakingMsg{ - Redelegate: &wasmvmtypes.RedelegateMsg{ - SrcValidator: valAddr.String(), - DstValidator: valAddr2.String(), - Amount: wasmvmtypes.NewCoin(222, "stake"), - }, - }, - }, - output: []sdk.Msg{ - &stakingtypes.MsgBeginRedelegate{ - DelegatorAddress: addr1.String(), - ValidatorSrcAddress: valAddr.String(), - ValidatorDstAddress: valAddr2.String(), - Amount: sdk.NewInt64Coin("stake", 222), - }, - }, - }, - "staking withdraw (explicit recipient)": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Distribution: &wasmvmtypes.DistributionMsg{ - WithdrawDelegatorReward: &wasmvmtypes.WithdrawDelegatorRewardMsg{ - Validator: valAddr2.String(), - }, - }, - }, - output: []sdk.Msg{ - &distributiontypes.MsgWithdrawDelegatorReward{ - DelegatorAddress: addr1.String(), - ValidatorAddress: valAddr2.String(), - }, - }, - }, - "staking set withdraw address": { - sender: addr1, - srcMsg: wasmvmtypes.CosmosMsg{ - Distribution: &wasmvmtypes.DistributionMsg{ - SetWithdrawAddress: &wasmvmtypes.SetWithdrawAddressMsg{ - Address: addr2.String(), - }, - }, - }, - output: []sdk.Msg{ - &distributiontypes.MsgSetWithdrawAddress{ - DelegatorAddress: addr1.String(), - WithdrawAddress: addr2.String(), - }, - }, - }, - "stargate encoded bank msg": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Stargate: &wasmvmtypes.StargateMsg{ - TypeURL: "/cosmos.bank.v1beta1.MsgSend", - Value: bankMsgBin, - }, - }, - output: []sdk.Msg{bankMsg}, - }, - "stargate encoded msg with any type": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Stargate: &wasmvmtypes.StargateMsg{ - TypeURL: "/cosmos.gov.v1beta1.MsgSubmitProposal", - Value: proposalMsgBin, - }, - }, - output: []sdk.Msg{proposalMsg}, - }, - "stargate encoded invalid typeUrl": { - sender: addr2, - srcMsg: wasmvmtypes.CosmosMsg{ - Stargate: &wasmvmtypes.StargateMsg{ - TypeURL: "/cosmos.bank.v2.MsgSend", - Value: bankMsgBin, - }, - }, - expError: true, - }, - "IBC transfer with block timeout": { - sender: addr1, - srcContractIBCPort: "myIBCPort", - srcMsg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - Transfer: &wasmvmtypes.TransferMsg{ - ChannelID: "myChanID", - ToAddress: addr2.String(), - Amount: wasmvmtypes.Coin{ - Denom: "ALX", - Amount: "1", - }, - Timeout: wasmvmtypes.IBCTimeout{ - Block: &wasmvmtypes.IBCTimeoutBlock{Revision: 1, Height: 2}, - }, - }, - }, - }, - transferPortSource: wasmtesting.MockIBCTransferKeeper{GetPortFn: func(ctx sdk.Context) string { - return "myTransferPort" - }}, - output: []sdk.Msg{ - &ibctransfertypes.MsgTransfer{ - SourcePort: "myTransferPort", - SourceChannel: "myChanID", - Token: sdk.Coin{ - Denom: "ALX", - Amount: sdk.NewInt(1), - }, - Sender: addr1.String(), - Receiver: addr2.String(), - TimeoutHeight: clienttypes.Height{RevisionNumber: 1, RevisionHeight: 2}, - }, - }, - }, - "IBC transfer with time timeout": { - sender: addr1, - srcContractIBCPort: "myIBCPort", - srcMsg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - Transfer: &wasmvmtypes.TransferMsg{ - ChannelID: "myChanID", - ToAddress: addr2.String(), - Amount: wasmvmtypes.Coin{ - Denom: "ALX", - Amount: "1", - }, - Timeout: wasmvmtypes.IBCTimeout{Timestamp: 100}, - }, - }, - }, - transferPortSource: wasmtesting.MockIBCTransferKeeper{GetPortFn: func(ctx sdk.Context) string { - return "transfer" - }}, - output: []sdk.Msg{ - &ibctransfertypes.MsgTransfer{ - SourcePort: "transfer", - SourceChannel: "myChanID", - Token: sdk.Coin{ - Denom: "ALX", - Amount: sdk.NewInt(1), - }, - Sender: addr1.String(), - Receiver: addr2.String(), - TimeoutTimestamp: 100, - }, - }, - }, - "IBC transfer with time and height timeout": { - sender: addr1, - srcContractIBCPort: "myIBCPort", - srcMsg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - Transfer: &wasmvmtypes.TransferMsg{ - ChannelID: "myChanID", - ToAddress: addr2.String(), - Amount: wasmvmtypes.Coin{ - Denom: "ALX", - Amount: "1", - }, - Timeout: wasmvmtypes.IBCTimeout{Timestamp: 100, Block: &wasmvmtypes.IBCTimeoutBlock{Height: 1, Revision: 2}}, - }, - }, - }, - transferPortSource: wasmtesting.MockIBCTransferKeeper{GetPortFn: func(ctx sdk.Context) string { - return "transfer" - }}, - output: []sdk.Msg{ - &ibctransfertypes.MsgTransfer{ - SourcePort: "transfer", - SourceChannel: "myChanID", - Token: sdk.Coin{ - Denom: "ALX", - Amount: sdk.NewInt(1), - }, - Sender: addr1.String(), - Receiver: addr2.String(), - TimeoutTimestamp: 100, - TimeoutHeight: clienttypes.NewHeight(2, 1), - }, - }, - }, - "IBC close channel": { - sender: addr1, - srcContractIBCPort: "myIBCPort", - srcMsg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - CloseChannel: &wasmvmtypes.CloseChannelMsg{ - ChannelID: "channel-1", - }, - }, - }, - output: []sdk.Msg{ - &channeltypes.MsgChannelCloseInit{ - PortId: "wasm." + addr1.String(), - ChannelId: "channel-1", - Signer: addr1.String(), - }, - }, - }, - } - encodingConfig := MakeEncodingConfig(t) - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - var ctx sdk.Context - encoder := DefaultEncoders(encodingConfig.Marshaler, tc.transferPortSource) - res, err := encoder.Encode(ctx, tc.sender, tc.srcContractIBCPort, tc.srcMsg) - if tc.expError { - assert.Error(t, err) - return - } - require.NoError(t, err) - assert.Equal(t, tc.output, res) - - // and valid sdk message - for _, v := range res { - gotErr := v.ValidateBasic() - if tc.expInvalid { - assert.Error(t, gotErr) - } else { - assert.NoError(t, gotErr) - } - } - }) - } -} - -func TestEncodeGovMsg(t *testing.T) { - myAddr := RandomAccountAddress(t) - - cases := map[string]struct { - sender sdk.AccAddress - srcMsg wasmvmtypes.CosmosMsg - transferPortSource types.ICS20TransferPortSource - // set if valid - output []sdk.Msg - // set if expect mapping fails - expError bool - // set if sdk validate basic should fail - expInvalid bool - }{ - "Gov vote: yes": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 1, Vote: wasmvmtypes.Yes}, - }, - }, - output: []sdk.Msg{ - &v1.MsgVote{ - ProposalId: 1, - Voter: myAddr.String(), - Option: v1.OptionYes, - }, - }, - }, - "Gov vote: No": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 1, Vote: wasmvmtypes.No}, - }, - }, - output: []sdk.Msg{ - &v1.MsgVote{ - ProposalId: 1, - Voter: myAddr.String(), - Option: v1.OptionNo, - }, - }, - }, - "Gov vote: Abstain": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 10, Vote: wasmvmtypes.Abstain}, - }, - }, - output: []sdk.Msg{ - &v1.MsgVote{ - ProposalId: 10, - Voter: myAddr.String(), - Option: v1.OptionAbstain, - }, - }, - }, - "Gov vote: No with veto": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 1, Vote: wasmvmtypes.NoWithVeto}, - }, - }, - output: []sdk.Msg{ - &v1.MsgVote{ - ProposalId: 1, - Voter: myAddr.String(), - Option: v1.OptionNoWithVeto, - }, - }, - }, - "Gov vote: unset option": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - Vote: &wasmvmtypes.VoteMsg{ProposalId: 1}, - }, - }, - expError: true, - }, - "Gov weighted vote: single vote": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "1"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDec(1).String()}, - }, - }, - }, - }, - "Gov weighted vote: splitted": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "0.23"}, - {Option: wasmvmtypes.No, Weight: "0.24"}, - {Option: wasmvmtypes.Abstain, Weight: "0.26"}, - {Option: wasmvmtypes.NoWithVeto, Weight: "0.27"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(23, 2).String()}, - {Option: v1.OptionNo, Weight: sdk.NewDecWithPrec(24, 2).String()}, - {Option: v1.OptionAbstain, Weight: sdk.NewDecWithPrec(26, 2).String()}, - {Option: v1.OptionNoWithVeto, Weight: sdk.NewDecWithPrec(27, 2).String()}, - }, - }, - }, - }, - "Gov weighted vote: duplicate option": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "0.5"}, - {Option: wasmvmtypes.Yes, Weight: "0.5"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(5, 1).String()}, - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(5, 1).String()}, - }, - }, - }, - expInvalid: true, - }, - "Gov weighted vote: weight sum exceeds 1": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "0.51"}, - {Option: wasmvmtypes.No, Weight: "0.5"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(51, 2).String()}, - {Option: v1.OptionNo, Weight: sdk.NewDecWithPrec(5, 1).String()}, - }, - }, - }, - expInvalid: true, - }, - "Gov weighted vote: weight sum less than 1": { - sender: myAddr, - srcMsg: wasmvmtypes.CosmosMsg{ - Gov: &wasmvmtypes.GovMsg{ - VoteWeighted: &wasmvmtypes.VoteWeightedMsg{ - ProposalId: 1, - Options: []wasmvmtypes.WeightedVoteOption{ - {Option: wasmvmtypes.Yes, Weight: "0.49"}, - {Option: wasmvmtypes.No, Weight: "0.5"}, - }, - }, - }, - }, - output: []sdk.Msg{ - &v1.MsgVoteWeighted{ - ProposalId: 1, - Voter: myAddr.String(), - Options: []*v1.WeightedVoteOption{ - {Option: v1.OptionYes, Weight: sdk.NewDecWithPrec(49, 2).String()}, - {Option: v1.OptionNo, Weight: sdk.NewDecWithPrec(5, 1).String()}, - }, - }, - }, - expInvalid: true, - }, - } - encodingConfig := MakeEncodingConfig(t) - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - var ctx sdk.Context - encoder := DefaultEncoders(encodingConfig.Marshaler, tc.transferPortSource) - res, gotEncErr := encoder.Encode(ctx, tc.sender, "myIBCPort", tc.srcMsg) - if tc.expError { - assert.Error(t, gotEncErr) - return - } - require.NoError(t, gotEncErr) - assert.Equal(t, tc.output, res) - - // and valid sdk message - for _, v := range res { - gotErr := v.ValidateBasic() - if tc.expInvalid { - assert.Error(t, gotErr) - } else { - assert.NoError(t, gotErr) - } - } - }) - } -} - -func TestConvertWasmCoinToSdkCoin(t *testing.T) { - specs := map[string]struct { - src wasmvmtypes.Coin - expErr bool - expVal sdk.Coin - }{ - "all good": { - src: wasmvmtypes.Coin{ - Denom: "foo", - Amount: "1", - }, - expVal: sdk.NewCoin("foo", sdk.NewIntFromUint64(1)), - }, - "negative amount": { - src: wasmvmtypes.Coin{ - Denom: "foo", - Amount: "-1", - }, - expErr: true, - }, - "denom to short": { - src: wasmvmtypes.Coin{ - Denom: "f", - Amount: "1", - }, - expErr: true, - }, - "invalid demum char": { - src: wasmvmtypes.Coin{ - Denom: "&fff", - Amount: "1", - }, - expErr: true, - }, - "not a number amount": { - src: wasmvmtypes.Coin{ - Denom: "foo", - Amount: "bar", - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotVal, gotErr := ConvertWasmCoinToSdkCoin(spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expVal, gotVal) - }) - } -} - -func TestConvertWasmCoinsToSdkCoins(t *testing.T) { - specs := map[string]struct { - src []wasmvmtypes.Coin - exp sdk.Coins - expErr bool - }{ - "empty": { - src: []wasmvmtypes.Coin{}, - exp: nil, - }, - "single coin": { - src: []wasmvmtypes.Coin{{Denom: "foo", Amount: "1"}}, - exp: sdk.NewCoins(sdk.NewCoin("foo", sdk.NewInt(1))), - }, - "multiple coins": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "1"}, - {Denom: "bar", Amount: "2"}, - }, - exp: sdk.NewCoins( - sdk.NewCoin("bar", sdk.NewInt(2)), - sdk.NewCoin("foo", sdk.NewInt(1)), - ), - }, - "sorted": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "1"}, - {Denom: "other", Amount: "1"}, - {Denom: "bar", Amount: "1"}, - }, - exp: []sdk.Coin{ - sdk.NewCoin("bar", sdk.NewInt(1)), - sdk.NewCoin("foo", sdk.NewInt(1)), - sdk.NewCoin("other", sdk.NewInt(1)), - }, - }, - "zero amounts dropped": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "1"}, - {Denom: "bar", Amount: "0"}, - }, - exp: sdk.NewCoins( - sdk.NewCoin("foo", sdk.NewInt(1)), - ), - }, - "duplicate denoms merged": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "1"}, - {Denom: "foo", Amount: "1"}, - }, - exp: []sdk.Coin{sdk.NewCoin("foo", sdk.NewInt(2))}, - }, - "duplicate denoms with one 0 amount does not fail": { - src: []wasmvmtypes.Coin{ - {Denom: "foo", Amount: "0"}, - {Denom: "foo", Amount: "1"}, - }, - exp: []sdk.Coin{sdk.NewCoin("foo", sdk.NewInt(1))}, - }, - "empty denom rejected": { - src: []wasmvmtypes.Coin{{Denom: "", Amount: "1"}}, - expErr: true, - }, - "invalid denom rejected": { - src: []wasmvmtypes.Coin{{Denom: "!%&", Amount: "1"}}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotCoins, gotErr := ConvertWasmCoinsToSdkCoins(spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.exp, gotCoins) - assert.NoError(t, gotCoins.Validate()) - }) - } -} diff --git a/x/wasm/keeper/handler_plugin_test.go b/x/wasm/keeper/handler_plugin_test.go deleted file mode 100644 index 42cc810..0000000 --- a/x/wasm/keeper/handler_plugin_test.go +++ /dev/null @@ -1,415 +0,0 @@ -package keeper - -import ( - "encoding/json" - "testing" - - errorsmod "cosmossdk.io/errors" - "github.com/cometbft/cometbft/libs/log" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestMessageHandlerChainDispatch(t *testing.T) { - capturingHandler, gotMsgs := wasmtesting.NewCapturingMessageHandler() - - alwaysUnknownMsgHandler := &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, types.ErrUnknownMsg - }, - } - - assertNotCalledHandler := &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - t.Fatal("not expected to be called") - return - }, - } - - myMsg := wasmvmtypes.CosmosMsg{Custom: []byte(`{}`)} - specs := map[string]struct { - handlers []Messenger - expErr *errorsmod.Error - expEvents []sdk.Event - }{ - "single handler": { - handlers: []Messenger{capturingHandler}, - }, - "passed to next handler": { - handlers: []Messenger{alwaysUnknownMsgHandler, capturingHandler}, - }, - "stops iteration when handled": { - handlers: []Messenger{capturingHandler, assertNotCalledHandler}, - }, - "stops iteration on handler error": { - handlers: []Messenger{&wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, types.ErrInvalidMsg - }, - }, assertNotCalledHandler}, - expErr: types.ErrInvalidMsg, - }, - "return events when handle": { - handlers: []Messenger{ - &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - _, data, _ = capturingHandler.DispatchMsg(ctx, contractAddr, contractIBCPortID, msg) - return []sdk.Event{sdk.NewEvent("myEvent", sdk.NewAttribute("foo", "bar"))}, data, nil - }, - }, - }, - expEvents: []sdk.Event{sdk.NewEvent("myEvent", sdk.NewAttribute("foo", "bar"))}, - }, - "return error when none can handle": { - handlers: []Messenger{alwaysUnknownMsgHandler}, - expErr: types.ErrUnknownMsg, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - *gotMsgs = make([]wasmvmtypes.CosmosMsg, 0) - - // when - h := MessageHandlerChain{spec.handlers} - gotEvents, gotData, gotErr := h.DispatchMsg(sdk.Context{}, RandomAccountAddress(t), "anyPort", myMsg) - - // then - require.True(t, spec.expErr.Is(gotErr), "exp %v but got %#+v", spec.expErr, gotErr) - if spec.expErr != nil { - return - } - assert.Equal(t, []wasmvmtypes.CosmosMsg{myMsg}, *gotMsgs) - assert.Equal(t, [][]byte{{1}}, gotData) // {1} is default in capturing handler - assert.Equal(t, spec.expEvents, gotEvents) - }) - } -} - -func TestSDKMessageHandlerDispatch(t *testing.T) { - myEvent := sdk.NewEvent("myEvent", sdk.NewAttribute("foo", "bar")) - const myData = "myData" - myRouterResult := sdk.Result{ - Data: []byte(myData), - Events: sdk.Events{myEvent}.ToABCIEvents(), - } - - var gotMsg []sdk.Msg - capturingMessageRouter := wasmtesting.MessageRouterFunc(func(msg sdk.Msg) baseapp.MsgServiceHandler { - return func(ctx sdk.Context, req sdk.Msg) (*sdk.Result, error) { - gotMsg = append(gotMsg, msg) - return &myRouterResult, nil - } - }) - noRouteMessageRouter := wasmtesting.MessageRouterFunc(func(msg sdk.Msg) baseapp.MsgServiceHandler { - return nil - }) - myContractAddr := RandomAccountAddress(t) - myContractMessage := wasmvmtypes.CosmosMsg{Custom: []byte("{}")} - - specs := map[string]struct { - srcRoute MessageRouter - srcEncoder CustomEncoder - expErr *errorsmod.Error - expMsgDispatched int - }{ - "all good": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - myMsg := types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - return []sdk.Msg{&myMsg}, nil - }, - expMsgDispatched: 1, - }, - "multiple output msgs": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - first := &types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - second := &types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - return []sdk.Msg{first, second}, nil - }, - expMsgDispatched: 2, - }, - "invalid sdk message rejected": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - invalidMsg := types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("INVALID_JSON"), - } - return []sdk.Msg{&invalidMsg}, nil - }, - expErr: types.ErrInvalid, - }, - "invalid sender rejected": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - invalidMsg := types.MsgExecuteContract{ - Sender: RandomBech32AccountAddress(t), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - return []sdk.Msg{&invalidMsg}, nil - }, - expErr: sdkerrors.ErrUnauthorized, - }, - "unroutable message rejected": { - srcRoute: noRouteMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - myMsg := types.MsgExecuteContract{ - Sender: myContractAddr.String(), - Contract: RandomBech32AccountAddress(t), - Msg: []byte("{}"), - } - return []sdk.Msg{&myMsg}, nil - }, - expErr: sdkerrors.ErrUnknownRequest, - }, - "encoding error passed": { - srcRoute: capturingMessageRouter, - srcEncoder: func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - myErr := types.ErrUnpinContractFailed // any error that is not used - return nil, myErr - }, - expErr: types.ErrUnpinContractFailed, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotMsg = make([]sdk.Msg, 0) - - // when - ctx := sdk.Context{} - h := NewSDKMessageHandler(spec.srcRoute, MessageEncoders{Custom: spec.srcEncoder}) - gotEvents, gotData, gotErr := h.DispatchMsg(ctx, myContractAddr, "myPort", myContractMessage) - - // then - require.True(t, spec.expErr.Is(gotErr), "exp %v but got %#+v", spec.expErr, gotErr) - if spec.expErr != nil { - require.Len(t, gotMsg, 0) - return - } - assert.Len(t, gotMsg, spec.expMsgDispatched) - for i := 0; i < spec.expMsgDispatched; i++ { - assert.Equal(t, myEvent, gotEvents[i]) - assert.Equal(t, []byte(myData), gotData[i]) - } - }) - } -} - -func TestIBCRawPacketHandler(t *testing.T) { - ibcPort := "contractsIBCPort" - ctx := sdk.Context{}.WithLogger(log.TestingLogger()) - - type CapturedPacket struct { - sourcePort string - sourceChannel string - timeoutHeight clienttypes.Height - timeoutTimestamp uint64 - data []byte - } - var capturedPacket *CapturedPacket - - chanKeeper := &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channeltypes.Channel, bool) { - return channeltypes.Channel{ - Counterparty: channeltypes.NewCounterparty( - "other-port", - "other-channel-1", - ), - }, true - }, - SendPacketFn: func(ctx sdk.Context, channelCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte) (uint64, error) { - capturedPacket = &CapturedPacket{ - sourcePort: sourcePort, - sourceChannel: sourceChannel, - timeoutHeight: timeoutHeight, - timeoutTimestamp: timeoutTimestamp, - data: data, - } - return 1, nil - }, - } - capKeeper := &wasmtesting.MockCapabilityKeeper{ - GetCapabilityFn: func(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) { - return &capabilitytypes.Capability{}, true - }, - } - - specs := map[string]struct { - srcMsg wasmvmtypes.SendPacketMsg - chanKeeper types.ChannelKeeper - capKeeper types.CapabilityKeeper - expPacketSent *CapturedPacket - expErr *errorsmod.Error - }{ - "all good": { - srcMsg: wasmvmtypes.SendPacketMsg{ - ChannelID: "channel-1", - Data: []byte("myData"), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{Revision: 1, Height: 2}}, - }, - chanKeeper: chanKeeper, - capKeeper: capKeeper, - expPacketSent: &CapturedPacket{ - sourcePort: ibcPort, - sourceChannel: "channel-1", - timeoutHeight: clienttypes.Height{RevisionNumber: 1, RevisionHeight: 2}, - data: []byte("myData"), - }, - }, - "capability not found returns error": { - srcMsg: wasmvmtypes.SendPacketMsg{ - ChannelID: "channel-1", - Data: []byte("myData"), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{Revision: 1, Height: 2}}, - }, - chanKeeper: chanKeeper, - capKeeper: wasmtesting.MockCapabilityKeeper{ - GetCapabilityFn: func(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) { - return nil, false - }, - }, - expErr: channeltypes.ErrChannelCapabilityNotFound, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - capturedPacket = nil - // when - h := NewIBCRawPacketHandler(spec.chanKeeper, spec.capKeeper) - evts, data, gotErr := h.DispatchMsg(ctx, RandomAccountAddress(t), ibcPort, wasmvmtypes.CosmosMsg{IBC: &wasmvmtypes.IBCMsg{SendPacket: &spec.srcMsg}}) - // then - require.True(t, spec.expErr.Is(gotErr), "exp %v but got %#+v", spec.expErr, gotErr) - if spec.expErr != nil { - return - } - - assert.Nil(t, evts) - require.NotNil(t, data) - - expMsg := types.MsgIBCSendResponse{Sequence: 1} - - actualMsg := types.MsgIBCSendResponse{} - err := actualMsg.Unmarshal(data[0]) - require.NoError(t, err) - - assert.Equal(t, expMsg, actualMsg) - assert.Equal(t, spec.expPacketSent, capturedPacket) - }) - } -} - -func TestBurnCoinMessageHandlerIntegration(t *testing.T) { - // testing via full keeper setup so that we are confident the - // module permissions are set correct and no other handler - // picks the message in the default handler chain - ctx, keepers := CreateDefaultTestInput(t) - // set some supply - keepers.Faucet.NewFundedRandomAccount(ctx, sdk.NewCoin("denom", sdk.NewInt(10_000_000))) - k := keepers.WasmKeeper - - example := InstantiateHackatomExampleContract(t, ctx, keepers) // with deposit of 100 stake - - before, err := keepers.BankKeeper.TotalSupply(sdk.WrapSDKContext(ctx), &banktypes.QueryTotalSupplyRequest{}) - require.NoError(t, err) - - specs := map[string]struct { - msg wasmvmtypes.BurnMsg - expErr bool - }{ - "all good": { - msg: wasmvmtypes.BurnMsg{ - Amount: wasmvmtypes.Coins{{ - Denom: "denom", - Amount: "100", - }}, - }, - }, - "not enough funds in contract": { - msg: wasmvmtypes.BurnMsg{ - Amount: wasmvmtypes.Coins{{ - Denom: "denom", - Amount: "101", - }}, - }, - expErr: true, - }, - "zero amount rejected": { - msg: wasmvmtypes.BurnMsg{ - Amount: wasmvmtypes.Coins{{ - Denom: "denom", - Amount: "0", - }}, - }, - expErr: true, - }, - "unknown denom - insufficient funds": { - msg: wasmvmtypes.BurnMsg{ - Amount: wasmvmtypes.Coins{{ - Denom: "unknown", - Amount: "1", - }}, - }, - expErr: true, - }, - } - parentCtx := ctx - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ = parentCtx.CacheContext() - k.wasmVM = &wasmtesting.MockWasmer{ExecuteFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{ - Messages: []wasmvmtypes.SubMsg{ - {Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{Burn: &spec.msg}}, ReplyOn: wasmvmtypes.ReplyNever}, - }, - }, 0, nil - }} - - // when - _, err = k.execute(ctx, example.Contract, example.CreatorAddr, nil, nil) - - // then - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - - // and total supply reduced by burned amount - after, err := keepers.BankKeeper.TotalSupply(sdk.WrapSDKContext(ctx), &banktypes.QueryTotalSupplyRequest{}) - require.NoError(t, err) - diff := before.Supply.Sub(after.Supply...) - assert.Equal(t, sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(100))), diff) - }) - } - - // test cases: - // not enough money to burn -} diff --git a/x/wasm/keeper/ibc.go b/x/wasm/keeper/ibc.go deleted file mode 100644 index ff94048..0000000 --- a/x/wasm/keeper/ibc.go +++ /dev/null @@ -1,56 +0,0 @@ -package keeper - -import ( - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - host "github.com/cosmos/ibc-go/v7/modules/core/24-host" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// bindIbcPort will reserve the port. -// returns a string name of the port or error if we cannot bind it. -// this will fail if call twice. -func (k Keeper) bindIbcPort(ctx sdk.Context, portID string) error { - portCap := k.portKeeper.BindPort(ctx, portID) - return k.ClaimCapability(ctx, portCap, host.PortPath(portID)) -} - -// ensureIbcPort is like registerIbcPort, but it checks if we already hold the port -// before calling register, so this is safe to call multiple times. -// Returns success if we already registered or just registered and error if we cannot -// (lack of permissions or someone else has it) -func (k Keeper) ensureIbcPort(ctx sdk.Context, contractAddr sdk.AccAddress) (string, error) { - portID := PortIDForContract(contractAddr) - if _, ok := k.capabilityKeeper.GetCapability(ctx, host.PortPath(portID)); ok { - return portID, nil - } - return portID, k.bindIbcPort(ctx, portID) -} - -const portIDPrefix = "wasm." - -func PortIDForContract(addr sdk.AccAddress) string { - return portIDPrefix + addr.String() -} - -func ContractFromPortID(portID string) (sdk.AccAddress, error) { - if !strings.HasPrefix(portID, portIDPrefix) { - return nil, errorsmod.Wrapf(types.ErrInvalid, "without prefix") - } - return sdk.AccAddressFromBech32(portID[len(portIDPrefix):]) -} - -// AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function -func (k Keeper) AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool { - return k.capabilityKeeper.AuthenticateCapability(ctx, cap, name) -} - -// ClaimCapability allows the transfer module to claim a capability -// that IBC module passes to it -func (k Keeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error { - return k.capabilityKeeper.ClaimCapability(ctx, cap, name) -} diff --git a/x/wasm/keeper/ibc_test.go b/x/wasm/keeper/ibc_test.go deleted file mode 100644 index 063dfb7..0000000 --- a/x/wasm/keeper/ibc_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package keeper - -import ( - "fmt" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - - "github.com/stretchr/testify/require" -) - -func TestDontBindPortNonIBCContract(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example := InstantiateHackatomExampleContract(t, ctx, keepers) // ensure we bound the port - _, _, err := keepers.IBCKeeper.PortKeeper.LookupModuleByPort(ctx, keepers.WasmKeeper.GetContractInfo(ctx, example.Contract).IBCPortID) - require.Error(t, err) -} - -func TestBindingPortForIBCContractOnInstantiate(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example := InstantiateIBCReflectContract(t, ctx, keepers) // ensure we bound the port - owner, _, err := keepers.IBCKeeper.PortKeeper.LookupModuleByPort(ctx, keepers.WasmKeeper.GetContractInfo(ctx, example.Contract).IBCPortID) - require.NoError(t, err) - require.Equal(t, "wasm", owner) - - initMsgBz := IBCReflectInitMsg{ - ReflectCodeID: example.ReflectCodeID, - }.GetBytes(t) - - // create a second contract should give yet another portID (and different address) - creator := RandomAccountAddress(t) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, creator, nil, initMsgBz, "ibc-reflect-2", nil) - require.NoError(t, err) - require.NotEqual(t, example.Contract, addr) - - portID2 := PortIDForContract(addr) - owner, _, err = keepers.IBCKeeper.PortKeeper.LookupModuleByPort(ctx, portID2) - require.NoError(t, err) - require.Equal(t, "wasm", owner) -} - -func TestContractFromPortID(t *testing.T) { - contractAddr := BuildContractAddressClassic(1, 100) - specs := map[string]struct { - srcPort string - expAddr sdk.AccAddress - expErr bool - }{ - "all good": { - srcPort: fmt.Sprintf("wasm.%s", contractAddr.String()), - expAddr: contractAddr, - }, - "without prefix": { - srcPort: contractAddr.String(), - expErr: true, - }, - "invalid prefix": { - srcPort: fmt.Sprintf("wasmx.%s", contractAddr.String()), - expErr: true, - }, - "without separator char": { - srcPort: fmt.Sprintf("wasm%s", contractAddr.String()), - expErr: true, - }, - "invalid account": { - srcPort: "wasm.foobar", - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotAddr, gotErr := ContractFromPortID(spec.srcPort) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expAddr, gotAddr) - }) - } -} diff --git a/x/wasm/keeper/keeper.go b/x/wasm/keeper/keeper.go deleted file mode 100644 index f5d5c4d..0000000 --- a/x/wasm/keeper/keeper.go +++ /dev/null @@ -1,1211 +0,0 @@ -package keeper - -import ( - "bytes" - "context" - "encoding/binary" - "encoding/hex" - "fmt" - "math" - "reflect" - "strconv" - "strings" - "time" - - errorsmod "cosmossdk.io/errors" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/log" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" - - "github.com/terpnetwork/terp-core/x/wasm/ioutils" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// contractMemoryLimit is the memory limit of each contract execution (in MiB) -// constant value so all nodes run with the same limit. -const contractMemoryLimit = 32 - -type contextKey int - -const ( - // private type creates an interface key for Context that cannot be accessed by any other package - contextKeyQueryStackSize contextKey = iota -) - -// Option is an extension point to instantiate keeper with non default values -type Option interface { - apply(*Keeper) -} - -// WasmVMQueryHandler is an extension point for custom query handler implementations -type WasmVMQueryHandler interface { - // HandleQuery executes the requested query - HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) -} - -type CoinTransferrer interface { - // TransferCoins sends the coin amounts from the source to the destination with rules applied. - TransferCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error -} - -// AccountPruner handles the balances and data cleanup for accounts that are pruned on contract instantiate. -// This is an extension point to attach custom logic -type AccountPruner interface { - // CleanupExistingAccount handles the cleanup process for balances and data of the given account. The persisted account - // type is already reset to base account at this stage. - // The method returns true when the account address can be reused. Unsupported account types are rejected by returning false - CleanupExistingAccount(ctx sdk.Context, existingAccount authtypes.AccountI) (handled bool, err error) -} - -// WasmVMResponseHandler is an extension point to handles the response data returned by a contract call. -type WasmVMResponseHandler interface { - // Handle processes the data returned by a contract invocation. - Handle( - ctx sdk.Context, - contractAddr sdk.AccAddress, - ibcPort string, - messages []wasmvmtypes.SubMsg, - origRspData []byte, - ) ([]byte, error) -} - -// list of account types that are accepted for wasm contracts. Chains importing wasmd -// can overwrite this list with the WithAcceptedAccountTypesOnContractInstantiation option. -var defaultAcceptedAccountTypes = map[reflect.Type]struct{}{ - reflect.TypeOf(&authtypes.BaseAccount{}): {}, -} - -// Keeper will have a reference to Wasmer with it's own data directory. -type Keeper struct { - storeKey storetypes.StoreKey - cdc codec.Codec - accountKeeper types.AccountKeeper - bank CoinTransferrer - portKeeper types.PortKeeper - capabilityKeeper types.CapabilityKeeper - wasmVM types.WasmerEngine - wasmVMQueryHandler WasmVMQueryHandler - wasmVMResponseHandler WasmVMResponseHandler - messenger Messenger - // queryGasLimit is the max wasmvm gas that can be spent on executing a query with a contract - queryGasLimit uint64 - gasRegister GasRegister - maxQueryStackSize uint32 - acceptedAccountTypes map[reflect.Type]struct{} - accountPruner AccountPruner - // the address capable of executing a MsgUpdateParams message. Typically, this - // should be the x/gov module account. - authority string -} - -func (k Keeper) getUploadAccessConfig(ctx sdk.Context) types.AccessConfig { - return k.GetParams(ctx).CodeUploadAccess -} - -func (k Keeper) getInstantiateAccessConfig(ctx sdk.Context) types.AccessType { - return k.GetParams(ctx).InstantiateDefaultPermission -} - -// GetParams returns the total set of wasm parameters. -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - var params types.Params - store := ctx.KVStore(k.storeKey) - bz := store.Get(types.ParamsKey) - if bz == nil { - return params - } - - k.cdc.MustUnmarshal(bz, ¶ms) - return params -} - -// SetParams sets all wasm parameters. -func (k Keeper) SetParams(ctx sdk.Context, ps types.Params) error { - if err := ps.ValidateBasic(); err != nil { - return err - } - - store := ctx.KVStore(k.storeKey) - bz, err := k.cdc.Marshal(&ps) - if err != nil { - return err - } - store.Set(types.ParamsKey, bz) - - return nil -} - -// GetAuthority returns the x/wasm module's authority. -func (k Keeper) GetAuthority() string { - return k.authority -} - -func (k Keeper) create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *types.AccessConfig, authZ AuthorizationPolicy) (codeID uint64, checksum []byte, err error) { - if creator == nil { - return 0, checksum, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "cannot be nil") - } - - // figure out proper instantiate access - defaultAccessConfig := k.getInstantiateAccessConfig(ctx).With(creator) - if instantiateAccess == nil { - instantiateAccess = &defaultAccessConfig - } - chainConfigs := ChainAccessConfigs{ - Instantiate: defaultAccessConfig, - Upload: k.getUploadAccessConfig(ctx), - } - - if !authZ.CanCreateCode(chainConfigs, creator, *instantiateAccess) { - return 0, checksum, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not create code") - } - - if ioutils.IsGzip(wasmCode) { - ctx.GasMeter().ConsumeGas(k.gasRegister.UncompressCosts(len(wasmCode)), "Uncompress gzip bytecode") - wasmCode, err = ioutils.Uncompress(wasmCode, uint64(types.MaxWasmSize)) - if err != nil { - return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - } - - ctx.GasMeter().ConsumeGas(k.gasRegister.CompileCosts(len(wasmCode)), "Compiling wasm bytecode") - checksum, err = k.wasmVM.Create(wasmCode) - if err != nil { - return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - report, err := k.wasmVM.AnalyzeCode(checksum) - if err != nil { - return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - codeID = k.autoIncrementID(ctx, types.KeyLastCodeID) - k.Logger(ctx).Debug("storing new contract", "capabilities", report.RequiredCapabilities, "code_id", codeID) - codeInfo := types.NewCodeInfo(checksum, creator, *instantiateAccess) - k.storeCodeInfo(ctx, codeID, codeInfo) - - evt := sdk.NewEvent( - types.EventTypeStoreCode, - sdk.NewAttribute(types.AttributeKeyChecksum, hex.EncodeToString(checksum)), - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), // last element to be compatible with scripts - ) - for _, f := range strings.Split(report.RequiredCapabilities, ",") { - evt.AppendAttributes(sdk.NewAttribute(types.AttributeKeyRequiredCapability, strings.TrimSpace(f))) - } - ctx.EventManager().EmitEvent(evt) - - return codeID, checksum, nil -} - -func (k Keeper) storeCodeInfo(ctx sdk.Context, codeID uint64, codeInfo types.CodeInfo) { - store := ctx.KVStore(k.storeKey) - // 0x01 | codeID (uint64) -> ContractInfo - store.Set(types.GetCodeKey(codeID), k.cdc.MustMarshal(&codeInfo)) -} - -func (k Keeper) importCode(ctx sdk.Context, codeID uint64, codeInfo types.CodeInfo, wasmCode []byte) error { - if ioutils.IsGzip(wasmCode) { - var err error - wasmCode, err = ioutils.Uncompress(wasmCode, uint64(types.MaxWasmSize)) - if err != nil { - return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - } - newCodeHash, err := k.wasmVM.Create(wasmCode) - if err != nil { - return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - if !bytes.Equal(codeInfo.CodeHash, newCodeHash) { - return errorsmod.Wrap(types.ErrInvalid, "code hashes not same") - } - - store := ctx.KVStore(k.storeKey) - key := types.GetCodeKey(codeID) - if store.Has(key) { - return errorsmod.Wrapf(types.ErrDuplicate, "duplicate code: %d", codeID) - } - // 0x01 | codeID (uint64) -> ContractInfo - store.Set(key, k.cdc.MustMarshal(&codeInfo)) - return nil -} - -func (k Keeper) instantiate( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - addressGenerator AddressGenerator, - authPolicy AuthorizationPolicy, -) (sdk.AccAddress, []byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "instantiate") - - if creator == nil { - return nil, nil, types.ErrEmpty.Wrap("creator") - } - instanceCosts := k.gasRegister.NewContractInstanceCosts(k.IsPinnedCode(ctx, codeID), len(initMsg)) - ctx.GasMeter().ConsumeGas(instanceCosts, "Loading CosmWasm module: instantiate") - - codeInfo := k.GetCodeInfo(ctx, codeID) - if codeInfo == nil { - return nil, nil, errorsmod.Wrap(types.ErrNotFound, "code") - } - if !authPolicy.CanInstantiateContract(codeInfo.InstantiateConfig, creator) { - return nil, nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate") - } - - contractAddress := addressGenerator(ctx, codeID, codeInfo.CodeHash) - if k.HasContractInfo(ctx, contractAddress) { - return nil, nil, types.ErrDuplicate.Wrap("instance with this code id, sender and label exists: try a different label") - } - - // check account - // every cosmos module can define custom account types when needed. The cosmos-sdk comes with extension points - // to support this and a set of base and vesting account types that we integrated in our default lists. - // But not all account types of other modules are known or may make sense for contracts, therefore we kept this - // decision logic also very flexible and extendable. We provide new options to overwrite the default settings via WithAcceptedAccountTypesOnContractInstantiation and - // WithPruneAccountTypesOnContractInstantiation as constructor arguments - existingAcct := k.accountKeeper.GetAccount(ctx, contractAddress) - if existingAcct != nil { - if existingAcct.GetSequence() != 0 || existingAcct.GetPubKey() != nil { - return nil, nil, types.ErrAccountExists.Wrap("address is claimed by external account") - } - if _, accept := k.acceptedAccountTypes[reflect.TypeOf(existingAcct)]; accept { - // keep account and balance as it is - k.Logger(ctx).Info("instantiate contract with existing account", "address", contractAddress.String()) - } else { - // consider an account in the wasmd namespace spam and overwrite it. - k.Logger(ctx).Info("pruning existing account for contract instantiation", "address", contractAddress.String()) - contractAccount := k.accountKeeper.NewAccountWithAddress(ctx, contractAddress) - k.accountKeeper.SetAccount(ctx, contractAccount) - // also handle balance to not open cases where these accounts are abused and become liquid - switch handled, err := k.accountPruner.CleanupExistingAccount(ctx, existingAcct); { - case err != nil: - return nil, nil, errorsmod.Wrap(err, "prune balance") - case !handled: - return nil, nil, types.ErrAccountExists.Wrap("address is claimed by external account") - } - } - } else { - // create an empty account (so we don't have issues later) - contractAccount := k.accountKeeper.NewAccountWithAddress(ctx, contractAddress) - k.accountKeeper.SetAccount(ctx, contractAccount) - } - // deposit initial contract funds - if !deposit.IsZero() { - if err := k.bank.TransferCoins(ctx, creator, contractAddress, deposit); err != nil { - return nil, nil, err - } - } - - // prepare params for contract instantiate call - env := types.NewEnv(ctx, contractAddress) - info := types.NewInfo(creator, deposit) - - // create prefixed data store - // 0x03 | BuildContractAddressClassic (sdk.AccAddress) - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - vmStore := types.NewStoreAdapter(prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey)) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - - // instantiate wasm contract - gas := k.runtimeGasForContract(ctx) - res, gasUsed, err := k.wasmVM.Instantiate(codeInfo.CodeHash, env, info, initMsg, vmStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if err != nil { - return nil, nil, errorsmod.Wrap(types.ErrInstantiateFailed, err.Error()) - } - - // persist instance first - createdAt := types.NewAbsoluteTxPosition(ctx) - contractInfo := types.NewContractInfo(codeID, creator, admin, label, createdAt) - - // check for IBC flag - report, err := k.wasmVM.AnalyzeCode(codeInfo.CodeHash) - if err != nil { - return nil, nil, errorsmod.Wrap(types.ErrInstantiateFailed, err.Error()) - } - if report.HasIBCEntryPoints { - // register IBC port - ibcPort, err := k.ensureIbcPort(ctx, contractAddress) - if err != nil { - return nil, nil, err - } - contractInfo.IBCPortID = ibcPort - } - - // store contract before dispatch so that contract could be called back - historyEntry := contractInfo.InitialHistory(initMsg) - k.addToContractCodeSecondaryIndex(ctx, contractAddress, historyEntry) - k.addToContractCreatorSecondaryIndex(ctx, creator, historyEntry.Updated, contractAddress) - k.appendToContractHistory(ctx, contractAddress, historyEntry) - k.storeContractInfo(ctx, contractAddress, &contractInfo) - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeInstantiate, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, nil, errorsmod.Wrap(err, "dispatch") - } - - return contractAddress, data, nil -} - -// Execute executes the contract instance -func (k Keeper) execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "execute") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress) - if err != nil { - return nil, err - } - - executeCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, contractInfo.CodeID), len(msg)) - ctx.GasMeter().ConsumeGas(executeCosts, "Loading CosmWasm module: execute") - - // add more funds - if !coins.IsZero() { - if err := k.bank.TransferCoins(ctx, caller, contractAddress, coins); err != nil { - return nil, err - } - } - - env := types.NewEnv(ctx, contractAddress) - info := types.NewInfo(caller, coins) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.Execute(codeInfo.CodeHash, env, info, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return nil, errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeExecute, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, errorsmod.Wrap(err, "dispatch") - } - - return data, nil -} - -func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newCodeID uint64, msg []byte, authZ AuthorizationPolicy) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "migrate") - migrateSetupCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, newCodeID), len(msg)) - ctx.GasMeter().ConsumeGas(migrateSetupCosts, "Loading CosmWasm module: migrate") - - contractInfo := k.GetContractInfo(ctx, contractAddress) - if contractInfo == nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract") - } - if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) { - return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not migrate") - } - - newCodeInfo := k.GetCodeInfo(ctx, newCodeID) - if newCodeInfo == nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown code") - } - - if !authZ.CanInstantiateContract(newCodeInfo.InstantiateConfig, caller) { - return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "to use new code") - } - - // check for IBC flag - switch report, err := k.wasmVM.AnalyzeCode(newCodeInfo.CodeHash); { - case err != nil: - return nil, errorsmod.Wrap(types.ErrMigrationFailed, err.Error()) - case !report.HasIBCEntryPoints && contractInfo.IBCPortID != "": - // prevent update to non ibc contract - return nil, errorsmod.Wrap(types.ErrMigrationFailed, "requires ibc callbacks") - case report.HasIBCEntryPoints && contractInfo.IBCPortID == "": - // add ibc port - ibcPort, err := k.ensureIbcPort(ctx, contractAddress) - if err != nil { - return nil, err - } - contractInfo.IBCPortID = ibcPort - } - - env := types.NewEnv(ctx, contractAddress) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - vmStore := types.NewStoreAdapter(prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey)) - gas := k.runtimeGasForContract(ctx) - res, gasUsed, err := k.wasmVM.Migrate(newCodeInfo.CodeHash, env, msg, vmStore, cosmwasmAPI, &querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if err != nil { - return nil, errorsmod.Wrap(types.ErrMigrationFailed, err.Error()) - } - // delete old secondary index entry - k.removeFromContractCodeSecondaryIndex(ctx, contractAddress, k.getLastContractHistoryEntry(ctx, contractAddress)) - // persist migration updates - historyEntry := contractInfo.AddMigration(ctx, newCodeID, msg) - k.appendToContractHistory(ctx, contractAddress, historyEntry) - k.addToContractCodeSecondaryIndex(ctx, contractAddress, historyEntry) - k.storeContractInfo(ctx, contractAddress, contractInfo) - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeMigrate, - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(newCodeID, 10)), - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, errorsmod.Wrap(err, "dispatch") - } - - return data, nil -} - -// Sudo allows priviledged access to a contract. This can never be called by an external tx, but only by -// another native Go module directly, or on-chain governance (if sudo proposals are enabled). Thus, the keeper doesn't -// place any access controls on it, that is the responsibility or the app developer (who passes the wasm.Keeper in app.go) -func (k Keeper) Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "sudo") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress) - if err != nil { - return nil, err - } - - sudoSetupCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, contractInfo.CodeID), len(msg)) - ctx.GasMeter().ConsumeGas(sudoSetupCosts, "Loading CosmWasm module: sudo") - - env := types.NewEnv(ctx, contractAddress) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.Sudo(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return nil, errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeSudo, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, errorsmod.Wrap(err, "dispatch") - } - - return data, nil -} - -// reply is only called from keeper internal functions (dispatchSubmessages) after processing the submessage -func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddress) - if err != nil { - return nil, err - } - - // always consider this pinned - replyCosts := k.gasRegister.ReplyCosts(true, reply) - ctx.GasMeter().ConsumeGas(replyCosts, "Loading CosmWasm module: reply") - - env := types.NewEnv(ctx, contractAddress) - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddress) - gas := k.runtimeGasForContract(ctx) - - res, gasUsed, execErr := k.wasmVM.Reply(codeInfo.CodeHash, env, reply, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return nil, errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeReply, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - )) - - data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) - if err != nil { - return nil, errorsmod.Wrap(err, "dispatch") - } - - return data, nil -} - -// addToContractCodeSecondaryIndex adds element to the index for contracts-by-codeid queries -func (k Keeper) addToContractCodeSecondaryIndex(ctx sdk.Context, contractAddress sdk.AccAddress, entry types.ContractCodeHistoryEntry) { - store := ctx.KVStore(k.storeKey) - store.Set(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry), []byte{}) -} - -// removeFromContractCodeSecondaryIndex removes element to the index for contracts-by-codeid queries -func (k Keeper) removeFromContractCodeSecondaryIndex(ctx sdk.Context, contractAddress sdk.AccAddress, entry types.ContractCodeHistoryEntry) { - ctx.KVStore(k.storeKey).Delete(types.GetContractByCreatedSecondaryIndexKey(contractAddress, entry)) -} - -// addToContractCreatorSecondaryIndex adds element to the index for contracts-by-creator queries -func (k Keeper) addToContractCreatorSecondaryIndex(ctx sdk.Context, creatorAddress sdk.AccAddress, position *types.AbsoluteTxPosition, contractAddress sdk.AccAddress) { - store := ctx.KVStore(k.storeKey) - store.Set(types.GetContractByCreatorSecondaryIndexKey(creatorAddress, position.Bytes(), contractAddress), []byte{}) -} - -// IterateContractsByCreator iterates over all contracts with given creator address in order of creation time asc. -func (k Keeper) IterateContractsByCreator(ctx sdk.Context, creator sdk.AccAddress, cb func(address sdk.AccAddress) bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetContractsByCreatorPrefix(creator)) - for iter := prefixStore.Iterator(nil, nil); iter.Valid(); iter.Next() { - key := iter.Key() - if cb(key[types.AbsoluteTxPositionLen:]) { - return - } - } -} - -// IterateContractsByCode iterates over all contracts with given codeID ASC on code update time. -func (k Keeper) IterateContractsByCode(ctx sdk.Context, codeID uint64, cb func(address sdk.AccAddress) bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetContractByCodeIDSecondaryIndexPrefix(codeID)) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - key := iter.Key() - if cb(key[types.AbsoluteTxPositionLen:]) { - return - } - } -} - -func (k Keeper) setContractAdmin(ctx sdk.Context, contractAddress, caller, newAdmin sdk.AccAddress, authZ AuthorizationPolicy) error { - contractInfo := k.GetContractInfo(ctx, contractAddress) - if contractInfo == nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract") - } - if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) { - return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify contract") - } - newAdminStr := newAdmin.String() - contractInfo.Admin = newAdminStr - k.storeContractInfo(ctx, contractAddress, contractInfo) - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeUpdateContractAdmin, - sdk.NewAttribute(types.AttributeKeyContractAddr, contractAddress.String()), - sdk.NewAttribute(types.AttributeKeyNewAdmin, newAdminStr), - )) - - return nil -} - -func (k Keeper) appendToContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress, newEntries ...types.ContractCodeHistoryEntry) { - store := ctx.KVStore(k.storeKey) - // find last element position - var pos uint64 - prefixStore := prefix.NewStore(store, types.GetContractCodeHistoryElementPrefix(contractAddr)) - iter := prefixStore.ReverseIterator(nil, nil) - defer iter.Close() - - if iter.Valid() { - pos = sdk.BigEndianToUint64(iter.Key()) - } - // then store with incrementing position - for _, e := range newEntries { - pos++ - key := types.GetContractCodeHistoryElementKey(contractAddr, pos) - store.Set(key, k.cdc.MustMarshal(&e)) //nolint:gosec - } -} - -func (k Keeper) GetContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress) []types.ContractCodeHistoryEntry { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetContractCodeHistoryElementPrefix(contractAddr)) - r := make([]types.ContractCodeHistoryEntry, 0) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var e types.ContractCodeHistoryEntry - k.cdc.MustUnmarshal(iter.Value(), &e) - r = append(r, e) - } - return r -} - -// getLastContractHistoryEntry returns the last element from history. To be used internally only as it panics when none exists -func (k Keeper) getLastContractHistoryEntry(ctx sdk.Context, contractAddr sdk.AccAddress) types.ContractCodeHistoryEntry { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.GetContractCodeHistoryElementPrefix(contractAddr)) - iter := prefixStore.ReverseIterator(nil, nil) - defer iter.Close() - - var r types.ContractCodeHistoryEntry - if !iter.Valid() { - // all contracts have a history - panic(fmt.Sprintf("no history for %s", contractAddr.String())) - } - k.cdc.MustUnmarshal(iter.Value(), &r) - return r -} - -// QuerySmart queries the smart contract itself. -func (k Keeper) QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-smart") - - // checks and increase query stack size - ctx, err := checkAndIncreaseQueryStackSize(ctx, k.maxQueryStackSize) - if err != nil { - return nil, err - } - - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return nil, err - } - - smartQuerySetupCosts := k.gasRegister.InstantiateContractCosts(k.IsPinnedCode(ctx, contractInfo.CodeID), len(req)) - ctx.GasMeter().ConsumeGas(smartQuerySetupCosts, "Loading CosmWasm module: query") - - // prepare querier - querier := k.newQueryHandler(ctx, contractAddr) - - env := types.NewEnv(ctx, contractAddr) - queryResult, gasUsed, qErr := k.wasmVM.Query(codeInfo.CodeHash, env, req, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), k.runtimeGasForContract(ctx), costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if qErr != nil { - return nil, errorsmod.Wrap(types.ErrQueryFailed, qErr.Error()) - } - return queryResult, nil -} - -func checkAndIncreaseQueryStackSize(ctx sdk.Context, maxQueryStackSize uint32) (sdk.Context, error) { - var queryStackSize uint32 - - // read current value - if size := ctx.Context().Value(contextKeyQueryStackSize); size != nil { - queryStackSize = size.(uint32) - } else { - queryStackSize = 0 - } - - // increase - queryStackSize++ - - // did we go too far? - if queryStackSize > maxQueryStackSize { - return ctx, types.ErrExceedMaxQueryStackSize - } - - // set updated stack size - ctx = ctx.WithContext(context.WithValue(ctx.Context(), contextKeyQueryStackSize, queryStackSize)) - - return ctx, nil -} - -// QueryRaw returns the contract's state for give key. Returns `nil` when key is `nil`. -func (k Keeper) QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "query-raw") - if key == nil { - return nil - } - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) - return prefixStore.Get(key) -} - -// internal helper function -func (k Keeper) contractInstance(ctx sdk.Context, contractAddress sdk.AccAddress) (types.ContractInfo, types.CodeInfo, wasmvm.KVStore, error) { - store := ctx.KVStore(k.storeKey) - - contractBz := store.Get(types.GetContractAddressKey(contractAddress)) - if contractBz == nil { - return types.ContractInfo{}, types.CodeInfo{}, nil, errorsmod.Wrap(types.ErrNotFound, "contract") - } - var contractInfo types.ContractInfo - k.cdc.MustUnmarshal(contractBz, &contractInfo) - - codeInfoBz := store.Get(types.GetCodeKey(contractInfo.CodeID)) - if codeInfoBz == nil { - return contractInfo, types.CodeInfo{}, nil, errorsmod.Wrap(types.ErrNotFound, "code info") - } - var codeInfo types.CodeInfo - k.cdc.MustUnmarshal(codeInfoBz, &codeInfo) - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) - return contractInfo, codeInfo, types.NewStoreAdapter(prefixStore), nil -} - -func (k Keeper) GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - store := ctx.KVStore(k.storeKey) - var contract types.ContractInfo - contractBz := store.Get(types.GetContractAddressKey(contractAddress)) - if contractBz == nil { - return nil - } - k.cdc.MustUnmarshal(contractBz, &contract) - return &contract -} - -func (k Keeper) HasContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.GetContractAddressKey(contractAddress)) -} - -// storeContractInfo persists the ContractInfo. No secondary index updated here. -func (k Keeper) storeContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress, contract *types.ContractInfo) { - store := ctx.KVStore(k.storeKey) - store.Set(types.GetContractAddressKey(contractAddress), k.cdc.MustMarshal(contract)) -} - -func (k Keeper) IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, types.ContractInfo) bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.ContractKeyPrefix) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var contract types.ContractInfo - k.cdc.MustUnmarshal(iter.Value(), &contract) - // cb returns true to stop early - if cb(iter.Key(), contract) { - break - } - } -} - -// IterateContractState iterates through all elements of the key value store for the given contract address and passes -// them to the provided callback function. The callback method can return true to abort early. -func (k Keeper) IterateContractState(ctx sdk.Context, contractAddress sdk.AccAddress, cb func(key, value []byte) bool) { - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - if cb(iter.Key(), iter.Value()) { - break - } - } -} - -func (k Keeper) importContractState(ctx sdk.Context, contractAddress sdk.AccAddress, models []types.Model) error { - prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) - for _, model := range models { - if model.Value == nil { - model.Value = []byte{} - } - if prefixStore.Has(model.Key) { - return errorsmod.Wrapf(types.ErrDuplicate, "duplicate key: %x", model.Key) - } - prefixStore.Set(model.Key, model.Value) - } - return nil -} - -func (k Keeper) GetCodeInfo(ctx sdk.Context, codeID uint64) *types.CodeInfo { - store := ctx.KVStore(k.storeKey) - var codeInfo types.CodeInfo - codeInfoBz := store.Get(types.GetCodeKey(codeID)) - if codeInfoBz == nil { - return nil - } - k.cdc.MustUnmarshal(codeInfoBz, &codeInfo) - return &codeInfo -} - -func (k Keeper) containsCodeInfo(ctx sdk.Context, codeID uint64) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.GetCodeKey(codeID)) -} - -func (k Keeper) IterateCodeInfos(ctx sdk.Context, cb func(uint64, types.CodeInfo) bool) { - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.CodeKeyPrefix) - iter := prefixStore.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - var c types.CodeInfo - k.cdc.MustUnmarshal(iter.Value(), &c) - // cb returns true to stop early - if cb(binary.BigEndian.Uint64(iter.Key()), c) { - return - } - } -} - -func (k Keeper) GetByteCode(ctx sdk.Context, codeID uint64) ([]byte, error) { - store := ctx.KVStore(k.storeKey) - var codeInfo types.CodeInfo - codeInfoBz := store.Get(types.GetCodeKey(codeID)) - if codeInfoBz == nil { - return nil, nil - } - k.cdc.MustUnmarshal(codeInfoBz, &codeInfo) - return k.wasmVM.GetCode(codeInfo.CodeHash) -} - -// PinCode pins the wasm contract in wasmvm cache -func (k Keeper) pinCode(ctx sdk.Context, codeID uint64) error { - codeInfo := k.GetCodeInfo(ctx, codeID) - if codeInfo == nil { - return errorsmod.Wrap(types.ErrNotFound, "code info") - } - - if err := k.wasmVM.Pin(codeInfo.CodeHash); err != nil { - return errorsmod.Wrap(types.ErrPinContractFailed, err.Error()) - } - store := ctx.KVStore(k.storeKey) - // store 1 byte to not run into `nil` debugging issues - store.Set(types.GetPinnedCodeIndexPrefix(codeID), []byte{1}) - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypePinCode, - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), - )) - return nil -} - -// UnpinCode removes the wasm contract from wasmvm cache -func (k Keeper) unpinCode(ctx sdk.Context, codeID uint64) error { - codeInfo := k.GetCodeInfo(ctx, codeID) - if codeInfo == nil { - return errorsmod.Wrap(types.ErrNotFound, "code info") - } - if err := k.wasmVM.Unpin(codeInfo.CodeHash); err != nil { - return errorsmod.Wrap(types.ErrUnpinContractFailed, err.Error()) - } - - store := ctx.KVStore(k.storeKey) - store.Delete(types.GetPinnedCodeIndexPrefix(codeID)) - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeUnpinCode, - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), - )) - return nil -} - -// IsPinnedCode returns true when codeID is pinned in wasmvm cache -func (k Keeper) IsPinnedCode(ctx sdk.Context, codeID uint64) bool { - store := ctx.KVStore(k.storeKey) - return store.Has(types.GetPinnedCodeIndexPrefix(codeID)) -} - -// InitializePinnedCodes updates wasmvm to pin to cache all contracts marked as pinned -func (k Keeper) InitializePinnedCodes(ctx sdk.Context) error { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.PinnedCodeIndexPrefix) - iter := store.Iterator(nil, nil) - defer iter.Close() - - for ; iter.Valid(); iter.Next() { - codeInfo := k.GetCodeInfo(ctx, types.ParsePinnedCodeIndex(iter.Key())) - if codeInfo == nil { - return errorsmod.Wrap(types.ErrNotFound, "code info") - } - if err := k.wasmVM.Pin(codeInfo.CodeHash); err != nil { - return errorsmod.Wrap(types.ErrPinContractFailed, err.Error()) - } - } - return nil -} - -// setContractInfoExtension updates the extension point data that is stored with the contract info -func (k Keeper) setContractInfoExtension(ctx sdk.Context, contractAddr sdk.AccAddress, ext types.ContractInfoExtension) error { - info := k.GetContractInfo(ctx, contractAddr) - if info == nil { - return errorsmod.Wrap(types.ErrNotFound, "contract info") - } - if err := info.SetExtension(ext); err != nil { - return err - } - k.storeContractInfo(ctx, contractAddr, info) - return nil -} - -// setAccessConfig updates the access config of a code id. -func (k Keeper) setAccessConfig(ctx sdk.Context, codeID uint64, caller sdk.AccAddress, newConfig types.AccessConfig, authz AuthorizationPolicy) error { - info := k.GetCodeInfo(ctx, codeID) - if info == nil { - return errorsmod.Wrap(types.ErrNotFound, "code info") - } - isSubset := newConfig.Permission.IsSubset(k.getInstantiateAccessConfig(ctx)) - if !authz.CanModifyCodeAccessConfig(sdk.MustAccAddressFromBech32(info.Creator), caller, isSubset) { - return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify code access config") - } - - info.InstantiateConfig = newConfig - k.storeCodeInfo(ctx, codeID, *info) - evt := sdk.NewEvent( - types.EventTypeUpdateCodeAccessConfig, - sdk.NewAttribute(types.AttributeKeyCodePermission, newConfig.Permission.String()), - sdk.NewAttribute(types.AttributeKeyCodeID, strconv.FormatUint(codeID, 10)), - ) - if addrs := newConfig.AllAuthorizedAddresses(); len(addrs) != 0 { - attr := sdk.NewAttribute(types.AttributeKeyAuthorizedAddresses, strings.Join(addrs, ",")) - evt.Attributes = append(evt.Attributes, attr.ToKVPair()) - } - ctx.EventManager().EmitEvent(evt) - return nil -} - -// handleContractResponse processes the contract response data by emitting events and sending sub-/messages. -func (k *Keeper) handleContractResponse( - ctx sdk.Context, - contractAddr sdk.AccAddress, - ibcPort string, - msgs []wasmvmtypes.SubMsg, - attrs []wasmvmtypes.EventAttribute, - data []byte, - evts wasmvmtypes.Events, -) ([]byte, error) { - attributeGasCost := k.gasRegister.EventCosts(attrs, evts) - ctx.GasMeter().ConsumeGas(attributeGasCost, "Custom contract event attributes") - // emit all events from this contract itself - if len(attrs) != 0 { - wasmEvents, err := newWasmModuleEvent(attrs, contractAddr) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvents(wasmEvents) - } - if len(evts) > 0 { - customEvents, err := newCustomEvents(evts, contractAddr) - if err != nil { - return nil, err - } - ctx.EventManager().EmitEvents(customEvents) - } - return k.wasmVMResponseHandler.Handle(ctx, contractAddr, ibcPort, msgs, data) -} - -func (k Keeper) runtimeGasForContract(ctx sdk.Context) uint64 { - meter := ctx.GasMeter() - if meter.IsOutOfGas() { - return 0 - } - if meter.Limit() == math.MaxUint64 { // infinite gas meter and not out of gas - return math.MaxUint64 - } - return k.gasRegister.ToWasmVMGas(meter.Limit() - meter.GasConsumedToLimit()) -} - -func (k Keeper) consumeRuntimeGas(ctx sdk.Context, gas uint64) { - consumed := k.gasRegister.FromWasmVMGas(gas) - ctx.GasMeter().ConsumeGas(consumed, "wasm contract") - // throw OutOfGas error if we ran out (got exactly to zero due to better limit enforcing) - if ctx.GasMeter().IsOutOfGas() { - panic(sdk.ErrorOutOfGas{Descriptor: "Wasmer function execution"}) - } -} - -func (k Keeper) autoIncrementID(ctx sdk.Context, lastIDKey []byte) uint64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get(lastIDKey) - id := uint64(1) - if bz != nil { - id = binary.BigEndian.Uint64(bz) - } - bz = sdk.Uint64ToBigEndian(id + 1) - store.Set(lastIDKey, bz) - return id -} - -// PeekAutoIncrementID reads the current value without incrementing it. -func (k Keeper) PeekAutoIncrementID(ctx sdk.Context, lastIDKey []byte) uint64 { - store := ctx.KVStore(k.storeKey) - bz := store.Get(lastIDKey) - id := uint64(1) - if bz != nil { - id = binary.BigEndian.Uint64(bz) - } - return id -} - -func (k Keeper) importAutoIncrementID(ctx sdk.Context, lastIDKey []byte, val uint64) error { - store := ctx.KVStore(k.storeKey) - if store.Has(lastIDKey) { - return errorsmod.Wrapf(types.ErrDuplicate, "autoincrement id: %s", string(lastIDKey)) - } - bz := sdk.Uint64ToBigEndian(val) - store.Set(lastIDKey, bz) - return nil -} - -func (k Keeper) importContract(ctx sdk.Context, contractAddr sdk.AccAddress, c *types.ContractInfo, state []types.Model, entries []types.ContractCodeHistoryEntry) error { - if !k.containsCodeInfo(ctx, c.CodeID) { - return errorsmod.Wrapf(types.ErrNotFound, "code id: %d", c.CodeID) - } - if k.HasContractInfo(ctx, contractAddr) { - return errorsmod.Wrapf(types.ErrDuplicate, "contract: %s", contractAddr) - } - - creatorAddress, err := sdk.AccAddressFromBech32(c.Creator) - if err != nil { - return err - } - - k.appendToContractHistory(ctx, contractAddr, entries...) - k.storeContractInfo(ctx, contractAddr, c) - k.addToContractCodeSecondaryIndex(ctx, contractAddr, entries[len(entries)-1]) - k.addToContractCreatorSecondaryIndex(ctx, creatorAddress, entries[0].Updated, contractAddr) - return k.importContractState(ctx, contractAddr, state) -} - -func (k Keeper) newQueryHandler(ctx sdk.Context, contractAddress sdk.AccAddress) QueryHandler { - return NewQueryHandler(ctx, k.wasmVMQueryHandler, contractAddress, k.gasRegister) -} - -// MultipliedGasMeter wraps the GasMeter from context and multiplies all reads by out defined multiplier -type MultipliedGasMeter struct { - originalMeter sdk.GasMeter - GasRegister GasRegister -} - -func NewMultipliedGasMeter(originalMeter sdk.GasMeter, gr GasRegister) MultipliedGasMeter { - return MultipliedGasMeter{originalMeter: originalMeter, GasRegister: gr} -} - -var _ wasmvm.GasMeter = MultipliedGasMeter{} - -func (m MultipliedGasMeter) GasConsumed() sdk.Gas { - return m.GasRegister.ToWasmVMGas(m.originalMeter.GasConsumed()) -} - -func (k Keeper) gasMeter(ctx sdk.Context) MultipliedGasMeter { - return NewMultipliedGasMeter(ctx.GasMeter(), k.gasRegister) -} - -// Logger returns a module-specific logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return moduleLogger(ctx) -} - -func moduleLogger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -// Querier creates a new grpc querier instance -func Querier(k *Keeper) *GrpcQuerier { - return NewGrpcQuerier(k.cdc, k.storeKey, k, k.queryGasLimit) -} - -// QueryGasLimit returns the gas limit for smart queries. -func (k Keeper) QueryGasLimit() sdk.Gas { - return k.queryGasLimit -} - -// BankCoinTransferrer replicates the cosmos-sdk behaviour as in -// https://github.com/cosmos/cosmos-sdk/blob/v0.41.4/x/bank/keeper/msg_server.go#L26 -type BankCoinTransferrer struct { - keeper types.BankKeeper -} - -func NewBankCoinTransferrer(keeper types.BankKeeper) BankCoinTransferrer { - return BankCoinTransferrer{ - keeper: keeper, - } -} - -// TransferCoins transfers coins from source to destination account when coin send was enabled for them and the recipient -// is not in the blocked address list. -func (c BankCoinTransferrer) TransferCoins(parentCtx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amount sdk.Coins) error { - em := sdk.NewEventManager() - ctx := parentCtx.WithEventManager(em) - if err := c.keeper.IsSendEnabledCoins(ctx, amount...); err != nil { - return err - } - if c.keeper.BlockedAddr(toAddr) { - return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", toAddr.String()) - } - - sdkerr := c.keeper.SendCoins(ctx, fromAddr, toAddr, amount) - if sdkerr != nil { - return sdkerr - } - for _, e := range em.Events() { - if e.Type == sdk.EventTypeMessage { // skip messages as we talk to the keeper directly - continue - } - parentCtx.EventManager().EmitEvent(e) - } - return nil -} - -var _ AccountPruner = VestingCoinBurner{} - -// VestingCoinBurner default implementation for AccountPruner to burn the coins -type VestingCoinBurner struct { - bank types.BankKeeper -} - -// NewVestingCoinBurner constructor -func NewVestingCoinBurner(bank types.BankKeeper) VestingCoinBurner { - if bank == nil { - panic("bank keeper must not be nil") - } - return VestingCoinBurner{bank: bank} -} - -// CleanupExistingAccount accepts only vesting account types to burns all their original vesting coin balances. -// Other account types will be rejected and returned as unhandled. -func (b VestingCoinBurner) CleanupExistingAccount(ctx sdk.Context, existingAcc authtypes.AccountI) (handled bool, err error) { - v, ok := existingAcc.(vestingexported.VestingAccount) - if !ok { - return false, nil - } - - ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) - coinsToBurn := sdk.NewCoins() - for _, orig := range v.GetOriginalVesting() { // focus on the coin denoms that were setup originally; getAllBalances has some issues - coinsToBurn = append(coinsToBurn, b.bank.GetBalance(ctx, existingAcc.GetAddress(), orig.Denom)) - } - if err := b.bank.SendCoinsFromAccountToModule(ctx, existingAcc.GetAddress(), types.ModuleName, coinsToBurn); err != nil { - return false, errorsmod.Wrap(err, "prune account balance") - } - if err := b.bank.BurnCoins(ctx, types.ModuleName, coinsToBurn); err != nil { - return false, errorsmod.Wrap(err, "burn account balance") - } - return true, nil -} - -type msgDispatcher interface { - DispatchSubmessages(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) -} - -// DefaultWasmVMContractResponseHandler default implementation that first dispatches submessage then normal messages. -// The Submessage execution may include an success/failure response handling by the contract that can overwrite the -// original -type DefaultWasmVMContractResponseHandler struct { - md msgDispatcher -} - -func NewDefaultWasmVMContractResponseHandler(md msgDispatcher) *DefaultWasmVMContractResponseHandler { - return &DefaultWasmVMContractResponseHandler{md: md} -} - -// Handle processes the data returned by a contract invocation. -func (h DefaultWasmVMContractResponseHandler) Handle(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, messages []wasmvmtypes.SubMsg, origRspData []byte) ([]byte, error) { - result := origRspData - switch rsp, err := h.md.DispatchSubmessages(ctx, contractAddr, ibcPort, messages); { - case err != nil: - return nil, errorsmod.Wrap(err, "submessages") - case rsp != nil: - result = rsp - } - return result, nil -} diff --git a/x/wasm/keeper/keeper_cgo.go b/x/wasm/keeper/keeper_cgo.go deleted file mode 100644 index 64c94f3..0000000 --- a/x/wasm/keeper/keeper_cgo.go +++ /dev/null @@ -1,65 +0,0 @@ -//go:build cgo - -package keeper - -import ( - "path/filepath" - - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - wasmvm "github.com/CosmWasm/wasmvm" - "github.com/cosmos/cosmos-sdk/codec" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// NewKeeper creates a new contract Keeper instance -// If customEncoders is non-nil, we can use this to override some of the message handler, especially custom -func NewKeeper( - cdc codec.Codec, - storeKey storetypes.StoreKey, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - stakingKeeper types.StakingKeeper, - distrKeeper types.DistributionKeeper, - channelKeeper types.ChannelKeeper, - portKeeper types.PortKeeper, - capabilityKeeper types.CapabilityKeeper, - portSource types.ICS20TransferPortSource, - router MessageRouter, - _ GRPCQueryRouter, - homeDir string, - wasmConfig types.WasmConfig, - availableCapabilities string, - authority string, - opts ...Option, -) Keeper { - wasmer, err := wasmvm.NewVM(filepath.Join(homeDir, "wasm"), availableCapabilities, contractMemoryLimit, wasmConfig.ContractDebugMode, wasmConfig.MemoryCacheSize) - if err != nil { - panic(err) - } - - keeper := &Keeper{ - storeKey: storeKey, - cdc: cdc, - wasmVM: wasmer, - accountKeeper: accountKeeper, - bank: NewBankCoinTransferrer(bankKeeper), - accountPruner: NewVestingCoinBurner(bankKeeper), - portKeeper: portKeeper, - capabilityKeeper: capabilityKeeper, - messenger: NewDefaultMessageHandler(router, channelKeeper, capabilityKeeper, bankKeeper, cdc, portSource), - queryGasLimit: wasmConfig.SmartQueryGasLimit, - gasRegister: NewDefaultWasmGasRegister(), - maxQueryStackSize: types.DefaultMaxQueryStackSize, - acceptedAccountTypes: defaultAcceptedAccountTypes, - authority: authority, - } - keeper.wasmVMQueryHandler = DefaultQueryPlugins(bankKeeper, stakingKeeper, distrKeeper, channelKeeper, keeper) - for _, o := range opts { - o.apply(keeper) - } - // not updateable, yet - keeper.wasmVMResponseHandler = NewDefaultWasmVMContractResponseHandler(NewMessageDispatcher(keeper.messenger, keeper)) - return *keeper -} diff --git a/x/wasm/keeper/keeper_no_cgo.go b/x/wasm/keeper/keeper_no_cgo.go deleted file mode 100644 index 2c45dbc..0000000 --- a/x/wasm/keeper/keeper_no_cgo.go +++ /dev/null @@ -1,34 +0,0 @@ -//go:build !cgo - -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// NewKeeper creates a new contract Keeper instance -// If customEncoders is non-nil, we can use this to override some of the message handler, especially custom -func NewKeeper( - cdc codec.Codec, - storeKey storetypes.StoreKey, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - stakingKeeper types.StakingKeeper, - distrKeeper types.DistributionKeeper, - channelKeeper types.ChannelKeeper, - portKeeper types.PortKeeper, - capabilityKeeper types.CapabilityKeeper, - portSource types.ICS20TransferPortSource, - router MessageRouter, - _ GRPCQueryRouter, - homeDir string, - wasmConfig types.WasmConfig, - availableCapabilities string, - authority string, - opts ...Option, -) Keeper { - panic("not implemented, please build with cgo enabled") -} diff --git a/x/wasm/keeper/keeper_test.go b/x/wasm/keeper/keeper_test.go deleted file mode 100644 index 6d97ae6..0000000 --- a/x/wasm/keeper/keeper_test.go +++ /dev/null @@ -1,2418 +0,0 @@ -package keeper - -import ( - "bytes" - _ "embed" - "encoding/json" - "errors" - "fmt" - "os" - "strings" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - abci "github.com/cometbft/cometbft/abci/types" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/rand" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - stypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - fuzz "github.com/google/gofuzz" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -//go:embed testdata/hackatom.wasm -var hackatomWasm []byte - -const AvailableCapabilities = "iterator,staking,stargate,cosmwasm_1_1" - -func TestNewKeeper(t *testing.T) { - _, keepers := CreateTestInput(t, false, AvailableCapabilities) - require.NotNil(t, keepers.ContractKeeper) -} - -func TestCreateSuccess(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - em := sdk.NewEventManager() - contractID, _, err := keeper.Create(ctx.WithEventManager(em), creator, hackatomWasm, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - // and verify content - storedCode, err := keepers.WasmKeeper.GetByteCode(ctx, contractID) - require.NoError(t, err) - require.Equal(t, hackatomWasm, storedCode) - // and events emitted - codeHash := strings.ToLower("beb3de5e9b93b52e514c74ce87ccddb594b9bcd33b7f1af1bb6da63fc883917b") - exp := sdk.Events{sdk.NewEvent("store_code", sdk.NewAttribute("code_checksum", codeHash), sdk.NewAttribute("code_id", "1"))} - assert.Equal(t, exp, em.Events()) -} - -func TestCreateNilCreatorAddress(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - _, _, err := keepers.ContractKeeper.Create(ctx, nil, hackatomWasm, nil) - require.Error(t, err, "nil creator is not allowed") -} - -func TestCreateNilWasmCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - _, _, err := keepers.ContractKeeper.Create(ctx, creator, nil, nil) - require.Error(t, err, "nil WASM code is not allowed") -} - -func TestCreateInvalidWasmCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - _, _, err := keepers.ContractKeeper.Create(ctx, creator, []byte("potatoes"), nil) - require.Error(t, err, "potatoes are not valid WASM code") -} - -func TestCreateStoresInstantiatePermission(t *testing.T) { - var ( - deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - myAddr sdk.AccAddress = bytes.Repeat([]byte{1}, types.SDKAddrLen) - ) - - specs := map[string]struct { - srcPermission types.AccessType - expInstConf types.AccessConfig - }{ - "default": { - srcPermission: types.DefaultParams().InstantiateDefaultPermission, - expInstConf: types.AllowEverybody, - }, - "everybody": { - srcPermission: types.AccessTypeEverybody, - expInstConf: types.AllowEverybody, - }, - "nobody": { - srcPermission: types.AccessTypeNobody, - expInstConf: types.AllowNobody, - }, - "onlyAddress with matching address": { - srcPermission: types.AccessTypeOnlyAddress, - expInstConf: types.AccessConfig{Permission: types.AccessTypeOnlyAddress, Address: myAddr.String()}, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - err := keepers.WasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: spec.srcPermission, - }) - require.NoError(t, err) - fundAccounts(t, ctx, accKeeper, bankKeeper, myAddr, deposit) - - codeID, _, err := keeper.Create(ctx, myAddr, hackatomWasm, nil) - require.NoError(t, err) - - codeInfo := keepers.WasmKeeper.GetCodeInfo(ctx, codeID) - require.NotNil(t, codeInfo) - assert.True(t, spec.expInstConf.Equals(codeInfo.InstantiateConfig), "got %#v", codeInfo.InstantiateConfig) - }) - } -} - -func TestCreateWithParamPermissions(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - otherAddr := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - specs := map[string]struct { - policy AuthorizationPolicy - chainUpload types.AccessConfig - expError *errorsmod.Error - }{ - "default": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.DefaultUploadAccess, - }, - "everybody": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.AllowEverybody, - }, - "nobody": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.AllowNobody, - expError: sdkerrors.ErrUnauthorized, - }, - "onlyAddress with matching address": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.AccessTypeOnlyAddress.With(creator), - }, - "onlyAddress with non matching address": { - policy: DefaultAuthorizationPolicy{}, - chainUpload: types.AccessTypeOnlyAddress.With(otherAddr), - expError: sdkerrors.ErrUnauthorized, - }, - "gov: always allowed": { - policy: GovAuthorizationPolicy{}, - chainUpload: types.AllowNobody, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - params := types.DefaultParams() - params.CodeUploadAccess = spec.chainUpload - err := keepers.WasmKeeper.SetParams(ctx, params) - require.NoError(t, err) - keeper := NewPermissionedKeeper(keepers.WasmKeeper, spec.policy) - _, _, err = keeper.Create(ctx, creator, hackatomWasm, nil) - require.True(t, spec.expError.Is(err), err) - if spec.expError != nil { - return - } - }) - } -} - -// ensure that the user cannot set the code instantiate permission to something more permissive -// than the default -func TestEnforceValidPermissionsOnCreate(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - contractKeeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - other := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - onlyCreator := types.AccessTypeOnlyAddress.With(creator) - onlyOther := types.AccessTypeOnlyAddress.With(other) - - specs := map[string]struct { - defaultPermssion types.AccessType - requestedPermission *types.AccessConfig - // grantedPermission is set iff no error - grantedPermission types.AccessConfig - // expError is nil iff the request is allowed - expError *errorsmod.Error - }{ - "override everybody": { - defaultPermssion: types.AccessTypeEverybody, - requestedPermission: &onlyCreator, - grantedPermission: onlyCreator, - }, - "default to everybody": { - defaultPermssion: types.AccessTypeEverybody, - requestedPermission: nil, - grantedPermission: types.AccessConfig{Permission: types.AccessTypeEverybody}, - }, - "explicitly set everybody": { - defaultPermssion: types.AccessTypeEverybody, - requestedPermission: &types.AccessConfig{Permission: types.AccessTypeEverybody}, - grantedPermission: types.AccessConfig{Permission: types.AccessTypeEverybody}, - }, - "cannot override nobody": { - defaultPermssion: types.AccessTypeNobody, - requestedPermission: &onlyCreator, - expError: sdkerrors.ErrUnauthorized, - }, - "default to nobody": { - defaultPermssion: types.AccessTypeNobody, - requestedPermission: nil, - grantedPermission: types.AccessConfig{Permission: types.AccessTypeNobody}, - }, - "only defaults to code creator": { - defaultPermssion: types.AccessTypeOnlyAddress, - requestedPermission: nil, - grantedPermission: onlyCreator, - }, - "can explicitly set to code creator": { - defaultPermssion: types.AccessTypeOnlyAddress, - requestedPermission: &onlyCreator, - grantedPermission: onlyCreator, - }, - "cannot override which address in only": { - defaultPermssion: types.AccessTypeOnlyAddress, - requestedPermission: &onlyOther, - expError: sdkerrors.ErrUnauthorized, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - params := types.DefaultParams() - params.InstantiateDefaultPermission = spec.defaultPermssion - err := keeper.SetParams(ctx, params) - require.NoError(t, err) - codeID, _, err := contractKeeper.Create(ctx, creator, hackatomWasm, spec.requestedPermission) - require.True(t, spec.expError.Is(err), err) - if spec.expError == nil { - codeInfo := keeper.GetCodeInfo(ctx, codeID) - require.Equal(t, codeInfo.InstantiateConfig, spec.grantedPermission) - } - }) - } -} - -func TestCreateDuplicate(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // create one copy - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - - // create second copy - duplicateID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - require.Equal(t, uint64(2), duplicateID) - - // and verify both content is proper - storedCode, err := keepers.WasmKeeper.GetByteCode(ctx, contractID) - require.NoError(t, err) - require.Equal(t, hackatomWasm, storedCode) - storedCode, err = keepers.WasmKeeper.GetByteCode(ctx, duplicateID) - require.NoError(t, err) - require.Equal(t, hackatomWasm, storedCode) -} - -func TestCreateWithSimulation(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - ctx = ctx.WithBlockHeader(tmproto.Header{Height: 1}). - WithGasMeter(stypes.NewInfiniteGasMeter()) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // create this once in simulation mode - contractID, _, err := keepers.ContractKeeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - - // then try to create it in non-simulation mode (should not fail) - ctx, keepers = CreateTestInput(t, false, AvailableCapabilities) - ctx = ctx.WithGasMeter(sdk.NewGasMeter(10_000_000)) - creator = keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - contractID, _, err = keepers.ContractKeeper.Create(ctx, creator, hackatomWasm, nil) - - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - - // and verify content - code, err := keepers.WasmKeeper.GetByteCode(ctx, contractID) - require.NoError(t, err) - require.Equal(t, code, hackatomWasm) -} - -func TestIsSimulationMode(t *testing.T) { - specs := map[string]struct { - ctx sdk.Context - exp bool - }{ - "genesis block": { - ctx: sdk.Context{}.WithBlockHeader(tmproto.Header{}).WithGasMeter(stypes.NewInfiniteGasMeter()), - exp: false, - }, - "any regular block": { - ctx: sdk.Context{}.WithBlockHeader(tmproto.Header{Height: 1}).WithGasMeter(stypes.NewGasMeter(10000000)), - exp: false, - }, - "simulation": { - ctx: sdk.Context{}.WithBlockHeader(tmproto.Header{Height: 1}).WithGasMeter(stypes.NewInfiniteGasMeter()), - exp: true, - }, - } - for msg := range specs { - t.Run(msg, func(t *testing.T) { - // assert.Equal(t, spec.exp, isSimulationMode(spec.ctx)) - }) - } -} - -func TestCreateWithGzippedPayload(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm.gzip") - require.NoError(t, err, "reading gzipped WASM code") - - contractID, _, err := keeper.Create(ctx, creator, wasmCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), contractID) - // and verify content - storedCode, err := keepers.WasmKeeper.GetByteCode(ctx, contractID) - require.NoError(t, err) - require.Equal(t, hackatomWasm, storedCode) -} - -func TestCreateWithBrokenGzippedPayload(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - wasmCode, err := os.ReadFile("./testdata/broken_crc.gzip") - require.NoError(t, err, "reading gzipped WASM code") - - gm := sdk.NewInfiniteGasMeter() - codeID, checksum, err := keeper.Create(ctx.WithGasMeter(gm), creator, wasmCode, nil) - require.Error(t, err) - assert.Empty(t, codeID) - assert.Empty(t, checksum) - assert.GreaterOrEqual(t, gm.GasConsumed(), sdk.Gas(121384)) // 809232 * 0.15 (default uncompress costs) = 121384 -} - -func TestInstantiate(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - keepers.Faucet.Fund(ctx, creator, deposit...) - example := StoreHackatomExampleContract(t, ctx, keepers) - - initMsg := HackatomExampleInitMsg{ - Verifier: RandomAccountAddress(t), - Beneficiary: RandomAccountAddress(t), - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - gasBefore := ctx.GasMeter().GasConsumed() - - em := sdk.NewEventManager() - // create with no balance is also legal - gotContractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil) - require.NoError(t, err) - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", gotContractAddr.String()) - - gasAfter := ctx.GasMeter().GasConsumed() - if types.EnableGasVerification { - require.Equal(t, uint64(0x1b5bc), gasAfter-gasBefore) - } - - // ensure it is stored properly - info := keepers.WasmKeeper.GetContractInfo(ctx, gotContractAddr) - require.NotNil(t, info) - assert.Equal(t, creator.String(), info.Creator) - assert.Equal(t, example.CodeID, info.CodeID) - assert.Equal(t, "demo contract 1", info.Label) - - exp := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: example.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: initMsgBz, - }} - assert.Equal(t, exp, keepers.WasmKeeper.GetContractHistory(ctx, gotContractAddr)) - - // and events emitted - expEvt := sdk.Events{ - sdk.NewEvent("instantiate", - sdk.NewAttribute("_contract_address", gotContractAddr.String()), sdk.NewAttribute("code_id", "1")), - sdk.NewEvent("wasm", - sdk.NewAttribute("_contract_address", gotContractAddr.String()), sdk.NewAttribute("Let the", "hacking begin")), - } - assert.Equal(t, expEvt, em.Events()) -} - -func TestInstantiateWithDeposit(t *testing.T) { - var ( - bob = bytes.Repeat([]byte{1}, types.SDKAddrLen) - fred = bytes.Repeat([]byte{2}, types.SDKAddrLen) - - deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - initMsg = mustMarshal(t, HackatomExampleInitMsg{Verifier: fred, Beneficiary: bob}) - ) - - specs := map[string]struct { - srcActor sdk.AccAddress - expError bool - fundAddr bool - }{ - "address with funds": { - srcActor: bob, - fundAddr: true, - }, - "address without funds": { - srcActor: bob, - expError: true, - }, - "blocked address": { - srcActor: authtypes.NewModuleAddress(authtypes.FeeCollectorName), - fundAddr: true, - expError: false, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.ContractKeeper - - if spec.fundAddr { - fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, sdk.NewCoins(sdk.NewInt64Coin("denom", 200))) - } - contractID, _, err := keeper.Create(ctx, spec.srcActor, hackatomWasm, nil) - require.NoError(t, err) - - // when - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsg, "my label", deposit) - // then - if spec.expError { - require.Error(t, err) - return - } - require.NoError(t, err) - balances := bankKeeper.GetAllBalances(ctx, addr) - assert.Equal(t, deposit, balances) - }) - } -} - -func TestInstantiateWithPermissions(t *testing.T) { - var ( - deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - myAddr = bytes.Repeat([]byte{1}, types.SDKAddrLen) - otherAddr = bytes.Repeat([]byte{2}, types.SDKAddrLen) - anyAddr = bytes.Repeat([]byte{3}, types.SDKAddrLen) - ) - - initMsg := HackatomExampleInitMsg{ - Verifier: anyAddr, - Beneficiary: anyAddr, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - specs := map[string]struct { - srcPermission types.AccessConfig - srcActor sdk.AccAddress - expError *errorsmod.Error - }{ - "default": { - srcPermission: types.DefaultUploadAccess, - srcActor: anyAddr, - }, - "everybody": { - srcPermission: types.AllowEverybody, - srcActor: anyAddr, - }, - "nobody": { - srcPermission: types.AllowNobody, - srcActor: myAddr, - expError: sdkerrors.ErrUnauthorized, - }, - "onlyAddress with matching address": { - srcPermission: types.AccessTypeOnlyAddress.With(myAddr), - srcActor: myAddr, - }, - "onlyAddress with non matching address": { - srcActor: myAddr, - srcPermission: types.AccessTypeOnlyAddress.With(otherAddr), - expError: sdkerrors.ErrUnauthorized, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.ContractKeeper - fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, deposit) - - contractID, _, err := keeper.Create(ctx, myAddr, hackatomWasm, &spec.srcPermission) - require.NoError(t, err) - - _, _, err = keepers.ContractKeeper.Instantiate(ctx, contractID, spec.srcActor, nil, initMsgBz, "demo contract 1", nil) - assert.True(t, spec.expError.Is(err), "got %+v", err) - }) - } -} - -func TestInstantiateWithAccounts(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example := StoreHackatomExampleContract(t, parentCtx, keepers) - require.Equal(t, uint64(1), example.CodeID) - initMsg := mustMarshal(t, HackatomExampleInitMsg{Verifier: RandomAccountAddress(t), Beneficiary: RandomAccountAddress(t)}) - - senderAddr := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, senderAddr, sdk.NewInt64Coin("denom", 100000000)) - mySalt := []byte(`my salt`) - contractAddr := BuildContractAddressPredictable(example.Checksum, senderAddr, mySalt, []byte{}) - - lastAccountNumber := keepers.AccountKeeper.GetAccount(parentCtx, senderAddr).GetAccountNumber() - - specs := map[string]struct { - option Option - account authtypes.AccountI - initBalance sdk.Coin - deposit sdk.Coins - expErr error - expAccount authtypes.AccountI - expBalance sdk.Coins - }{ - "unused BaseAccount exists": { - account: authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - initBalance: sdk.NewInt64Coin("denom", 100000000), - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), // +1 for next seq - expBalance: sdk.NewCoins(sdk.NewInt64Coin("denom", 100000000)), - }, - "BaseAccount with sequence exists": { - account: authtypes.NewBaseAccount(contractAddr, nil, 0, 1), - expErr: types.ErrAccountExists, - }, - "BaseAccount with pubkey exists": { - account: authtypes.NewBaseAccount(contractAddr, &ed25519.PubKey{}, 0, 0), - expErr: types.ErrAccountExists, - }, - "no account existed": { - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), // +1 for next seq, - expBalance: sdk.NewCoins(), - }, - "no account existed before create with deposit": { - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), // +1 for next seq - deposit: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), - expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), - }, - "prunable DelayedVestingAccount gets overwritten": { - account: vestingtypes.NewDelayedVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix()), - initBalance: sdk.NewCoin("denom", sdk.NewInt(1_000)), - deposit: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+2, 0), // +1 for next seq, +1 for spec.account created - expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - }, - "prunable ContinuousVestingAccount gets overwritten": { - account: vestingtypes.NewContinuousVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(time.Hour).Unix(), time.Now().Add(2*time.Hour).Unix()), - initBalance: sdk.NewCoin("denom", sdk.NewInt(1_000)), - deposit: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+2, 0), // +1 for next seq, +1 for spec.account created - expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - }, - "prunable account without balance gets overwritten": { - account: vestingtypes.NewContinuousVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(0))), time.Now().Add(time.Hour).Unix(), time.Now().Add(2*time.Hour).Unix()), - expAccount: authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+2, 0), // +1 for next seq, +1 for spec.account created - expBalance: sdk.NewCoins(), - }, - "unknown account type is rejected with error": { - account: authtypes.NewModuleAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - "testing", - ), - initBalance: sdk.NewCoin("denom", sdk.NewInt(1_000)), - expErr: types.ErrAccountExists, - }, - "with option used to set non default type to accept list": { - option: WithAcceptedAccountTypesOnContractInstantiation(&vestingtypes.DelayedVestingAccount{}), - account: vestingtypes.NewDelayedVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix()), - initBalance: sdk.NewCoin("denom", sdk.NewInt(1_000)), - deposit: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1))), - expAccount: vestingtypes.NewDelayedVestingAccount(authtypes.NewBaseAccount(contractAddr, nil, lastAccountNumber+1, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix()), - expBalance: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_001))), - }, - "pruning account fails": { - option: WithAccountPruner(wasmtesting.AccountPrunerMock{CleanupExistingAccountFn: func(ctx sdk.Context, existingAccount authtypes.AccountI) (handled bool, err error) { - return false, types.ErrUnsupportedForContract.Wrap("testing") - }}), - account: vestingtypes.NewDelayedVestingAccount( - authtypes.NewBaseAccount(contractAddr, nil, 0, 0), - sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))), time.Now().Add(30*time.Hour).Unix()), - expErr: types.ErrUnsupportedForContract, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - if spec.account != nil { - keepers.AccountKeeper.SetAccount(ctx, keepers.AccountKeeper.NewAccount(ctx, spec.account)) - } - if !spec.initBalance.IsNil() { - keepers.Faucet.Fund(ctx, spec.account.GetAddress(), spec.initBalance) - } - if spec.option != nil { - spec.option.apply(keepers.WasmKeeper) - } - defer func() { - if spec.option != nil { // reset - WithAcceptedAccountTypesOnContractInstantiation(&authtypes.BaseAccount{}).apply(keepers.WasmKeeper) - WithAccountPruner(NewVestingCoinBurner(keepers.BankKeeper)).apply(keepers.WasmKeeper) - } - }() - // when - gotAddr, _, gotErr := keepers.ContractKeeper.Instantiate2(ctx, 1, senderAddr, nil, initMsg, myTestLabel, spec.deposit, mySalt, false) - if spec.expErr != nil { - assert.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, contractAddr, gotAddr) - // and - gotAcc := keepers.AccountKeeper.GetAccount(ctx, contractAddr) - assert.Equal(t, spec.expAccount, gotAcc) - // and - gotBalance := keepers.BankKeeper.GetAllBalances(ctx, contractAddr) - assert.Equal(t, spec.expBalance, gotBalance) - }) - } -} - -func TestInstantiateWithNonExistingCodeID(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - initMsg := HackatomExampleInitMsg{} - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - const nonExistingCodeID = 9999 - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, nonExistingCodeID, creator, nil, initMsgBz, "demo contract 2", nil) - require.True(t, types.ErrNotFound.Is(err), err) - require.Nil(t, addr) -} - -func TestInstantiateWithContractDataResponse(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - wasmerMock := &wasmtesting.MockWasmer{ - InstantiateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{Data: []byte("my-response-data")}, 0, nil - }, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - CreateFn: wasmtesting.NoOpCreateFn, - } - - example := StoreRandomContract(t, ctx, keepers, wasmerMock) - _, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, nil, "test", nil) - require.NoError(t, err) - assert.Equal(t, []byte("my-response-data"), data) -} - -func TestInstantiateWithContractFactoryChildQueriesParent(t *testing.T) { - // Scenario: - // given a factory contract stored - // when instantiated, the contract creates a new child contract instance - // and the child contracts queries the senders ContractInfo on instantiation - // then the factory contract's ContractInfo should be returned to the child contract - // - // see also: https://github.com/terpnetwork/terp-core/issues/896 - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - var instantiationCount int - callbacks := make([]func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error), 2) - wasmerMock := &wasmtesting.MockWasmer{ - // dispatch instantiation calls to callbacks - InstantiateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - require.Greater(t, len(callbacks), instantiationCount, "unexpected call to instantiation") - do := callbacks[instantiationCount] - instantiationCount++ - return do(codeID, env, info, initMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) - }, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - CreateFn: wasmtesting.NoOpCreateFn, - } - - // overwrite wasmvm in router - router := baseapp.NewMsgServiceRouter() - router.SetInterfaceRegistry(keepers.EncodingConfig.InterfaceRegistry) - types.RegisterMsgServer(router, NewMsgServerImpl(keeper)) - keeper.messenger = NewDefaultMessageHandler(router, nil, nil, nil, keepers.EncodingConfig.Marshaler, nil) - // overwrite wasmvm in response handler - keeper.wasmVMResponseHandler = NewDefaultWasmVMContractResponseHandler(NewMessageDispatcher(keeper.messenger, keeper)) - - example := StoreRandomContract(t, ctx, keepers, wasmerMock) - // factory contract - callbacks[0] = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - t.Log("called factory") - return &wasmvmtypes.Response{Data: []byte("parent"), Messages: []wasmvmtypes.SubMsg{ - { - ID: 1, ReplyOn: wasmvmtypes.ReplyNever, - Msg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Instantiate: &wasmvmtypes.InstantiateMsg{CodeID: example.CodeID, Msg: []byte(`{}`), Label: "child"}, - }, - }, - }, - }}, 0, nil - } - - // child contract - var capturedSenderAddr string - var capturedCodeInfo []byte - callbacks[1] = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - t.Log("called child") - capturedSenderAddr = info.Sender - var err error - capturedCodeInfo, err = querier.Query(wasmvmtypes.QueryRequest{ - Wasm: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: info.Sender}, - }, - }, gasLimit) - require.NoError(t, err) - return &wasmvmtypes.Response{Data: []byte("child")}, 0, nil - } - - // when - parentAddr, data, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, nil, "test", nil) - - // then - require.NoError(t, err) - assert.Equal(t, []byte("parent"), data) - require.Equal(t, parentAddr.String(), capturedSenderAddr) - expCodeInfo := fmt.Sprintf(`{"code_id":%d,"creator":%q,"pinned":false}`, example.CodeID, example.CreatorAddr.String()) - assert.JSONEq(t, expCodeInfo, string(capturedCodeInfo)) -} - -func TestExecute(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - bob := RandomAccountAddress(t) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) - require.NoError(t, err) - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", addr.String()) - - // ensure bob doesn't exist - bobAcct := accKeeper.GetAccount(ctx, bob) - require.Nil(t, bobAcct) - - // ensure funder has reduced balance - creatorAcct := accKeeper.GetAccount(ctx, creator) - require.NotNil(t, creatorAcct) - // we started at 2*deposit, should have spent one above - assert.Equal(t, deposit, bankKeeper.GetAllBalances(ctx, creatorAcct.GetAddress())) - - // ensure contract has updated balance - contractAcct := accKeeper.GetAccount(ctx, addr) - require.NotNil(t, contractAcct) - assert.Equal(t, deposit, bankKeeper.GetAllBalances(ctx, contractAcct.GetAddress())) - - // unauthorized - trialCtx so we don't change state - trialCtx := ctx.WithMultiStore(ctx.MultiStore().CacheWrap().(sdk.MultiStore)) - _, err = keepers.ContractKeeper.Execute(trialCtx, addr, creator, []byte(`{"release":{}}`), nil) - require.Error(t, err) - require.True(t, errors.Is(err, types.ErrExecuteFailed)) - require.Equal(t, "Unauthorized: execute wasm contract failed", err.Error()) - - // verifier can execute, and get proper gas amount - start := time.Now() - gasBefore := ctx.GasMeter().GasConsumed() - em := sdk.NewEventManager() - // when - res, err := keepers.ContractKeeper.Execute(ctx.WithEventManager(em), addr, fred, []byte(`{"release":{}}`), topUp) - diff := time.Since(start) - require.NoError(t, err) - require.NotNil(t, res) - - // make sure gas is properly deducted from ctx - gasAfter := ctx.GasMeter().GasConsumed() - if types.EnableGasVerification { - require.Equal(t, uint64(0x1a154), gasAfter-gasBefore) - } - // ensure bob now exists and got both payments released - bobAcct = accKeeper.GetAccount(ctx, bob) - require.NotNil(t, bobAcct) - balance := bankKeeper.GetAllBalances(ctx, bobAcct.GetAddress()) - assert.Equal(t, deposit.Add(topUp...), balance) - - // ensure contract has updated balance - contractAcct = accKeeper.GetAccount(ctx, addr) - require.NotNil(t, contractAcct) - assert.Equal(t, sdk.Coins{}, bankKeeper.GetAllBalances(ctx, contractAcct.GetAddress())) - - // and events emitted - require.Len(t, em.Events(), 9) - expEvt := sdk.NewEvent("execute", - sdk.NewAttribute("_contract_address", addr.String())) - assert.Equal(t, expEvt, em.Events()[3], prettyEvents(t, em.Events())) - - t.Logf("Duration: %v (%d gas)\n", diff, gasAfter-gasBefore) -} - -func TestExecuteWithDeposit(t *testing.T) { - var ( - bob = bytes.Repeat([]byte{1}, types.SDKAddrLen) - fred = bytes.Repeat([]byte{2}, types.SDKAddrLen) - blockedAddr = authtypes.NewModuleAddress(distributiontypes.ModuleName) - deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - ) - - specs := map[string]struct { - srcActor sdk.AccAddress - beneficiary sdk.AccAddress - newBankParams *banktypes.Params - expError bool - fundAddr bool - }{ - "actor with funds": { - srcActor: bob, - fundAddr: true, - beneficiary: fred, - }, - "actor without funds": { - srcActor: bob, - beneficiary: fred, - expError: true, - }, - "blocked address as actor": { - srcActor: blockedAddr, - fundAddr: true, - beneficiary: fred, - expError: false, - }, - "coin transfer with all transfers disabled": { - srcActor: bob, - fundAddr: true, - beneficiary: fred, - newBankParams: &banktypes.Params{DefaultSendEnabled: false}, - expError: true, - }, - "coin transfer with transfer denom disabled": { - srcActor: bob, - fundAddr: true, - beneficiary: fred, - newBankParams: &banktypes.Params{ - DefaultSendEnabled: true, - SendEnabled: []*banktypes.SendEnabled{{Denom: "denom", Enabled: false}}, - }, - expError: true, - }, - "blocked address as beneficiary": { - srcActor: bob, - fundAddr: true, - beneficiary: blockedAddr, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.ContractKeeper - if spec.newBankParams != nil { - err := bankKeeper.SetParams(ctx, *spec.newBankParams) - require.NoError(t, err) - } - if spec.fundAddr { - fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, sdk.NewCoins(sdk.NewInt64Coin("denom", 200))) - } - codeID, _, err := keeper.Create(ctx, spec.srcActor, hackatomWasm, nil) - require.NoError(t, err) - - initMsg := HackatomExampleInitMsg{Verifier: spec.srcActor, Beneficiary: spec.beneficiary} - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, spec.srcActor, nil, initMsgBz, "my label", nil) - require.NoError(t, err) - - // when - _, err = keepers.ContractKeeper.Execute(ctx, contractAddr, spec.srcActor, []byte(`{"release":{}}`), deposit) - - // then - if spec.expError { - require.Error(t, err) - return - } - require.NoError(t, err) - balances := bankKeeper.GetAllBalances(ctx, spec.beneficiary) - assert.Equal(t, deposit, balances) - }) - } -} - -func TestExecuteWithNonExistingAddress(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - - // unauthorized - trialCtx so we don't change state - nonExistingAddress := RandomAccountAddress(t) - _, err := keeper.Execute(ctx, nonExistingAddress, creator, []byte(`{}`), nil) - require.True(t, types.ErrNotFound.Is(err), err) -} - -func TestExecuteWithPanic(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 4", deposit) - require.NoError(t, err) - - // let's make sure we get a reasonable error, no panic/crash - _, err = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"panic":{}}`), topUp) - require.Error(t, err) - require.True(t, errors.Is(err, types.ErrExecuteFailed)) - // test with contains as "Display" implementation of the Wasmer "RuntimeError" is different for Mac and Linux - assert.Contains(t, err.Error(), "Error calling the VM: Error executing Wasm: Wasmer runtime error: RuntimeError: Aborted: panicked at 'This page intentionally faulted', src/contract.rs:169:5: execute wasm contract failed") -} - -func TestExecuteWithCpuLoop(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 5", deposit) - require.NoError(t, err) - - // make sure we set a limit before calling - var gasLimit uint64 = 400_000 - ctx = ctx.WithGasMeter(sdk.NewGasMeter(gasLimit)) - require.Equal(t, uint64(0), ctx.GasMeter().GasConsumed()) - - // ensure we get an out of gas panic - defer func() { - r := recover() - require.NotNil(t, r) - _, ok := r.(sdk.ErrorOutOfGas) - require.True(t, ok, "%v", r) - }() - - // this should throw out of gas exception (panic) - _, _ = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"cpu_loop":{}}`), nil) - require.True(t, false, "We must panic before this line") -} - -func TestExecuteWithStorageLoop(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 6", deposit) - require.NoError(t, err) - - // make sure we set a limit before calling - var gasLimit uint64 = 400_002 - ctx = ctx.WithGasMeter(sdk.NewGasMeter(gasLimit)) - require.Equal(t, uint64(0), ctx.GasMeter().GasConsumed()) - - // ensure we get an out of gas panic - defer func() { - r := recover() - require.NotNil(t, r) - _, ok := r.(sdk.ErrorOutOfGas) - require.True(t, ok, "%v", r) - }() - - // this should throw out of gas exception (panic) - _, _ = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"storage_loop":{}}`), nil) - require.True(t, false, "We must panic before this line") -} - -func TestMigrate(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, creator, deposit.Add(deposit...)...) - fred := DeterministicAccountAddress(t, 2) - keepers.Faucet.Fund(parentCtx, fred, topUp...) - - originalCodeID := StoreHackatomExampleContract(t, parentCtx, keepers).CodeID - newCodeID := StoreHackatomExampleContract(t, parentCtx, keepers).CodeID - ibcCodeID := StoreIBCReflectContract(t, parentCtx, keepers).CodeID - require.NotEqual(t, originalCodeID, newCodeID) - - restrictedCodeExample := StoreHackatomExampleContract(t, parentCtx, keepers) - require.NoError(t, keeper.SetAccessConfig(parentCtx, restrictedCodeExample.CodeID, restrictedCodeExample.CreatorAddr, types.AllowNobody)) - require.NotEqual(t, originalCodeID, restrictedCodeExample.CodeID) - - anyAddr := RandomAccountAddress(t) - newVerifierAddr := RandomAccountAddress(t) - initMsgBz := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: anyAddr, - }.GetBytes(t) - - migMsg := struct { - Verifier sdk.AccAddress `json:"verifier"` - }{Verifier: newVerifierAddr} - migMsgBz, err := json.Marshal(migMsg) - require.NoError(t, err) - - specs := map[string]struct { - admin sdk.AccAddress - overrideContractAddr sdk.AccAddress - caller sdk.AccAddress - fromCodeID uint64 - toCodeID uint64 - migrateMsg []byte - expErr *errorsmod.Error - expVerifier sdk.AccAddress - expIBCPort bool - initMsg []byte - }{ - "all good with same code id": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - migrateMsg: migMsgBz, - expVerifier: newVerifierAddr, - }, - "all good with different code id": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: newCodeID, - migrateMsg: migMsgBz, - expVerifier: newVerifierAddr, - }, - "all good with admin set": { - admin: fred, - caller: fred, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: newCodeID, - migrateMsg: migMsgBz, - expVerifier: newVerifierAddr, - }, - "adds IBC port for IBC enabled contracts": { - admin: fred, - caller: fred, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: ibcCodeID, - migrateMsg: []byte(`{}`), - expIBCPort: true, - expVerifier: fred, // not updated - }, - "prevent migration when admin was not set on instantiate": { - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - expErr: sdkerrors.ErrUnauthorized, - }, - "prevent migration when not sent by admin": { - caller: creator, - admin: fred, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - expErr: sdkerrors.ErrUnauthorized, - }, - "prevent migration when new code is restricted": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: restrictedCodeExample.CodeID, - migrateMsg: migMsgBz, - expErr: sdkerrors.ErrUnauthorized, - }, - "fail with non existing code id": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: 99999, - expErr: sdkerrors.ErrInvalidRequest, - }, - "fail with non existing contract addr": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - overrideContractAddr: anyAddr, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - expErr: sdkerrors.ErrInvalidRequest, - }, - "fail in contract with invalid migrate msg": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - migrateMsg: bytes.Repeat([]byte{0x1}, 7), - expErr: types.ErrMigrationFailed, - }, - "fail in contract without migrate msg": { - admin: creator, - caller: creator, - initMsg: initMsgBz, - fromCodeID: originalCodeID, - toCodeID: originalCodeID, - expErr: types.ErrMigrationFailed, - }, - "fail when no IBC callbacks": { - admin: fred, - caller: fred, - initMsg: IBCReflectInitMsg{ReflectCodeID: StoreReflectContract(t, parentCtx, keepers).CodeID}.GetBytes(t), - fromCodeID: ibcCodeID, - toCodeID: newCodeID, - migrateMsg: migMsgBz, - expErr: types.ErrMigrationFailed, - }, - } - - blockHeight := parentCtx.BlockHeight() - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - // given a contract instance - ctx, _ := parentCtx.WithBlockHeight(blockHeight + 1).CacheContext() - blockHeight++ - - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, spec.fromCodeID, creator, spec.admin, spec.initMsg, "demo contract", nil) - require.NoError(t, err) - if spec.overrideContractAddr != nil { - contractAddr = spec.overrideContractAddr - } - // when - _, err = keeper.Migrate(ctx, contractAddr, spec.caller, spec.toCodeID, spec.migrateMsg) - - // then - require.True(t, spec.expErr.Is(err), "expected %v but got %+v", spec.expErr, err) - if spec.expErr != nil { - return - } - cInfo := keepers.WasmKeeper.GetContractInfo(ctx, contractAddr) - assert.Equal(t, spec.toCodeID, cInfo.CodeID) - assert.Equal(t, spec.expIBCPort, cInfo.IBCPortID != "", cInfo.IBCPortID) - - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: spec.fromCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: initMsgBz, - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: spec.toCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: spec.migrateMsg, - }} - assert.Equal(t, expHistory, keepers.WasmKeeper.GetContractHistory(ctx, contractAddr)) - - // and verify contract state - raw := keepers.WasmKeeper.QueryRaw(ctx, contractAddr, []byte("config")) - var stored map[string]string - require.NoError(t, json.Unmarshal(raw, &stored)) - require.Contains(t, stored, "verifier") - require.NoError(t, err) - assert.Equal(t, spec.expVerifier.String(), stored["verifier"]) - }) - } -} - -func TestMigrateReplacesTheSecondIndex(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example := InstantiateHackatomExampleContract(t, ctx, keepers) - - // then assert a second index exists - store := ctx.KVStore(keepers.WasmKeeper.storeKey) - oldContractInfo := keepers.WasmKeeper.GetContractInfo(ctx, example.Contract) - require.NotNil(t, oldContractInfo) - createHistoryEntry := types.ContractCodeHistoryEntry{ - CodeID: example.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - } - exists := store.Has(types.GetContractByCreatedSecondaryIndexKey(example.Contract, createHistoryEntry)) - require.True(t, exists) - - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) // increment for different block - // when do migrate - newCodeExample := StoreBurnerExampleContract(t, ctx, keepers) - migMsgBz := BurnerExampleInitMsg{Payout: example.CreatorAddr}.GetBytes(t) - _, err := keepers.ContractKeeper.Migrate(ctx, example.Contract, example.CreatorAddr, newCodeExample.CodeID, migMsgBz) - require.NoError(t, err) - - // then the new index exists - migrateHistoryEntry := types.ContractCodeHistoryEntry{ - CodeID: newCodeExample.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - } - exists = store.Has(types.GetContractByCreatedSecondaryIndexKey(example.Contract, migrateHistoryEntry)) - require.True(t, exists) - // and the old index was removed - exists = store.Has(types.GetContractByCreatedSecondaryIndexKey(example.Contract, createHistoryEntry)) - require.False(t, exists) -} - -func TestMigrateWithDispatchedMessage(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(ctx, sdk.NewInt64Coin("denom", 5000)) - - burnerCode, err := os.ReadFile("./testdata/burner.wasm") - require.NoError(t, err) - - originalContractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - burnerContractID, _, err := keeper.Create(ctx, creator, burnerCode, nil) - require.NoError(t, err) - require.NotEqual(t, originalContractID, burnerContractID) - - _, myPayoutAddr := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: fred, - } - initMsgBz := initMsg.GetBytes(t) - - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, originalContractID, creator, fred, initMsgBz, "demo contract", deposit) - require.NoError(t, err) - - migMsgBz := BurnerExampleInitMsg{Payout: myPayoutAddr}.GetBytes(t) - ctx = ctx.WithEventManager(sdk.NewEventManager()).WithBlockHeight(ctx.BlockHeight() + 1) - data, err := keeper.Migrate(ctx, contractAddr, fred, burnerContractID, migMsgBz) - require.NoError(t, err) - assert.Equal(t, "burnt 1 keys", string(data)) - type dict map[string]interface{} - expEvents := []dict{ - { - "Type": "migrate", - "Attr": []dict{ - {"code_id": "2"}, - {"_contract_address": contractAddr}, - }, - }, - { - "Type": "wasm", - "Attr": []dict{ - {"_contract_address": contractAddr}, - {"action": "burn"}, - {"payout": myPayoutAddr}, - }, - }, - { - "Type": "coin_spent", - "Attr": []dict{ - {"spender": contractAddr}, - {"amount": "100000denom"}, - }, - }, - { - "Type": "coin_received", - "Attr": []dict{ - {"receiver": myPayoutAddr}, - {"amount": "100000denom"}, - }, - }, - { - "Type": "transfer", - "Attr": []dict{ - {"recipient": myPayoutAddr}, - {"sender": contractAddr}, - {"amount": "100000denom"}, - }, - }, - } - expJSONEvts := string(mustMarshal(t, expEvents)) - assert.JSONEq(t, expJSONEvts, prettyEvents(t, ctx.EventManager().Events()), prettyEvents(t, ctx.EventManager().Events())) - - // all persistent data cleared - m := keepers.WasmKeeper.QueryRaw(ctx, contractAddr, []byte("config")) - require.Len(t, m, 0) - - // and all deposit tokens sent to myPayoutAddr - balance := keepers.BankKeeper.GetAllBalances(ctx, myPayoutAddr) - assert.Equal(t, deposit, balance) -} - -func TestIterateContractsByCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k, c := keepers.WasmKeeper, keepers.ContractKeeper - example1 := InstantiateHackatomExampleContract(t, ctx, keepers) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - example2 := InstantiateIBCReflectContract(t, ctx, keepers) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - initMsg := HackatomExampleInitMsg{ - Verifier: RandomAccountAddress(t), - Beneficiary: RandomAccountAddress(t), - }.GetBytes(t) - contractAddr3, _, err := c.Instantiate(ctx, example1.CodeID, example1.CreatorAddr, nil, initMsg, "foo", nil) - require.NoError(t, err) - specs := map[string]struct { - codeID uint64 - exp []sdk.AccAddress - }{ - "multiple results": { - codeID: example1.CodeID, - exp: []sdk.AccAddress{example1.Contract, contractAddr3}, - }, - "single results": { - codeID: example2.CodeID, - exp: []sdk.AccAddress{example2.Contract}, - }, - "empty results": { - codeID: 99999, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var gotAddr []sdk.AccAddress - k.IterateContractsByCode(ctx, spec.codeID, func(address sdk.AccAddress) bool { - gotAddr = append(gotAddr, address) - return false - }) - assert.Equal(t, spec.exp, gotAddr) - }) - } -} - -func TestIterateContractsByCodeWithMigration(t *testing.T) { - // mock migration so that it does not fail when migrate example1 to example2.codeID - mockWasmVM := wasmtesting.MockWasmer{MigrateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, migrateMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{}, 1, nil - }} - wasmtesting.MakeInstantiable(&mockWasmVM) - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithWasmEngine(&mockWasmVM)) - k, c := keepers.WasmKeeper, keepers.ContractKeeper - example1 := InstantiateHackatomExampleContract(t, ctx, keepers) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - example2 := InstantiateIBCReflectContract(t, ctx, keepers) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - _, err := c.Migrate(ctx, example1.Contract, example1.CreatorAddr, example2.CodeID, []byte("{}")) - require.NoError(t, err) - - // when - var gotAddr []sdk.AccAddress - k.IterateContractsByCode(ctx, example2.CodeID, func(address sdk.AccAddress) bool { - gotAddr = append(gotAddr, address) - return false - }) - - // then - exp := []sdk.AccAddress{example2.Contract, example1.Contract} - assert.Equal(t, exp, gotAddr) -} - -type sudoMsg struct { - // This is a tongue-in-check demo command. This is not the intended purpose of Sudo. - // Here we show that some priviledged Go module can make a call that should never be exposed - // to end users (via Tx/Execute). - // - // The contract developer can choose to expose anything to sudo. This functionality is not a true - // backdoor (it can never be called by end users), but allows the developers of the native blockchain - // code to make special calls. This can also be used as an authentication mechanism, if you want to expose - // some callback that only can be triggered by some system module and not faked by external users. - StealFunds stealFundsMsg `json:"steal_funds"` -} - -type stealFundsMsg struct { - Recipient string `json:"recipient"` - Amount wasmvmtypes.Coins `json:"amount"` -} - -func TestSudo(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(ctx, creator, deposit.Add(deposit...)...) - - contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - _, fred := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract 3", deposit) - require.NoError(t, err) - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", addr.String()) - - // the community is broke - _, community := keyPubAddr() - comAcct := accKeeper.GetAccount(ctx, community) - require.Nil(t, comAcct) - - // now the community wants to get paid via sudo - msg := sudoMsg{ - // This is a tongue-in-check demo command. This is not the intended purpose of Sudo. - // Here we show that some priviledged Go module can make a call that should never be exposed - // to end users (via Tx/Execute). - StealFunds: stealFundsMsg{ - Recipient: community.String(), - Amount: wasmvmtypes.Coins{wasmvmtypes.NewCoin(76543, "denom")}, - }, - } - sudoMsg, err := json.Marshal(msg) - require.NoError(t, err) - - em := sdk.NewEventManager() - - // when - _, err = keepers.WasmKeeper.Sudo(ctx.WithEventManager(em), addr, sudoMsg) - require.NoError(t, err) - - // ensure community now exists and got paid - comAcct = accKeeper.GetAccount(ctx, community) - require.NotNil(t, comAcct) - balance := bankKeeper.GetBalance(ctx, comAcct.GetAddress(), "denom") - assert.Equal(t, sdk.NewInt64Coin("denom", 76543), balance) - // and events emitted - require.Len(t, em.Events(), 4, prettyEvents(t, em.Events())) - expEvt := sdk.NewEvent("sudo", - sdk.NewAttribute("_contract_address", addr.String())) - assert.Equal(t, expEvt, em.Events()[0]) -} - -func prettyEvents(t *testing.T, events sdk.Events) string { - t.Helper() - type prettyEvent struct { - Type string - Attr []map[string]string - } - - r := make([]prettyEvent, len(events)) - for i, e := range events { - attr := make([]map[string]string, len(e.Attributes)) - for j, a := range e.Attributes { - attr[j] = map[string]string{a.Key: a.Value} - } - r[i] = prettyEvent{Type: e.Type, Attr: attr} - } - return string(mustMarshal(t, r)) -} - -func mustMarshal(t *testing.T, r interface{}) []byte { - t.Helper() - bz, err := json.Marshal(r) - require.NoError(t, err) - return bz -} - -func TestUpdateContractAdmin(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - - originalContractID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, anyAddr := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: anyAddr, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - specs := map[string]struct { - instAdmin sdk.AccAddress - newAdmin sdk.AccAddress - overrideContractAddr sdk.AccAddress - caller sdk.AccAddress - expErr *errorsmod.Error - }{ - "all good with admin set": { - instAdmin: fred, - newAdmin: anyAddr, - caller: fred, - }, - "prevent update when admin was not set on instantiate": { - caller: creator, - newAdmin: fred, - expErr: sdkerrors.ErrUnauthorized, - }, - "prevent updates from non admin address": { - instAdmin: creator, - newAdmin: fred, - caller: fred, - expErr: sdkerrors.ErrUnauthorized, - }, - "fail with non existing contract addr": { - instAdmin: creator, - newAdmin: anyAddr, - caller: creator, - overrideContractAddr: anyAddr, - expErr: sdkerrors.ErrInvalidRequest, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, originalContractID, creator, spec.instAdmin, initMsgBz, "demo contract", nil) - require.NoError(t, err) - if spec.overrideContractAddr != nil { - addr = spec.overrideContractAddr - } - err = keeper.UpdateContractAdmin(ctx, addr, spec.caller, spec.newAdmin) - require.True(t, spec.expErr.Is(err), "expected %v but got %+v", spec.expErr, err) - if spec.expErr != nil { - return - } - cInfo := keepers.WasmKeeper.GetContractInfo(ctx, addr) - assert.Equal(t, spec.newAdmin.String(), cInfo.Admin) - }) - } -} - -func TestClearContractAdmin(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, creator, deposit.Add(deposit...)...) - fred := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - - originalContractID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) - require.NoError(t, err) - - _, anyAddr := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: anyAddr, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - specs := map[string]struct { - instAdmin sdk.AccAddress - overrideContractAddr sdk.AccAddress - caller sdk.AccAddress - expErr *errorsmod.Error - }{ - "all good when called by proper admin": { - instAdmin: fred, - caller: fred, - }, - "prevent update when admin was not set on instantiate": { - caller: creator, - expErr: sdkerrors.ErrUnauthorized, - }, - "prevent updates from non admin address": { - instAdmin: creator, - caller: fred, - expErr: sdkerrors.ErrUnauthorized, - }, - "fail with non existing contract addr": { - instAdmin: creator, - caller: creator, - overrideContractAddr: anyAddr, - expErr: sdkerrors.ErrInvalidRequest, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, originalContractID, creator, spec.instAdmin, initMsgBz, "demo contract", nil) - require.NoError(t, err) - if spec.overrideContractAddr != nil { - addr = spec.overrideContractAddr - } - err = keeper.ClearContractAdmin(ctx, addr, spec.caller) - require.True(t, spec.expErr.Is(err), "expected %v but got %+v", spec.expErr, err) - if spec.expErr != nil { - return - } - cInfo := keepers.WasmKeeper.GetContractInfo(ctx, addr) - assert.Empty(t, cInfo.Admin) - }) - } -} - -func TestPinCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - - var capturedChecksums []wasmvm.Checksum - mock := wasmtesting.MockWasmer{PinFn: func(checksum wasmvm.Checksum) error { - capturedChecksums = append(capturedChecksums, checksum) - return nil - }} - wasmtesting.MakeInstantiable(&mock) - myCodeID := StoreRandomContract(t, ctx, keepers, &mock).CodeID - require.Equal(t, uint64(1), myCodeID) - em := sdk.NewEventManager() - - // when - gotErr := k.pinCode(ctx.WithEventManager(em), myCodeID) - - // then - require.NoError(t, gotErr) - assert.NotEmpty(t, capturedChecksums) - assert.True(t, k.IsPinnedCode(ctx, myCodeID)) - - // and events - exp := sdk.Events{sdk.NewEvent("pin_code", sdk.NewAttribute("code_id", "1"))} - assert.Equal(t, exp, em.Events()) -} - -func TestUnpinCode(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - - var capturedChecksums []wasmvm.Checksum - mock := wasmtesting.MockWasmer{ - PinFn: func(checksum wasmvm.Checksum) error { - return nil - }, - UnpinFn: func(checksum wasmvm.Checksum) error { - capturedChecksums = append(capturedChecksums, checksum) - return nil - }, - } - wasmtesting.MakeInstantiable(&mock) - myCodeID := StoreRandomContract(t, ctx, keepers, &mock).CodeID - require.Equal(t, uint64(1), myCodeID) - err := k.pinCode(ctx, myCodeID) - require.NoError(t, err) - em := sdk.NewEventManager() - - // when - gotErr := k.unpinCode(ctx.WithEventManager(em), myCodeID) - - // then - require.NoError(t, gotErr) - assert.NotEmpty(t, capturedChecksums) - assert.False(t, k.IsPinnedCode(ctx, myCodeID)) - - // and events - exp := sdk.Events{sdk.NewEvent("unpin_code", sdk.NewAttribute("code_id", "1"))} - assert.Equal(t, exp, em.Events()) -} - -func TestInitializePinnedCodes(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - - var capturedChecksums []wasmvm.Checksum - mock := wasmtesting.MockWasmer{PinFn: func(checksum wasmvm.Checksum) error { - capturedChecksums = append(capturedChecksums, checksum) - return nil - }} - wasmtesting.MakeInstantiable(&mock) - - const testItems = 3 - myCodeIDs := make([]uint64, testItems) - for i := 0; i < testItems; i++ { - myCodeIDs[i] = StoreRandomContract(t, ctx, keepers, &mock).CodeID - require.NoError(t, k.pinCode(ctx, myCodeIDs[i])) - } - capturedChecksums = nil - - // when - gotErr := k.InitializePinnedCodes(ctx) - - // then - require.NoError(t, gotErr) - require.Len(t, capturedChecksums, testItems) - for i, c := range myCodeIDs { - var exp wasmvm.Checksum = k.GetCodeInfo(ctx, c).CodeHash - assert.Equal(t, exp, capturedChecksums[i]) - } -} - -func TestPinnedContractLoops(t *testing.T) { - var capturedChecksums []wasmvm.Checksum - mock := wasmtesting.MockWasmer{PinFn: func(checksum wasmvm.Checksum) error { - capturedChecksums = append(capturedChecksums, checksum) - return nil - }} - wasmtesting.MakeInstantiable(&mock) - - // a pinned contract that calls itself via submessages should terminate with an - // error at some point - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithWasmEngine(&mock)) - k := keepers.WasmKeeper - - example := SeedNewContractInstance(t, ctx, keepers, &mock) - require.NoError(t, k.pinCode(ctx, example.CodeID)) - var loops int - anyMsg := []byte(`{}`) - mock.ExecuteFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - loops++ - return &wasmvmtypes.Response{ - Messages: []wasmvmtypes.SubMsg{ - { - ID: 1, - ReplyOn: wasmvmtypes.ReplyNever, - Msg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Execute: &wasmvmtypes.ExecuteMsg{ - ContractAddr: example.Contract.String(), - Msg: anyMsg, - }, - }, - }, - }, - }, - }, 0, nil - } - ctx = ctx.WithGasMeter(sdk.NewGasMeter(20000)) - require.PanicsWithValue(t, sdk.ErrorOutOfGas{Descriptor: "ReadFlat"}, func() { - _, err := k.execute(ctx, example.Contract, RandomAccountAddress(t), anyMsg, nil) - require.NoError(t, err) - }) - assert.True(t, ctx.GasMeter().IsOutOfGas()) - assert.Greater(t, loops, 2) -} - -func TestNewDefaultWasmVMContractResponseHandler(t *testing.T) { - specs := map[string]struct { - srcData []byte - setup func(m *wasmtesting.MockMsgDispatcher) - expErr bool - expData []byte - expEvts sdk.Events - }{ - "submessage overwrites result when set": { - srcData: []byte("otherData"), - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - return []byte("mySubMsgData"), nil - } - }, - expErr: false, - expData: []byte("mySubMsgData"), - expEvts: sdk.Events{}, - }, - "submessage overwrites result when empty": { - srcData: []byte("otherData"), - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - return []byte(""), nil - } - }, - expErr: false, - expData: []byte(""), - expEvts: sdk.Events{}, - }, - "submessage do not overwrite result when nil": { - srcData: []byte("otherData"), - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - return nil, nil - } - }, - expErr: false, - expData: []byte("otherData"), - expEvts: sdk.Events{}, - }, - "submessage error aborts process": { - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - return nil, errors.New("test - ignore") - } - }, - expErr: true, - }, - "message emit non message events": { - setup: func(m *wasmtesting.MockMsgDispatcher) { - m.DispatchSubmessagesFn = func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - ctx.EventManager().EmitEvent(sdk.NewEvent("myEvent")) - return nil, nil - } - }, - expEvts: sdk.Events{sdk.NewEvent("myEvent")}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var msgs []wasmvmtypes.SubMsg - var mock wasmtesting.MockMsgDispatcher - spec.setup(&mock) - d := NewDefaultWasmVMContractResponseHandler(&mock) - em := sdk.NewEventManager() - - // when - gotData, gotErr := d.Handle(sdk.Context{}.WithEventManager(em), RandomAccountAddress(t), "ibc-port", msgs, spec.srcData) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expData, gotData) - assert.Equal(t, spec.expEvts, em.Events()) - }) - } -} - -func TestReply(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - var mock wasmtesting.MockWasmer - wasmtesting.MakeInstantiable(&mock) - example := SeedNewContractInstance(t, ctx, keepers, &mock) - - specs := map[string]struct { - replyFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - expData []byte - expErr bool - expEvt sdk.Events - }{ - "all good": { - replyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{Data: []byte("foo")}, 1, nil - }, - expData: []byte("foo"), - expEvt: sdk.Events{sdk.NewEvent("reply", sdk.NewAttribute("_contract_address", example.Contract.String()))}, - }, - "with query": { - replyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - bzRsp, err := querier.Query(wasmvmtypes.QueryRequest{ - Bank: &wasmvmtypes.BankQuery{ - Balance: &wasmvmtypes.BalanceQuery{Address: env.Contract.Address, Denom: "stake"}, - }, - }, 10_000*DefaultGasMultiplier) - require.NoError(t, err) - var gotBankRsp wasmvmtypes.BalanceResponse - require.NoError(t, json.Unmarshal(bzRsp, &gotBankRsp)) - assert.Equal(t, wasmvmtypes.BalanceResponse{Amount: wasmvmtypes.NewCoin(0, "stake")}, gotBankRsp) - return &wasmvmtypes.Response{Data: []byte("foo")}, 1, nil - }, - expData: []byte("foo"), - expEvt: sdk.Events{sdk.NewEvent("reply", sdk.NewAttribute("_contract_address", example.Contract.String()))}, - }, - "with query error handled": { - replyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - bzRsp, err := querier.Query(wasmvmtypes.QueryRequest{}, 0) - require.Error(t, err) - assert.Nil(t, bzRsp) - return &wasmvmtypes.Response{Data: []byte("foo")}, 1, nil - }, - expData: []byte("foo"), - expEvt: sdk.Events{sdk.NewEvent("reply", sdk.NewAttribute("_contract_address", example.Contract.String()))}, - }, - "error": { - replyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return nil, 1, errors.New("testing") - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - mock.ReplyFn = spec.replyFn - em := sdk.NewEventManager() - gotData, gotErr := k.reply(ctx.WithEventManager(em), example.Contract, wasmvmtypes.Reply{}) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expData, gotData) - assert.Equal(t, spec.expEvt, em.Events()) - }) - } -} - -func TestQueryIsolation(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - var mock wasmtesting.MockWasmer - wasmtesting.MakeInstantiable(&mock) - example := SeedNewContractInstance(t, ctx, keepers, &mock) - WithQueryHandlerDecorator(func(other WasmVMQueryHandler) WasmVMQueryHandler { - return WasmVMQueryHandlerFn(func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - if request.Custom == nil { - return other.HandleQuery(ctx, caller, request) - } - // here we write to DB which should not be persisted - ctx.KVStore(k.storeKey).Set([]byte(`set_in_query`), []byte(`this_is_allowed`)) - return nil, nil - }) - }).apply(k) - - // when - mock.ReplyFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - _, err := querier.Query(wasmvmtypes.QueryRequest{ - Custom: []byte(`{}`), - }, 10000*DefaultGasMultiplier) - require.NoError(t, err) - return &wasmvmtypes.Response{}, 0, nil - } - em := sdk.NewEventManager() - _, gotErr := k.reply(ctx.WithEventManager(em), example.Contract, wasmvmtypes.Reply{}) - require.NoError(t, gotErr) - assert.Nil(t, ctx.KVStore(k.storeKey).Get([]byte(`set_in_query`))) -} - -func TestSetAccessConfig(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - creatorAddr := RandomAccountAddress(t) - nonCreatorAddr := RandomAccountAddress(t) - const codeID = 1 - - specs := map[string]struct { - authz AuthorizationPolicy - chainPermission types.AccessType - newConfig types.AccessConfig - caller sdk.AccAddress - expErr bool - expEvts map[string]string - }{ - "user with new permissions == chain permissions": { - authz: DefaultAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowEverybody, - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Everybody", - }, - }, - "user with new permissions < chain permissions": { - authz: DefaultAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowNobody, - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Nobody", - }, - }, - "user with new permissions > chain permissions": { - authz: DefaultAuthorizationPolicy{}, - chainPermission: types.AccessTypeNobody, - newConfig: types.AllowEverybody, - caller: creatorAddr, - expErr: true, - }, - "different actor": { - authz: DefaultAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowEverybody, - caller: nonCreatorAddr, - expErr: true, - }, - "gov with new permissions == chain permissions": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowEverybody, - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Everybody", - }, - }, - "gov with new permissions < chain permissions": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowNobody, - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Nobody", - }, - }, - "gov with new permissions > chain permissions": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeNobody, - newConfig: types.AccessTypeOnlyAddress.With(creatorAddr), - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "OnlyAddress", - "authorized_addresses": creatorAddr.String(), - }, - }, - "gov with new permissions > chain permissions - multiple addresses": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeNobody, - newConfig: types.AccessTypeAnyOfAddresses.With(creatorAddr, nonCreatorAddr), - caller: creatorAddr, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "AnyOfAddresses", - "authorized_addresses": creatorAddr.String() + "," + nonCreatorAddr.String(), - }, - }, - "gov without actor": { - authz: GovAuthorizationPolicy{}, - chainPermission: types.AccessTypeEverybody, - newConfig: types.AllowEverybody, - expEvts: map[string]string{ - "code_id": "1", - "code_permission": "Everybody", - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - em := sdk.NewEventManager() - ctx = ctx.WithEventManager(em) - - newParams := types.DefaultParams() - newParams.InstantiateDefaultPermission = spec.chainPermission - err := k.SetParams(ctx, newParams) - require.NoError(t, err) - - k.storeCodeInfo(ctx, codeID, types.NewCodeInfo(nil, creatorAddr, types.AllowNobody)) - // when - gotErr := k.setAccessConfig(ctx, codeID, spec.caller, spec.newConfig, spec.authz) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - // and event emitted - require.Len(t, em.Events(), 1) - assert.Equal(t, "update_code_access_config", em.Events()[0].Type) - assert.Equal(t, spec.expEvts, attrsToStringMap(em.Events()[0].Attributes)) - }) - } -} - -func TestAppendToContractHistory(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - var contractAddr sdk.AccAddress = rand.Bytes(types.ContractAddrLen) - var orderedEntries []types.ContractCodeHistoryEntry - - f := fuzz.New().Funcs(ModelFuzzers...) - for i := 0; i < 10; i++ { - var entry types.ContractCodeHistoryEntry - f.Fuzz(&entry) - keepers.WasmKeeper.appendToContractHistory(ctx, contractAddr, entry) - orderedEntries = append(orderedEntries, entry) - } - // when - gotHistory := keepers.WasmKeeper.GetContractHistory(ctx, contractAddr) - assert.Equal(t, orderedEntries, gotHistory) -} - -func TestCoinBurnerPruneBalances(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - amts := sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - senderAddr := keepers.Faucet.NewFundedRandomAccount(parentCtx, amts...) - - // create vesting account - var vestingAddr sdk.AccAddress = rand.Bytes(types.ContractAddrLen) - msgCreateVestingAccount := vestingtypes.NewMsgCreateVestingAccount(senderAddr, vestingAddr, amts, time.Now().Add(time.Minute).Unix(), false) - _, err := vesting.NewMsgServerImpl(keepers.AccountKeeper, keepers.BankKeeper).CreateVestingAccount(sdk.WrapSDKContext(parentCtx), msgCreateVestingAccount) - require.NoError(t, err) - myVestingAccount := keepers.AccountKeeper.GetAccount(parentCtx, vestingAddr) - require.NotNil(t, myVestingAccount) - - specs := map[string]struct { - setupAcc func(t *testing.T, ctx sdk.Context) authtypes.AccountI - expBalances sdk.Coins - expHandled bool - expErr *errorsmod.Error - }{ - "vesting account - all removed": { - setupAcc: func(t *testing.T, ctx sdk.Context) authtypes.AccountI { return myVestingAccount }, - - expBalances: sdk.NewCoins(), - expHandled: true, - }, - "vesting account with other tokens - only original denoms removed": { - setupAcc: func(t *testing.T, ctx sdk.Context) authtypes.AccountI { - keepers.Faucet.Fund(ctx, vestingAddr, sdk.NewCoin("other", sdk.NewInt(2))) - return myVestingAccount - }, - expBalances: sdk.NewCoins(sdk.NewCoin("other", sdk.NewInt(2))), - expHandled: true, - }, - "non vesting account - not handled": { - setupAcc: func(t *testing.T, ctx sdk.Context) authtypes.AccountI { - return &authtypes.BaseAccount{Address: myVestingAccount.GetAddress().String()} - }, - expBalances: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(100))), - expHandled: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - existingAccount := spec.setupAcc(t, ctx) - // overwrite account in store as in keeper before calling prune - keepers.AccountKeeper.SetAccount(ctx, keepers.AccountKeeper.NewAccountWithAddress(ctx, vestingAddr)) - - // when - noGasCtx := ctx.WithGasMeter(sdk.NewGasMeter(0)) // should not use callers gas - gotHandled, gotErr := NewVestingCoinBurner(keepers.BankKeeper).CleanupExistingAccount(noGasCtx, existingAccount) - // then - if spec.expErr != nil { - require.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expBalances, keepers.BankKeeper.GetAllBalances(ctx, vestingAddr)) - assert.Equal(t, spec.expHandled, gotHandled) - // and no out of gas panic - }) - } -} - -func TestIteratorAllContract(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - example1 := InstantiateHackatomExampleContract(t, ctx, keepers) - example2 := InstantiateHackatomExampleContract(t, ctx, keepers) - example3 := InstantiateHackatomExampleContract(t, ctx, keepers) - example4 := InstantiateHackatomExampleContract(t, ctx, keepers) - - var allContract []string - keepers.WasmKeeper.IterateContractInfo(ctx, func(addr sdk.AccAddress, _ types.ContractInfo) bool { - allContract = append(allContract, addr.String()) - return false - }) - - // IterateContractInfo not ordering - expContracts := []string{example4.Contract.String(), example2.Contract.String(), example1.Contract.String(), example3.Contract.String()} - require.Equal(t, allContract, expContracts) -} - -func TestIteratorContractByCreator(t *testing.T) { - // setup test - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.ContractKeeper - - depositFund := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := DeterministicAccountAddress(t, 1) - keepers.Faucet.Fund(parentCtx, creator, depositFund.Add(depositFund...)...) - mockAddress1 := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - mockAddress2 := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - mockAddress3 := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) - - contract1ID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) - require.NoError(t, err) - - contract2ID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) - require.NoError(t, err) - - initMsgBz := HackatomExampleInitMsg{ - Verifier: mockAddress1, - Beneficiary: mockAddress1, - }.GetBytes(t) - - depositContract := sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(1_000))) - - gotAddr1, _, _ := keepers.ContractKeeper.Instantiate(parentCtx, contract1ID, mockAddress1, nil, initMsgBz, "label", depositContract) - ctx := parentCtx.WithBlockHeight(parentCtx.BlockHeight() + 1) - gotAddr2, _, _ := keepers.ContractKeeper.Instantiate(ctx, contract1ID, mockAddress2, nil, initMsgBz, "label", depositContract) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - gotAddr3, _, _ := keepers.ContractKeeper.Instantiate(ctx, contract1ID, gotAddr1, nil, initMsgBz, "label", depositContract) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - gotAddr4, _, _ := keepers.ContractKeeper.Instantiate(ctx, contract2ID, mockAddress2, nil, initMsgBz, "label", depositContract) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - gotAddr5, _, _ := keepers.ContractKeeper.Instantiate(ctx, contract2ID, mockAddress2, nil, initMsgBz, "label", depositContract) - - specs := map[string]struct { - creatorAddr sdk.AccAddress - contractsAddr []string - }{ - "single contract": { - creatorAddr: mockAddress1, - contractsAddr: []string{gotAddr1.String()}, - }, - "multiple contracts": { - creatorAddr: mockAddress2, - contractsAddr: []string{gotAddr2.String(), gotAddr4.String(), gotAddr5.String()}, - }, - "contractAdress": { - creatorAddr: gotAddr1, - contractsAddr: []string{gotAddr3.String()}, - }, - "no contracts- unknown": { - creatorAddr: mockAddress3, - contractsAddr: nil, - }, - } - - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var allContract []string - keepers.WasmKeeper.IterateContractsByCreator(parentCtx, spec.creatorAddr, func(addr sdk.AccAddress) bool { - allContract = append(allContract, addr.String()) - return false - }) - require.Equal(t, - allContract, - spec.contractsAddr, - ) - }) - } -} - -func TestSetContractAdmin(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities) - k := keepers.WasmKeeper - myAddr := RandomAccountAddress(t) - example := InstantiateReflectExampleContract(t, parentCtx, keepers) - specs := map[string]struct { - newAdmin sdk.AccAddress - caller sdk.AccAddress - policy AuthorizationPolicy - expAdmin string - expErr bool - }{ - "update admin": { - newAdmin: myAddr, - caller: example.CreatorAddr, - policy: DefaultAuthorizationPolicy{}, - expAdmin: myAddr.String(), - }, - "update admin - unauthorized": { - newAdmin: myAddr, - caller: RandomAccountAddress(t), - policy: DefaultAuthorizationPolicy{}, - expErr: true, - }, - "clear admin - default policy": { - caller: example.CreatorAddr, - policy: DefaultAuthorizationPolicy{}, - expAdmin: "", - }, - "clear admin - unauthorized": { - expAdmin: "", - policy: DefaultAuthorizationPolicy{}, - caller: RandomAccountAddress(t), - expErr: true, - }, - "clear admin - gov policy": { - newAdmin: nil, - policy: GovAuthorizationPolicy{}, - caller: example.CreatorAddr, - expAdmin: "", - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - em := sdk.NewEventManager() - ctx = ctx.WithEventManager(em) - gotErr := k.setContractAdmin(ctx, example.Contract, spec.caller, spec.newAdmin, spec.policy) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expAdmin, k.GetContractInfo(ctx, example.Contract).Admin) - // and event emitted - require.Len(t, em.Events(), 1) - assert.Equal(t, "update_contract_admin", em.Events()[0].Type) - exp := map[string]string{ - "_contract_address": example.Contract.String(), - "new_admin_address": spec.expAdmin, - } - assert.Equal(t, exp, attrsToStringMap(em.Events()[0].Attributes)) - }) - } -} - -func attrsToStringMap(attrs []abci.EventAttribute) map[string]string { - r := make(map[string]string, len(attrs)) - for _, v := range attrs { - r[v.Key] = v.Value - } - return r -} diff --git a/x/wasm/keeper/metrics.go b/x/wasm/keeper/metrics.go deleted file mode 100644 index 4c4b959..0000000 --- a/x/wasm/keeper/metrics.go +++ /dev/null @@ -1,72 +0,0 @@ -package keeper - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/prometheus/client_golang/prometheus" -) - -const ( - labelPinned = "pinned" - labelMemory = "memory" - labelFs = "fs" -) - -// metricSource source of wasmvm metrics -type metricSource interface { - GetMetrics() (*wasmvmtypes.Metrics, error) -} - -var _ prometheus.Collector = (*WasmVMMetricsCollector)(nil) - -// WasmVMMetricsCollector custom metrics collector to be used with Prometheus -type WasmVMMetricsCollector struct { - source metricSource - CacheHitsDescr *prometheus.Desc - CacheMissesDescr *prometheus.Desc - CacheElementsDescr *prometheus.Desc - CacheSizeDescr *prometheus.Desc -} - -// NewWasmVMMetricsCollector constructor -func NewWasmVMMetricsCollector(s metricSource) *WasmVMMetricsCollector { - return &WasmVMMetricsCollector{ - source: s, - CacheHitsDescr: prometheus.NewDesc("wasmvm_cache_hits_total", "Total number of cache hits", []string{"type"}, nil), - CacheMissesDescr: prometheus.NewDesc("wasmvm_cache_misses_total", "Total number of cache misses", nil, nil), - CacheElementsDescr: prometheus.NewDesc("wasmvm_cache_elements_total", "Total number of elements in the cache", []string{"type"}, nil), - CacheSizeDescr: prometheus.NewDesc("wasmvm_cache_size_bytes", "Total number of elements in the cache", []string{"type"}, nil), - } -} - -// Register registers all metrics -func (p *WasmVMMetricsCollector) Register(r prometheus.Registerer) { - r.MustRegister(p) -} - -// Describe sends the super-set of all possible descriptors of metrics -func (p *WasmVMMetricsCollector) Describe(descs chan<- *prometheus.Desc) { - descs <- p.CacheHitsDescr - descs <- p.CacheMissesDescr - descs <- p.CacheElementsDescr - descs <- p.CacheSizeDescr -} - -// Collect is called by the Prometheus registry when collecting metrics. -func (p *WasmVMMetricsCollector) Collect(c chan<- prometheus.Metric) { - m, err := p.source.GetMetrics() - if err != nil { - return - } - c <- prometheus.MustNewConstMetric(p.CacheHitsDescr, prometheus.CounterValue, float64(m.HitsPinnedMemoryCache), labelPinned) - c <- prometheus.MustNewConstMetric(p.CacheHitsDescr, prometheus.CounterValue, float64(m.HitsMemoryCache), labelMemory) - c <- prometheus.MustNewConstMetric(p.CacheHitsDescr, prometheus.CounterValue, float64(m.HitsFsCache), labelFs) - c <- prometheus.MustNewConstMetric(p.CacheMissesDescr, prometheus.CounterValue, float64(m.Misses)) - c <- prometheus.MustNewConstMetric(p.CacheElementsDescr, prometheus.GaugeValue, float64(m.ElementsPinnedMemoryCache), labelPinned) - c <- prometheus.MustNewConstMetric(p.CacheElementsDescr, prometheus.GaugeValue, float64(m.ElementsMemoryCache), labelMemory) - c <- prometheus.MustNewConstMetric(p.CacheSizeDescr, prometheus.GaugeValue, float64(m.SizeMemoryCache), labelMemory) - c <- prometheus.MustNewConstMetric(p.CacheSizeDescr, prometheus.GaugeValue, float64(m.SizePinnedMemoryCache), labelPinned) - // Node about fs metrics: - // The number of elements and the size of elements in the file system cache cannot easily be obtained. - // We had to either scan the whole directory of potentially thousands of files or track the values when files are added or removed. - // Such a tracking would need to be on disk such that the values are not cleared when the node is restarted. -} diff --git a/x/wasm/keeper/migrations.go b/x/wasm/keeper/migrations.go deleted file mode 100644 index 7ce1211..0000000 --- a/x/wasm/keeper/migrations.go +++ /dev/null @@ -1,32 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - v1 "github.com/terpnetwork/terp-core/x/wasm/migrations/v1" - v2 "github.com/terpnetwork/terp-core/x/wasm/migrations/v2" - - "github.com/terpnetwork/terp-core/x/wasm/exported" -) - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper Keeper - legacySubspace exported.Subspace -} - -// NewMigrator returns a new Migrator. -func NewMigrator(keeper Keeper, legacySubspace exported.Subspace) Migrator { - return Migrator{keeper: keeper, legacySubspace: legacySubspace} -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - return v1.NewMigrator(m.keeper, m.keeper.addToContractCreatorSecondaryIndex).Migrate1to2(ctx) -} - -// Migrate2to3 migrates the x/wasm module state from the consensus -// version 2 to version 3. -func (m Migrator) Migrate2to3(ctx sdk.Context) error { - return v2.MigrateStore(ctx, m.keeper.storeKey, m.legacySubspace, m.keeper.cdc) -} diff --git a/x/wasm/keeper/migrations_integration_test.go b/x/wasm/keeper/migrations_integration_test.go deleted file mode 100644 index 0e7a033..0000000 --- a/x/wasm/keeper/migrations_integration_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm" -) - -func TestModuleMigrations(t *testing.T) { - wasmApp := app.Setup(t) - upgradeHandler := func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { //nolint:unparam - return wasmApp.ModuleManager.RunMigrations(ctx, wasmApp.Configurator(), fromVM) - } - - specs := map[string]struct { - setup func(ctx sdk.Context) - startVersion uint64 - exp types.Params - }{ - "with legacy params migrated": { - startVersion: 1, - setup: func(ctx sdk.Context) { - params := types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - } - sp, _ := wasmApp.ParamsKeeper.GetSubspace(types.ModuleName) - sp.SetParamSet(ctx, ¶ms) - }, - exp: types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }, - }, - "fresh from genesis": { - startVersion: wasmApp.ModuleManager.GetVersionMap()[types.ModuleName], // latest - setup: func(ctx sdk.Context) {}, - exp: types.DefaultParams(), - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx, _ := wasmApp.BaseApp.NewContext(false, tmproto.Header{}).CacheContext() - spec.setup(ctx) - - fromVM := wasmApp.UpgradeKeeper.GetModuleVersionMap(ctx) - fromVM[wasm.ModuleName] = spec.startVersion - _, err := upgradeHandler(ctx, upgradetypes.Plan{Name: "testing"}, fromVM) - require.NoError(t, err) - - // when - gotVM, err := wasmApp.ModuleManager.RunMigrations(ctx, wasmApp.Configurator(), fromVM) - - // then - require.NoError(t, err) - var expModuleVersion uint64 = 3 - assert.Equal(t, expModuleVersion, gotVM[wasm.ModuleName]) - gotParams := wasmApp.WasmKeeper.GetParams(ctx) - assert.Equal(t, spec.exp, gotParams) - }) - } -} diff --git a/x/wasm/keeper/msg_dispatcher.go b/x/wasm/keeper/msg_dispatcher.go deleted file mode 100644 index 392dbd2..0000000 --- a/x/wasm/keeper/msg_dispatcher.go +++ /dev/null @@ -1,223 +0,0 @@ -package keeper - -import ( - "fmt" - "sort" - "strings" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - abci "github.com/cometbft/cometbft/abci/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// Messenger is an extension point for custom wasmd message handling -type Messenger interface { - // DispatchMsg encodes the wasmVM message and dispatches it. - DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) -} - -// replyer is a subset of keeper that can handle replies to submessages -type replyer interface { - reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) -} - -// MessageDispatcher coordinates message sending and submessage reply/ state commits -type MessageDispatcher struct { - messenger Messenger - keeper replyer -} - -// NewMessageDispatcher constructor -func NewMessageDispatcher(messenger Messenger, keeper replyer) *MessageDispatcher { - return &MessageDispatcher{messenger: messenger, keeper: keeper} -} - -// DispatchMessages sends all messages. -func (d MessageDispatcher) DispatchMessages(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.CosmosMsg) error { - for _, msg := range msgs { - events, _, err := d.messenger.DispatchMsg(ctx, contractAddr, ibcPort, msg) - if err != nil { - return err - } - // redispatch all events, (type sdk.EventTypeMessage will be filtered out in the handler) - ctx.EventManager().EmitEvents(events) - } - return nil -} - -// dispatchMsgWithGasLimit sends a message with gas limit applied -func (d MessageDispatcher) dispatchMsgWithGasLimit(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msg wasmvmtypes.CosmosMsg, gasLimit uint64) (events []sdk.Event, data [][]byte, err error) { - limitedMeter := sdk.NewGasMeter(gasLimit) - subCtx := ctx.WithGasMeter(limitedMeter) - - // catch out of gas panic and just charge the entire gas limit - defer func() { - if r := recover(); r != nil { - // if it's not an OutOfGas error, raise it again - if _, ok := r.(sdk.ErrorOutOfGas); !ok { - // log it to get the original stack trace somewhere (as panic(r) keeps message but stacktrace to here - moduleLogger(ctx).Info("SubMsg rethrowing panic: %#v", r) - panic(r) - } - ctx.GasMeter().ConsumeGas(gasLimit, "Sub-Message OutOfGas panic") - err = errorsmod.Wrap(sdkerrors.ErrOutOfGas, "SubMsg hit gas limit") - } - }() - events, data, err = d.messenger.DispatchMsg(subCtx, contractAddr, ibcPort, msg) - - // make sure we charge the parent what was spent - spent := subCtx.GasMeter().GasConsumed() - ctx.GasMeter().ConsumeGas(spent, "From limited Sub-Message") - - return events, data, err -} - -// DispatchSubmessages builds a sandbox to execute these messages and returns the execution result to the contract -// that dispatched them, both on success as well as failure -func (d MessageDispatcher) DispatchSubmessages(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - var rsp []byte - for _, msg := range msgs { - switch msg.ReplyOn { - case wasmvmtypes.ReplySuccess, wasmvmtypes.ReplyError, wasmvmtypes.ReplyAlways, wasmvmtypes.ReplyNever: - default: - return nil, errorsmod.Wrap(types.ErrInvalid, "replyOn value") - } - // first, we build a sub-context which we can use inside the submessages - subCtx, commit := ctx.CacheContext() - em := sdk.NewEventManager() - subCtx = subCtx.WithEventManager(em) - - // check how much gas left locally, optionally wrap the gas meter - gasRemaining := ctx.GasMeter().Limit() - ctx.GasMeter().GasConsumed() - limitGas := msg.GasLimit != nil && (*msg.GasLimit < gasRemaining) - - var err error - var events []sdk.Event - var data [][]byte - if limitGas { - events, data, err = d.dispatchMsgWithGasLimit(subCtx, contractAddr, ibcPort, msg.Msg, *msg.GasLimit) - } else { - events, data, err = d.messenger.DispatchMsg(subCtx, contractAddr, ibcPort, msg.Msg) - } - - // if it succeeds, commit state changes from submessage, and pass on events to Event Manager - var filteredEvents []sdk.Event - if err == nil { - commit() - filteredEvents = filterEvents(append(em.Events(), events...)) - ctx.EventManager().EmitEvents(filteredEvents) - if msg.Msg.Wasm == nil { - filteredEvents = []sdk.Event{} - } else { - for _, e := range filteredEvents { - attributes := e.Attributes - sort.SliceStable(attributes, func(i, j int) bool { - return strings.Compare(attributes[i].Key, attributes[j].Key) < 0 - }) - } - } - } // on failure, revert state from sandbox, and ignore events (just skip doing the above) - - // we only callback if requested. Short-circuit here the cases we don't want to - if (msg.ReplyOn == wasmvmtypes.ReplySuccess || msg.ReplyOn == wasmvmtypes.ReplyNever) && err != nil { - return nil, err - } - if msg.ReplyOn == wasmvmtypes.ReplyNever || (msg.ReplyOn == wasmvmtypes.ReplyError && err == nil) { - continue - } - - // otherwise, we create a SubMsgResult and pass it into the calling contract - var result wasmvmtypes.SubMsgResult - if err == nil { - // just take the first one for now if there are multiple sub-sdk messages - // and safely return nothing if no data - var responseData []byte - if len(data) > 0 { - responseData = data[0] - } - result = wasmvmtypes.SubMsgResult{ - Ok: &wasmvmtypes.SubMsgResponse{ - Events: sdkEventsToWasmVMEvents(filteredEvents), - Data: responseData, - }, - } - } else { - // Issue #759 - we don't return error string for worries of non-determinism - moduleLogger(ctx).Info("Redacting submessage error", "cause", err) - result = wasmvmtypes.SubMsgResult{ - Err: redactError(err).Error(), - } - } - - // now handle the reply, we use the parent context, and abort on error - reply := wasmvmtypes.Reply{ - ID: msg.ID, - Result: result, - } - - // we can ignore any result returned as there is nothing to do with the data - // and the events are already in the ctx.EventManager() - rspData, err := d.keeper.reply(ctx, contractAddr, reply) - switch { - case err != nil: - return nil, errorsmod.Wrap(err, "reply") - case rspData != nil: - rsp = rspData - } - } - return rsp, nil -} - -// Issue #759 - we don't return error string for worries of non-determinism -func redactError(err error) error { - // Do not redact system errors - // SystemErrors must be created in x/wasm and we can ensure determinism - if wasmvmtypes.ToSystemError(err) != nil { - return err - } - - // FIXME: do we want to hardcode some constant string mappings here as well? - // Or better document them? (SDK error string may change on a patch release to fix wording) - // sdk/11 is out of gas - // sdk/5 is insufficient funds (on bank send) - // (we can theoretically redact less in the future, but this is a first step to safety) - codespace, code, _ := errorsmod.ABCIInfo(err, false) - return fmt.Errorf("codespace: %s, code: %d", codespace, code) -} - -func filterEvents(events []sdk.Event) []sdk.Event { - // pre-allocate space for efficiency - res := make([]sdk.Event, 0, len(events)) - for _, ev := range events { - if ev.Type != "message" { - res = append(res, ev) - } - } - return res -} - -func sdkEventsToWasmVMEvents(events []sdk.Event) []wasmvmtypes.Event { - res := make([]wasmvmtypes.Event, len(events)) - for i, ev := range events { - res[i] = wasmvmtypes.Event{ - Type: ev.Type, - Attributes: sdkAttributesToWasmVMAttributes(ev.Attributes), - } - } - return res -} - -func sdkAttributesToWasmVMAttributes(attrs []abci.EventAttribute) []wasmvmtypes.EventAttribute { - res := make([]wasmvmtypes.EventAttribute, len(attrs)) - for i, attr := range attrs { - res[i] = wasmvmtypes.EventAttribute{ - Key: attr.Key, - Value: attr.Value, - } - } - return res -} diff --git a/x/wasm/keeper/msg_dispatcher_test.go b/x/wasm/keeper/msg_dispatcher_test.go deleted file mode 100644 index 436ad6d..0000000 --- a/x/wasm/keeper/msg_dispatcher_test.go +++ /dev/null @@ -1,430 +0,0 @@ -package keeper - -import ( - "errors" - "fmt" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" -) - -func TestDispatchSubmessages(t *testing.T) { - noReplyCalled := &mockReplyer{} - var anyGasLimit uint64 = 1 - specs := map[string]struct { - msgs []wasmvmtypes.SubMsg - replyer *mockReplyer - msgHandler *wasmtesting.MockMessageHandler - expErr bool - expData []byte - expCommits []bool - expEvents sdk.Events - }{ - "no reply on error without error": { - msgs: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyError}}, - replyer: noReplyCalled, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{[]byte("myData")}, nil - }, - }, - expCommits: []bool{true}, - }, - "no reply on success without success": { - msgs: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplySuccess}}, - replyer: noReplyCalled, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("test, ignore") - }, - }, - expCommits: []bool{false}, - expErr: true, - }, - "reply on success - received": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplySuccess, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return []byte("myReplyData"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{[]byte("myData")}, nil - }, - }, - expData: []byte("myReplyData"), - expCommits: []bool{true}, - }, - "reply on error - handled": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplyError, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return []byte("myReplyData"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("my error") - }, - }, - expData: []byte("myReplyData"), - expCommits: []bool{false}, - }, - "with reply events": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplySuccess, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - ctx.EventManager().EmitEvent(sdk.NewEvent("wasm-reply")) - return []byte("myReplyData"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - myEvents := []sdk.Event{{Type: "myEvent", Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}}} - return myEvents, [][]byte{[]byte("myData")}, nil - }, - }, - expData: []byte("myReplyData"), - expCommits: []bool{true}, - expEvents: []sdk.Event{ - { - Type: "myEvent", - Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}, - }, - sdk.NewEvent("wasm-reply"), - }, - }, - "with context events - released on commit": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplyNever, - }}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - myEvents := []sdk.Event{{Type: "myEvent", Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}}} - ctx.EventManager().EmitEvents(myEvents) - return nil, nil, nil - }, - }, - expCommits: []bool{true}, - expEvents: []sdk.Event{{ - Type: "myEvent", - Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}, - }}, - }, - "with context events - discarded on failure": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplyNever, - }}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - myEvents := []sdk.Event{{Type: "myEvent", Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}}} - ctx.EventManager().EmitEvents(myEvents) - return nil, nil, errors.New("testing") - }, - }, - expCommits: []bool{false}, - expErr: true, - }, - "reply returns error": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplySuccess, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return nil, errors.New("reply failed") - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, nil - }, - }, - expCommits: []bool{false}, - expErr: true, - }, - "with gas limit - out of gas": { - msgs: []wasmvmtypes.SubMsg{{ - GasLimit: &anyGasLimit, - ReplyOn: wasmvmtypes.ReplyError, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return []byte("myReplyData"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - ctx.GasMeter().ConsumeGas(sdk.Gas(101), "testing") - return nil, [][]byte{[]byte("someData")}, nil - }, - }, - expData: []byte("myReplyData"), - expCommits: []bool{false}, - }, - "with gas limit - within limit no error": { - msgs: []wasmvmtypes.SubMsg{{ - GasLimit: &anyGasLimit, - ReplyOn: wasmvmtypes.ReplyError, - }}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - ctx.GasMeter().ConsumeGas(sdk.Gas(1), "testing") - return nil, [][]byte{[]byte("someData")}, nil - }, - }, - expCommits: []bool{true}, - }, - "never reply - with nil response": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyNever}, {ID: 2, ReplyOn: wasmvmtypes.ReplyNever}}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{nil}, nil - }, - }, - expCommits: []bool{true, true}, - }, - "never reply - with any non nil response": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyNever}, {ID: 2, ReplyOn: wasmvmtypes.ReplyNever}}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{{}}, nil - }, - }, - expCommits: []bool{true, true}, - }, - "never reply - with error": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyNever}, {ID: 2, ReplyOn: wasmvmtypes.ReplyNever}}, - replyer: &mockReplyer{}, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, [][]byte{{}}, errors.New("testing") - }, - }, - expCommits: []bool{false, false}, - expErr: true, - }, - "multiple msg - last reply returned": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyError}, {ID: 2, ReplyOn: wasmvmtypes.ReplyError}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return []byte(fmt.Sprintf("myReplyData:%d", reply.ID)), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("my error") - }, - }, - expData: []byte("myReplyData:2"), - expCommits: []bool{false, false}, - }, - "multiple msg - last non nil reply returned": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyError}, {ID: 2, ReplyOn: wasmvmtypes.ReplyError}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if reply.ID == 2 { - return nil, nil - } - return []byte("myReplyData:1"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("my error") - }, - }, - expData: []byte("myReplyData:1"), - expCommits: []bool{false, false}, - }, - "multiple msg - empty reply can overwrite result": { - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyError}, {ID: 2, ReplyOn: wasmvmtypes.ReplyError}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if reply.ID == 2 { - return []byte{}, nil - } - return []byte("myReplyData:1"), nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("my error") - }, - }, - expData: []byte{}, - expCommits: []bool{false, false}, - }, - "message event filtered without reply": { - msgs: []wasmvmtypes.SubMsg{{ - ReplyOn: wasmvmtypes.ReplyNever, - }}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - return nil, errors.New("should never be called") - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - myEvents := []sdk.Event{ - sdk.NewEvent("message"), - sdk.NewEvent("execute", sdk.NewAttribute("foo", "bar")), - } - return myEvents, [][]byte{[]byte("myData")}, nil - }, - }, - expData: nil, - expCommits: []bool{true}, - expEvents: []sdk.Event{sdk.NewEvent("execute", sdk.NewAttribute("foo", "bar"))}, - }, - "wasm reply gets proper events": { - // put fake wasmmsg in here to show where it comes from - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyAlways, Msg: wasmvmtypes.CosmosMsg{Wasm: &wasmvmtypes.WasmMsg{}}}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if reply.Result.Err != "" { - return nil, errors.New(reply.Result.Err) - } - res := reply.Result.Ok - - // ensure the input events are what we expect - // I didn't use require.Equal() to act more like a contract... but maybe that would be better - if len(res.Events) != 2 { - return nil, fmt.Errorf("event count: %#v", res.Events) - } - if res.Events[0].Type != "execute" { - return nil, fmt.Errorf("event0: %#v", res.Events[0]) - } - if res.Events[1].Type != "wasm" { - return nil, fmt.Errorf("event1: %#v", res.Events[1]) - } - - // let's add a custom event here and see if it makes it out - ctx.EventManager().EmitEvent(sdk.NewEvent("wasm-reply")) - - // update data from what we got in - return res.Data, nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - events = []sdk.Event{ - sdk.NewEvent("message", sdk.NewAttribute("_contract_address", contractAddr.String())), - // we don't know what the contarctAddr will be so we can't use it in the final tests - sdk.NewEvent("execute", sdk.NewAttribute("_contract_address", "placeholder-random-addr")), - sdk.NewEvent("wasm", sdk.NewAttribute("random", "data")), - } - return events, [][]byte{[]byte("subData")}, nil - }, - }, - expData: []byte("subData"), - expCommits: []bool{true}, - expEvents: []sdk.Event{ - sdk.NewEvent("execute", sdk.NewAttribute("_contract_address", "placeholder-random-addr")), - sdk.NewEvent("wasm", sdk.NewAttribute("random", "data")), - sdk.NewEvent("wasm-reply"), - }, - }, - "non-wasm reply events get filtered": { - // show events from a stargate message gets filtered out - msgs: []wasmvmtypes.SubMsg{{ID: 1, ReplyOn: wasmvmtypes.ReplyAlways, Msg: wasmvmtypes.CosmosMsg{Stargate: &wasmvmtypes.StargateMsg{}}}}, - replyer: &mockReplyer{ - replyFn: func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if reply.Result.Err != "" { - return nil, errors.New(reply.Result.Err) - } - res := reply.Result.Ok - - // ensure the input events are what we expect - // I didn't use require.Equal() to act more like a contract... but maybe that would be better - if len(res.Events) != 0 { - return nil, errors.New("events not filtered out") - } - - // let's add a custom event here and see if it makes it out - ctx.EventManager().EmitEvent(sdk.NewEvent("stargate-reply")) - - // update data from what we got in - return res.Data, nil - }, - }, - msgHandler: &wasmtesting.MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - events = []sdk.Event{ - // this is filtered out - sdk.NewEvent("message", sdk.NewAttribute("stargate", "something-something")), - // we still emit this to the client, but not the contract - sdk.NewEvent("non-determinstic"), - } - return events, [][]byte{[]byte("subData")}, nil - }, - }, - expData: []byte("subData"), - expCommits: []bool{true}, - expEvents: []sdk.Event{ - sdk.NewEvent("non-determinstic"), - // the event from reply is also exposed - sdk.NewEvent("stargate-reply"), - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var mockStore wasmtesting.MockCommitMultiStore - em := sdk.NewEventManager() - ctx := sdk.Context{}.WithMultiStore(&mockStore). - WithGasMeter(sdk.NewGasMeter(100)). - WithEventManager(em).WithLogger(log.TestingLogger()) - d := NewMessageDispatcher(spec.msgHandler, spec.replyer) - - // run the test - gotData, gotErr := d.DispatchSubmessages(ctx, RandomAccountAddress(t), "any_port", spec.msgs) - if spec.expErr { - require.Error(t, gotErr) - assert.Empty(t, em.Events()) - return - } - - // if we don't expect an error, we should get no error - require.NoError(t, gotErr) - assert.Equal(t, spec.expData, gotData) - - // ensure the commits are what we expect - assert.Equal(t, spec.expCommits, mockStore.Committed) - if len(spec.expEvents) == 0 { - assert.Empty(t, em.Events()) - } else { - assert.Equal(t, spec.expEvents, em.Events()) - } - }) - } -} - -type mockReplyer struct { - replyFn func(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) -} - -func (m mockReplyer) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply wasmvmtypes.Reply) ([]byte, error) { - if m.replyFn == nil { - panic("not expected to be called") - } - return m.replyFn(ctx, contractAddress, reply) -} diff --git a/x/wasm/keeper/msg_server.go b/x/wasm/keeper/msg_server.go deleted file mode 100644 index 66d1cd6..0000000 --- a/x/wasm/keeper/msg_server.go +++ /dev/null @@ -1,365 +0,0 @@ -package keeper - -import ( - "context" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.MsgServer = msgServer{} - -// grpc message server implementation -type msgServer struct { - keeper *Keeper -} - -// NewMsgServerImpl default constructor -func NewMsgServerImpl(k *Keeper) types.MsgServer { - return &msgServer{keeper: k} -} - -// StoreCode stores a new wasm code on chain -func (m msgServer) StoreCode(goCtx context.Context, msg *types.MsgStoreCode) (*types.MsgStoreCodeResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - codeID, checksum, err := m.keeper.create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission, policy) - if err != nil { - return nil, err - } - - return &types.MsgStoreCodeResponse{ - CodeID: codeID, - Checksum: checksum, - }, nil -} - -// InstantiateContract instantiate a new contract with classic sequence based address generation -func (m msgServer) InstantiateContract(goCtx context.Context, msg *types.MsgInstantiateContract) (*types.MsgInstantiateContractResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(goCtx) - - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - var adminAddr sdk.AccAddress - if msg.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - contractAddr, data, err := m.keeper.instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds, m.keeper.ClassicAddressGenerator(), policy) - if err != nil { - return nil, err - } - - return &types.MsgInstantiateContractResponse{ - Address: contractAddr.String(), - Data: data, - }, nil -} - -// InstantiateContract2 instantiate a new contract with predicatable address generated -func (m msgServer) InstantiateContract2(goCtx context.Context, msg *types.MsgInstantiateContract2) (*types.MsgInstantiateContract2Response, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(goCtx) - - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - var adminAddr sdk.AccAddress - if msg.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - addrGenerator := PredicableAddressGenerator(senderAddr, msg.Salt, msg.Msg, msg.FixMsg) - - contractAddr, data, err := m.keeper.instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds, addrGenerator, policy) - if err != nil { - return nil, err - } - - return &types.MsgInstantiateContract2Response{ - Address: contractAddr.String(), - Data: data, - }, nil -} - -func (m msgServer) ExecuteContract(goCtx context.Context, msg *types.MsgExecuteContract) (*types.MsgExecuteContractResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - - data, err := m.keeper.execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) - if err != nil { - return nil, err - } - - return &types.MsgExecuteContractResponse{ - Data: data, - }, nil -} - -func (m msgServer) MigrateContract(goCtx context.Context, msg *types.MsgMigrateContract) (*types.MsgMigrateContractResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - data, err := m.keeper.migrate(ctx, contractAddr, senderAddr, msg.CodeID, msg.Msg, policy) - if err != nil { - return nil, err - } - - return &types.MsgMigrateContractResponse{ - Data: data, - }, nil -} - -func (m msgServer) UpdateAdmin(goCtx context.Context, msg *types.MsgUpdateAdmin) (*types.MsgUpdateAdminResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - newAdminAddr, err := sdk.AccAddressFromBech32(msg.NewAdmin) - if err != nil { - return nil, errorsmod.Wrap(err, "new admin") - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - if err := m.keeper.setContractAdmin(ctx, contractAddr, senderAddr, newAdminAddr, policy); err != nil { - return nil, err - } - - return &types.MsgUpdateAdminResponse{}, nil -} - -func (m msgServer) ClearAdmin(goCtx context.Context, msg *types.MsgClearAdmin) (*types.MsgClearAdminResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - - policy := m.selectAuthorizationPolicy(msg.Sender) - - if err := m.keeper.setContractAdmin(ctx, contractAddr, senderAddr, nil, policy); err != nil { - return nil, err - } - - return &types.MsgClearAdminResponse{}, nil -} - -func (m msgServer) UpdateInstantiateConfig(goCtx context.Context, msg *types.MsgUpdateInstantiateConfig) (*types.MsgUpdateInstantiateConfigResponse, error) { - if err := msg.ValidateBasic(); err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(goCtx) - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - policy := m.selectAuthorizationPolicy(msg.Sender) - - if err := m.keeper.setAccessConfig(ctx, msg.CodeID, senderAddr, *msg.NewInstantiatePermission, policy); err != nil { - return nil, err - } - - return &types.MsgUpdateInstantiateConfigResponse{}, nil -} - -// UpdateParams updates the module parameters -func (m msgServer) UpdateParams(goCtx context.Context, req *types.MsgUpdateParams) (*types.MsgUpdateParamsResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - authority := m.keeper.GetAuthority() - if authority != req.Authority { - return nil, errorsmod.Wrapf(types.ErrInvalid, "invalid authority; expected %s, got %s", authority, req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - if err := m.keeper.SetParams(ctx, req.Params); err != nil { - return nil, err - } - - return &types.MsgUpdateParamsResponse{}, nil -} - -// PinCodes pins a set of code ids in the wasmvm cache. -func (m msgServer) PinCodes(goCtx context.Context, req *types.MsgPinCodes) (*types.MsgPinCodesResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - - authority := m.keeper.GetAuthority() - if authority != req.Authority { - return nil, errorsmod.Wrapf(types.ErrInvalid, "invalid authority; expected %s, got %s", authority, req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - for _, codeID := range req.CodeIDs { - if err := m.keeper.pinCode(ctx, codeID); err != nil { - return nil, err - } - } - - return &types.MsgPinCodesResponse{}, nil -} - -// UnpinCodes unpins a set of code ids in the wasmvm cache. -func (m msgServer) UnpinCodes(goCtx context.Context, req *types.MsgUnpinCodes) (*types.MsgUnpinCodesResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - - authority := m.keeper.GetAuthority() - if authority != req.Authority { - return nil, errorsmod.Wrapf(types.ErrInvalid, "invalid authority; expected %s, got %s", authority, req.Authority) - } - - ctx := sdk.UnwrapSDKContext(goCtx) - for _, codeID := range req.CodeIDs { - if err := m.keeper.unpinCode(ctx, codeID); err != nil { - return nil, err - } - } - - return &types.MsgUnpinCodesResponse{}, nil -} - -// SudoContract calls sudo on a contract. -func (m msgServer) SudoContract(goCtx context.Context, req *types.MsgSudoContract) (*types.MsgSudoContractResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - authority := m.keeper.GetAuthority() - if authority != req.Authority { - return nil, errorsmod.Wrapf(types.ErrInvalid, "invalid authority; expected %s, got %s", authority, req.Authority) - } - - contractAddr, err := sdk.AccAddressFromBech32(req.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "contract") - } - - ctx := sdk.UnwrapSDKContext(goCtx) - data, err := m.keeper.Sudo(ctx, contractAddr, req.Msg) - if err != nil { - return nil, err - } - - return &types.MsgSudoContractResponse{Data: data}, nil -} - -// StoreAndInstantiateContract stores and instantiates the contract. -func (m msgServer) StoreAndInstantiateContract(goCtx context.Context, req *types.MsgStoreAndInstantiateContract) (*types.MsgStoreAndInstantiateContractResponse, error) { - if err := req.ValidateBasic(); err != nil { - return nil, err - } - - authorityAddr, err := sdk.AccAddressFromBech32(req.Authority) - if err != nil { - return nil, errorsmod.Wrap(err, "authority") - } - - if err = req.ValidateBasic(); err != nil { - return nil, err - } - - var adminAddr sdk.AccAddress - if req.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(req.Admin); err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - } - - ctx := sdk.UnwrapSDKContext(goCtx) - policy := m.selectAuthorizationPolicy(req.Authority) - - codeID, _, err := m.keeper.create(ctx, authorityAddr, req.WASMByteCode, req.InstantiatePermission, policy) - if err != nil { - return nil, err - } - - contractAddr, data, err := m.keeper.instantiate(ctx, codeID, authorityAddr, adminAddr, req.Msg, req.Label, req.Funds, m.keeper.ClassicAddressGenerator(), policy) - if err != nil { - return nil, err - } - - return &types.MsgStoreAndInstantiateContractResponse{ - Address: contractAddr.String(), - Data: data, - }, nil -} - -func (m msgServer) selectAuthorizationPolicy(actor string) AuthorizationPolicy { - if actor == m.keeper.GetAuthority() { - return GovAuthorizationPolicy{} - } - return DefaultAuthorizationPolicy{} -} diff --git a/x/wasm/keeper/msg_server_integration_test.go b/x/wasm/keeper/msg_server_integration_test.go deleted file mode 100644 index 11003c0..0000000 --- a/x/wasm/keeper/msg_server_integration_test.go +++ /dev/null @@ -1,855 +0,0 @@ -package keeper_test - -import ( - "crypto/sha256" - _ "embed" - "encoding/json" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -//go:embed testdata/reflect.wasm -var wasmContract []byte - -//go:embed testdata/hackatom.wasm -var hackatomContract []byte - -func TestStoreCode(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - }) - - // when - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - - // then - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - assert.Equal(t, uint64(1), result.CodeID) - expHash := sha256.Sum256(wasmContract) - assert.Equal(t, expHash[:], result.Checksum) - // and - info := wasmApp.WasmKeeper.GetCodeInfo(ctx, 1) - assert.NotNil(t, info) - assert.Equal(t, expHash[:], info.CodeHash) - assert.Equal(t, sender.String(), info.Creator) - assert.Equal(t, types.DefaultParams().InstantiateDefaultPermission.With(sender), info.InstantiateConfig) -} - -func TestUpdateParams(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - oneAddressAccessConfig = types.AccessTypeOnlyAddress.With(myAddress) - govAuthority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - src types.MsgUpdateParams - expUploadConfig types.AccessConfig - expInstantiateType types.AccessType - }{ - "update upload permission param": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeEverybody, - }, - }, - expUploadConfig: types.AllowNobody, - expInstantiateType: types.AccessTypeEverybody, - }, - "update upload permission with same as current value": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: types.AccessTypeEverybody, - }, - }, - expUploadConfig: types.AllowEverybody, - expInstantiateType: types.AccessTypeEverybody, - }, - "update upload permission param with address": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: oneAddressAccessConfig, - InstantiateDefaultPermission: types.AccessTypeEverybody, - }, - }, - expUploadConfig: oneAddressAccessConfig, - expInstantiateType: types.AccessTypeEverybody, - }, - "update instantiate param": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }, - }, - expUploadConfig: types.AllowEverybody, - expInstantiateType: types.AccessTypeNobody, - }, - "update instantiate param as default": { - src: types.MsgUpdateParams{ - Authority: govAuthority, - Params: types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: types.AccessTypeEverybody, - }, - }, - expUploadConfig: types.AllowEverybody, - expInstantiateType: types.AccessTypeEverybody, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - err := wasmApp.WasmKeeper.SetParams(ctx, types.DefaultParams()) - require.NoError(t, err) - - // when - rsp, err := wasmApp.MsgServiceRouter().Handler(&spec.src)(ctx, &spec.src) - require.NoError(t, err) - var result types.MsgUpdateParamsResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // then - assert.True(t, spec.expUploadConfig.Equals(wasmApp.WasmKeeper.GetParams(ctx).CodeUploadAccess), - "got %#v not %#v", wasmApp.WasmKeeper.GetParams(ctx).CodeUploadAccess, spec.expUploadConfig) - assert.Equal(t, spec.expInstantiateType, wasmApp.WasmKeeper.GetParams(ctx).InstantiateDefaultPermission) - }) - } -} - -func TestPinCodes(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can pin codes": { - addr: authority, - expErr: false, - }, - "other address cannot pin codes": { - addr: myAddress.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - require.False(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - - // when - msgPinCodes := &types.MsgPinCodes{ - Authority: spec.addr, - CodeIDs: []uint64{result.CodeID}, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgPinCodes)(ctx, msgPinCodes) - - // then - if spec.expErr { - require.Error(t, err) - assert.False(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - } else { - require.NoError(t, err) - assert.True(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - } - }) - } -} - -func TestUnpinCodes(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can unpin codes": { - addr: authority, - expErr: false, - }, - "other address cannot unpin codes": { - addr: myAddress.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // pin code - msgPin := &types.MsgPinCodes{ - Authority: authority, - CodeIDs: []uint64{result.CodeID}, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgPin)(ctx, msgPin) - require.NoError(t, err) - assert.True(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - - // when - msgUnpinCodes := &types.MsgUnpinCodes{ - Authority: spec.addr, - CodeIDs: []uint64{result.CodeID}, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgUnpinCodes)(ctx, msgUnpinCodes) - - // then - if spec.expErr { - require.Error(t, err) - assert.True(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - } else { - require.NoError(t, err) - assert.False(t, wasmApp.WasmKeeper.IsPinnedCode(ctx, result.CodeID)) - } - }) - } -} - -func TestSudoContract(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - type StealMsg struct { - Recipient string `json:"recipient"` - Amount []sdk.Coin `json:"amount"` - } - - stealMsg := struct { - Steal StealMsg `json:"steal_funds"` - }{Steal: StealMsg{ - Recipient: myAddress.String(), - Amount: []sdk.Coin{}, - }} - - stealMsgBz, err := json.Marshal(stealMsg) - require.NoError(t, err) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can call sudo on a contract": { - addr: authority, - expErr: false, - }, - "other address cannot call sudo on a contract": { - addr: myAddress.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = hackatomContract - m.Sender = sender.String() - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var storeCodeResponse types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &storeCodeResponse)) - - // instantiate contract - initMsg := keeper.HackatomExampleInitMsg{ - Verifier: sender, - Beneficiary: myAddress, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - msgInstantiate := &types.MsgInstantiateContract{ - Sender: sender.String(), - Admin: sender.String(), - CodeID: storeCodeResponse.CodeID, - Label: "test", - Msg: initMsgBz, - Funds: sdk.Coins{}, - } - rsp, err = wasmApp.MsgServiceRouter().Handler(msgInstantiate)(ctx, msgInstantiate) - require.NoError(t, err) - var instantiateResponse types.MsgInstantiateContractResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &instantiateResponse)) - - // when - msgSudoContract := &types.MsgSudoContract{ - Authority: spec.addr, - Msg: stealMsgBz, - Contract: instantiateResponse.Address, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgSudoContract)(ctx, msgSudoContract) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestStoreAndInstantiateContract(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - permission *types.AccessConfig - expErr bool - }{ - "authority can store and instantiate a contract when permission is nobody": { - addr: authority, - permission: &types.AllowNobody, - expErr: false, - }, - "other address cannot store and instantiate a contract when permission is nobody": { - addr: myAddress.String(), - permission: &types.AllowNobody, - expErr: true, - }, - "authority can store and instantiate a contract when permission is everybody": { - addr: authority, - permission: &types.AllowEverybody, - expErr: false, - }, - "other address can store and instantiate a contract when permission is everybody": { - addr: myAddress.String(), - permission: &types.AllowEverybody, - expErr: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // when - msg := &types.MsgStoreAndInstantiateContract{ - Authority: spec.addr, - WASMByteCode: wasmContract, - InstantiatePermission: spec.permission, - Admin: myAddress.String(), - UnpinCode: false, - Label: "test", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - _, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestUpdateAdmin(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - _, _, otherAddr = testdata.KeyTestPubAddr() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can update admin": { - addr: authority, - expErr: false, - }, - "admin can update admin": { - addr: myAddress.String(), - expErr: false, - }, - "other address cannot update admin": { - addr: otherAddr.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - _, _, newAdmin := testdata.KeyTestPubAddr() - - // setup - msg := &types.MsgStoreAndInstantiateContract{ - Authority: spec.addr, - WASMByteCode: wasmContract, - InstantiatePermission: &types.AllowEverybody, - Admin: myAddress.String(), - UnpinCode: false, - Label: "test", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var storeAndInstantiateResponse types.MsgStoreAndInstantiateContractResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &storeAndInstantiateResponse)) - - // when - msgUpdateAdmin := &types.MsgUpdateAdmin{ - Sender: spec.addr, - NewAdmin: newAdmin.String(), - Contract: storeAndInstantiateResponse.Address, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgUpdateAdmin)(ctx, msgUpdateAdmin) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestClearAdmin(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - _, _, otherAddr = testdata.KeyTestPubAddr() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can clear admin": { - addr: authority, - expErr: false, - }, - "admin can clear admin": { - addr: myAddress.String(), - expErr: false, - }, - "other address cannot clear admin": { - addr: otherAddr.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - msg := &types.MsgStoreAndInstantiateContract{ - Authority: spec.addr, - WASMByteCode: wasmContract, - InstantiatePermission: &types.AllowEverybody, - Admin: myAddress.String(), - UnpinCode: false, - Label: "test", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var storeAndInstantiateResponse types.MsgStoreAndInstantiateContractResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &storeAndInstantiateResponse)) - - // when - msgClearAdmin := &types.MsgClearAdmin{ - Sender: spec.addr, - Contract: storeAndInstantiateResponse.Address, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgClearAdmin)(ctx, msgClearAdmin) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestMigrateContract(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - _, _, otherAddr = testdata.KeyTestPubAddr() - ) - - specs := map[string]struct { - addr string - expErr bool - }{ - "authority can migrate a contract": { - addr: authority, - expErr: false, - }, - "admin can migrate a contract": { - addr: myAddress.String(), - expErr: false, - }, - "other address cannot migrate a contract": { - addr: otherAddr.String(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = hackatomContract - m.Sender = sender.String() - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var storeCodeResponse types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &storeCodeResponse)) - - // instantiate contract - initMsg := keeper.HackatomExampleInitMsg{ - Verifier: sender, - Beneficiary: myAddress, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - msgInstantiate := &types.MsgInstantiateContract{ - Sender: sender.String(), - Admin: myAddress.String(), - CodeID: storeCodeResponse.CodeID, - Label: "test", - Msg: initMsgBz, - Funds: sdk.Coins{}, - } - rsp, err = wasmApp.MsgServiceRouter().Handler(msgInstantiate)(ctx, msgInstantiate) - require.NoError(t, err) - var instantiateResponse types.MsgInstantiateContractResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &instantiateResponse)) - - // when - migMsg := struct { - Verifier sdk.AccAddress `json:"verifier"` - }{Verifier: myAddress} - migMsgBz, err := json.Marshal(migMsg) - require.NoError(t, err) - msgMigrateContract := &types.MsgMigrateContract{ - Sender: spec.addr, - Msg: migMsgBz, - Contract: instantiateResponse.Address, - CodeID: storeCodeResponse.CodeID, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgMigrateContract)(ctx, msgMigrateContract) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestInstantiateContract(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - permission *types.AccessConfig - expErr bool - }{ - "authority can instantiate a contract when permission is nobody": { - addr: authority, - permission: &types.AllowNobody, - expErr: false, - }, - "other address cannot instantiate a contract when permission is nobody": { - addr: myAddress.String(), - permission: &types.AllowNobody, - expErr: true, - }, - "authority can instantiate a contract when permission is everybody": { - addr: authority, - permission: &types.AllowEverybody, - expErr: false, - }, - "other address can instantiate a contract when permission is everybody": { - addr: myAddress.String(), - permission: &types.AllowEverybody, - expErr: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - m.InstantiatePermission = spec.permission - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // when - msgInstantiate := &types.MsgInstantiateContract{ - Sender: spec.addr, - Admin: myAddress.String(), - CodeID: result.CodeID, - Label: "test", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgInstantiate)(ctx, msgInstantiate) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestInstantiateContract2(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - salt string - permission *types.AccessConfig - expErr bool - }{ - "authority can instantiate a contract when permission is nobody": { - addr: authority, - permission: &types.AllowNobody, - salt: "salt1", - expErr: false, - }, - "other address cannot instantiate a contract when permission is nobody": { - addr: myAddress.String(), - permission: &types.AllowNobody, - salt: "salt2", - expErr: true, - }, - "authority can instantiate a contract when permission is everybody": { - addr: authority, - permission: &types.AllowEverybody, - salt: "salt3", - expErr: false, - }, - "other address can instantiate a contract when permission is everybody": { - addr: myAddress.String(), - permission: &types.AllowEverybody, - salt: "salt4", - expErr: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - _, _, sender := testdata.KeyTestPubAddr() - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = sender.String() - m.InstantiatePermission = spec.permission - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // when - msgInstantiate := &types.MsgInstantiateContract2{ - Sender: spec.addr, - Admin: myAddress.String(), - CodeID: result.CodeID, - Label: "label", - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - Salt: []byte(spec.salt), - FixMsg: true, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgInstantiate)(ctx, msgInstantiate) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestUpdateInstantiateConfig(t *testing.T) { - wasmApp := app.Setup(t) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{Time: time.Now()}) - - var ( - creator sdk.AccAddress = make([]byte, types.ContractAddrLen) - authority = wasmApp.WasmKeeper.GetAuthority() - ) - - specs := map[string]struct { - addr string - permission *types.AccessConfig - expErr bool - }{ - "authority can update instantiate config when permission is subset": { - addr: authority, - permission: &types.AllowNobody, - expErr: false, - }, - "creator can update instantiate config when permission is subset": { - addr: creator.String(), - permission: &types.AllowNobody, - expErr: false, - }, - "authority can update instantiate config when permission is not subset": { - addr: authority, - permission: &types.AllowEverybody, - expErr: false, - }, - "creator cannot update instantiate config when permission is not subset": { - addr: creator.String(), - permission: &types.AllowEverybody, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup - err := wasmApp.WasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowEverybody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { - m.WASMByteCode = wasmContract - m.Sender = creator.String() - m.InstantiatePermission = &types.AllowNobody - }) - - // store code - rsp, err := wasmApp.MsgServiceRouter().Handler(msg)(ctx, msg) - require.NoError(t, err) - var result types.MsgStoreCodeResponse - require.NoError(t, wasmApp.AppCodec().Unmarshal(rsp.Data, &result)) - - // when - msgUpdateInstantiateConfig := &types.MsgUpdateInstantiateConfig{ - Sender: spec.addr, - CodeID: result.CodeID, - NewInstantiatePermission: spec.permission, - } - _, err = wasmApp.MsgServiceRouter().Handler(msgUpdateInstantiateConfig)(ctx, msgUpdateInstantiateConfig) - - // then - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/x/wasm/keeper/options.go b/x/wasm/keeper/options.go deleted file mode 100644 index 1ce15c5..0000000 --- a/x/wasm/keeper/options.go +++ /dev/null @@ -1,170 +0,0 @@ -package keeper - -import ( - "fmt" - "reflect" - - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/prometheus/client_golang/prometheus" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type optsFn func(*Keeper) - -func (f optsFn) apply(keeper *Keeper) { - f(keeper) -} - -// WithWasmEngine is an optional constructor parameter to replace the default wasmVM engine with the -// given one. -func WithWasmEngine(x types.WasmerEngine) Option { - return optsFn(func(k *Keeper) { - k.wasmVM = x - }) -} - -// WithMessageHandler is an optional constructor parameter to set a custom handler for wasmVM messages. -// This option should not be combined with Option `WithMessageEncoders` or `WithMessageHandlerDecorator` -func WithMessageHandler(x Messenger) Option { - return optsFn(func(k *Keeper) { - k.messenger = x - }) -} - -// WithMessageHandlerDecorator is an optional constructor parameter to decorate the wasm handler for wasmVM messages. -// This option should not be combined with Option `WithMessageEncoders` or `WithMessageHandler` -func WithMessageHandlerDecorator(d func(old Messenger) Messenger) Option { - return optsFn(func(k *Keeper) { - k.messenger = d(k.messenger) - }) -} - -// WithQueryHandler is an optional constructor parameter to set custom query handler for wasmVM requests. -// This option should not be combined with Option `WithQueryPlugins` or `WithQueryHandlerDecorator` -func WithQueryHandler(x WasmVMQueryHandler) Option { - return optsFn(func(k *Keeper) { - k.wasmVMQueryHandler = x - }) -} - -// WithQueryHandlerDecorator is an optional constructor parameter to decorate the default wasm query handler for wasmVM requests. -// This option should not be combined with Option `WithQueryPlugins` or `WithQueryHandler` -func WithQueryHandlerDecorator(d func(old WasmVMQueryHandler) WasmVMQueryHandler) Option { - return optsFn(func(k *Keeper) { - k.wasmVMQueryHandler = d(k.wasmVMQueryHandler) - }) -} - -// WithQueryPlugins is an optional constructor parameter to pass custom query plugins for wasmVM requests. -// This option expects the default `QueryHandler` set and should not be combined with Option `WithQueryHandler` or `WithQueryHandlerDecorator`. -func WithQueryPlugins(x *QueryPlugins) Option { - return optsFn(func(k *Keeper) { - q, ok := k.wasmVMQueryHandler.(QueryPlugins) - if !ok { - panic(fmt.Sprintf("Unsupported query handler type: %T", k.wasmVMQueryHandler)) - } - k.wasmVMQueryHandler = q.Merge(x) - }) -} - -// WithMessageEncoders is an optional constructor parameter to pass custom message encoder to the default wasm message handler. -// This option expects the `DefaultMessageHandler` set and should not be combined with Option `WithMessageHandler` or `WithMessageHandlerDecorator`. -func WithMessageEncoders(x *MessageEncoders) Option { - return optsFn(func(k *Keeper) { - q, ok := k.messenger.(*MessageHandlerChain) - if !ok { - panic(fmt.Sprintf("Unsupported message handler type: %T", k.messenger)) - } - s, ok := q.handlers[0].(SDKMessageHandler) - if !ok { - panic(fmt.Sprintf("Unexpected message handler type: %T", q.handlers[0])) - } - e, ok := s.encoders.(MessageEncoders) - if !ok { - panic(fmt.Sprintf("Unsupported encoder type: %T", s.encoders)) - } - s.encoders = e.Merge(x) - q.handlers[0] = s - }) -} - -// WithCoinTransferrer is an optional constructor parameter to set a custom coin transferrer -func WithCoinTransferrer(x CoinTransferrer) Option { - if x == nil { - panic("must not be nil") - } - return optsFn(func(k *Keeper) { - k.bank = x - }) -} - -// WithAccountPruner is an optional constructor parameter to set a custom type that handles balances and data cleanup -// for accounts pruned on contract instantiate -func WithAccountPruner(x AccountPruner) Option { - if x == nil { - panic("must not be nil") - } - return optsFn(func(k *Keeper) { - k.accountPruner = x - }) -} - -func WithVMCacheMetrics(r prometheus.Registerer) Option { - return optsFn(func(k *Keeper) { - NewWasmVMMetricsCollector(k.wasmVM).Register(r) - }) -} - -// WithGasRegister set a new gas register to implement custom gas costs. -// When the "gas multiplier" for wasmvm gas conversion is modified inside the new register, -// make sure to also use `WithApiCosts` option for non default values -func WithGasRegister(x GasRegister) Option { - if x == nil { - panic("must not be nil") - } - return optsFn(func(k *Keeper) { - k.gasRegister = x - }) -} - -// WithAPICosts sets custom api costs. Amounts are in cosmwasm gas Not SDK gas. -func WithAPICosts(human, canonical uint64) Option { - return optsFn(func(_ *Keeper) { - costHumanize = human - costCanonical = canonical - }) -} - -// WithMaxQueryStackSize overwrites the default limit for maximum query stacks -func WithMaxQueryStackSize(m uint32) Option { - return optsFn(func(k *Keeper) { - k.maxQueryStackSize = m - }) -} - -// WithAcceptedAccountTypesOnContractInstantiation sets the accepted account types. Account types of this list won't be overwritten or cause a failure -// when they exist for an address on contract instantiation. -// -// Values should be references and contain the `*authtypes.BaseAccount` as default bank account type. -func WithAcceptedAccountTypesOnContractInstantiation(accts ...authtypes.AccountI) Option { - m := asTypeMap(accts) - return optsFn(func(k *Keeper) { - k.acceptedAccountTypes = m - }) -} - -func asTypeMap(accts []authtypes.AccountI) map[reflect.Type]struct{} { - m := make(map[reflect.Type]struct{}, len(accts)) - for _, a := range accts { - if a == nil { - panic(types.ErrEmpty.Wrap("address")) - } - at := reflect.TypeOf(a) - if _, exists := m[at]; exists { - panic(types.ErrDuplicate.Wrapf("%T", a)) - } - m[at] = struct{}{} - } - return m -} diff --git a/x/wasm/keeper/options_test.go b/x/wasm/keeper/options_test.go deleted file mode 100644 index e2c6142..0000000 --- a/x/wasm/keeper/options_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package keeper - -import ( - "reflect" - "testing" - - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestConstructorOptions(t *testing.T) { - specs := map[string]struct { - srcOpt Option - verify func(*testing.T, Keeper) - }{ - "wasm engine": { - srcOpt: WithWasmEngine(&wasmtesting.MockWasmer{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockWasmer{}, k.wasmVM) - }, - }, - "message handler": { - srcOpt: WithMessageHandler(&wasmtesting.MockMessageHandler{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockMessageHandler{}, k.messenger) - }, - }, - "query plugins": { - srcOpt: WithQueryHandler(&wasmtesting.MockQueryHandler{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockQueryHandler{}, k.wasmVMQueryHandler) - }, - }, - "message handler decorator": { - srcOpt: WithMessageHandlerDecorator(func(old Messenger) Messenger { - require.IsType(t, &MessageHandlerChain{}, old) - return &wasmtesting.MockMessageHandler{} - }), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockMessageHandler{}, k.messenger) - }, - }, - "query plugins decorator": { - srcOpt: WithQueryHandlerDecorator(func(old WasmVMQueryHandler) WasmVMQueryHandler { - require.IsType(t, QueryPlugins{}, old) - return &wasmtesting.MockQueryHandler{} - }), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockQueryHandler{}, k.wasmVMQueryHandler) - }, - }, - "coin transferrer": { - srcOpt: WithCoinTransferrer(&wasmtesting.MockCoinTransferrer{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockCoinTransferrer{}, k.bank) - }, - }, - "costs": { - srcOpt: WithGasRegister(&wasmtesting.MockGasRegister{}), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, &wasmtesting.MockGasRegister{}, k.gasRegister) - }, - }, - "api costs": { - srcOpt: WithAPICosts(1, 2), - verify: func(t *testing.T, k Keeper) { - t.Cleanup(setAPIDefaults) - assert.Equal(t, uint64(1), costHumanize) - assert.Equal(t, uint64(2), costCanonical) - }, - }, - "max recursion query limit": { - srcOpt: WithMaxQueryStackSize(1), - verify: func(t *testing.T, k Keeper) { - assert.IsType(t, uint32(1), k.maxQueryStackSize) - }, - }, - "accepted account types": { - srcOpt: WithAcceptedAccountTypesOnContractInstantiation(&authtypes.BaseAccount{}, &vestingtypes.ContinuousVestingAccount{}), - verify: func(t *testing.T, k Keeper) { - exp := map[reflect.Type]struct{}{ - reflect.TypeOf(&authtypes.BaseAccount{}): {}, - reflect.TypeOf(&vestingtypes.ContinuousVestingAccount{}): {}, - } - assert.Equal(t, exp, k.acceptedAccountTypes) - }, - }, - "account pruner": { - srcOpt: WithAccountPruner(VestingCoinBurner{}), - verify: func(t *testing.T, k Keeper) { - assert.Equal(t, VestingCoinBurner{}, k.accountPruner) - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - k := NewKeeper(nil, nil, authkeeper.AccountKeeper{}, &bankkeeper.BaseKeeper{}, stakingkeeper.Keeper{}, nil, nil, nil, nil, nil, nil, nil, "tempDir", types.DefaultWasmConfig(), AvailableCapabilities, "", spec.srcOpt) - spec.verify(t, k) - }) - } -} - -func setAPIDefaults() { - costHumanize = DefaultGasCostHumanAddress * DefaultGasMultiplier - costCanonical = DefaultGasCostCanonicalAddress * DefaultGasMultiplier -} diff --git a/x/wasm/keeper/proposal_handler.go b/x/wasm/keeper/proposal_handler.go deleted file mode 100644 index 6cc6214..0000000 --- a/x/wasm/keeper/proposal_handler.go +++ /dev/null @@ -1,342 +0,0 @@ -package keeper - -import ( - "bytes" - "encoding/hex" - "fmt" - - errorsmod "cosmossdk.io/errors" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// NewWasmProposalHandler creates a new governance Handler for wasm proposals -// -// Deprecated: Do not use. -func NewWasmProposalHandler(k decoratedKeeper, enabledProposalTypes []types.ProposalType) v1beta1.Handler { - return NewWasmProposalHandlerX(NewGovPermissionKeeper(k), enabledProposalTypes) -} - -// NewWasmProposalHandlerX creates a new governance Handler for wasm proposals -// -// Deprecated: Do not use. -func NewWasmProposalHandlerX(k types.ContractOpsKeeper, enabledProposalTypes []types.ProposalType) v1beta1.Handler { - enabledTypes := make(map[string]struct{}, len(enabledProposalTypes)) - for i := range enabledProposalTypes { - enabledTypes[string(enabledProposalTypes[i])] = struct{}{} - } - return func(ctx sdk.Context, content v1beta1.Content) error { - if content == nil { - return errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "content must not be empty") - } - if _, ok := enabledTypes[content.ProposalType()]; !ok { - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unsupported wasm proposal content type: %q", content.ProposalType()) - } - switch c := content.(type) { - case *types.StoreCodeProposal: - return handleStoreCodeProposal(ctx, k, *c) - case *types.InstantiateContractProposal: - return handleInstantiateProposal(ctx, k, *c) - case *types.InstantiateContract2Proposal: - return handleInstantiate2Proposal(ctx, k, *c) - case *types.MigrateContractProposal: - return handleMigrateProposal(ctx, k, *c) - case *types.SudoContractProposal: - return handleSudoProposal(ctx, k, *c) - case *types.ExecuteContractProposal: - return handleExecuteProposal(ctx, k, *c) - case *types.UpdateAdminProposal: - return handleUpdateAdminProposal(ctx, k, *c) - case *types.ClearAdminProposal: - return handleClearAdminProposal(ctx, k, *c) - case *types.PinCodesProposal: - return handlePinCodesProposal(ctx, k, *c) - case *types.UnpinCodesProposal: - return handleUnpinCodesProposal(ctx, k, *c) - case *types.UpdateInstantiateConfigProposal: - return handleUpdateInstantiateConfigProposal(ctx, k, *c) - case *types.StoreAndInstantiateContractProposal: - return handleStoreAndInstantiateContractProposal(ctx, k, *c) - default: - return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized wasm proposal content type: %T", c) - } - } -} - -//nolint:staticcheck -func handleStoreCodeProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.StoreCodeProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - codeID, checksum, err := k.Create(ctx, runAsAddr, p.WASMByteCode, p.InstantiatePermission) - if err != nil { - return err - } - - if len(p.CodeHash) != 0 && !bytes.Equal(checksum, p.CodeHash) { - return fmt.Errorf("code-hash mismatch: %X, checksum: %X", p.CodeHash, checksum) - } - - // if code should not be pinned return earlier - if p.UnpinCode { - return nil - } - return k.PinCode(ctx, codeID) -} - -//nolint:staticcheck -func handleInstantiateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.InstantiateContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - var adminAddr sdk.AccAddress - if p.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(p.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - - _, data, err := k.Instantiate(ctx, p.CodeID, runAsAddr, adminAddr, p.Msg, p.Label, p.Funds) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleInstantiate2Proposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.InstantiateContract2Proposal) error { - // Validatebasic with proposal - if err := p.ValidateBasic(); err != nil { - return err - } - - // Get runAsAddr as AccAddress - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - - // Get admin address - var adminAddr sdk.AccAddress - if p.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(p.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - - _, data, err := k.Instantiate2(ctx, p.CodeID, runAsAddr, adminAddr, p.Msg, p.Label, p.Funds, p.Salt, p.FixMsg) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleStoreAndInstantiateContractProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.StoreAndInstantiateContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - var adminAddr sdk.AccAddress - if p.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(p.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - - codeID, checksum, err := k.Create(ctx, runAsAddr, p.WASMByteCode, p.InstantiatePermission) - if err != nil { - return err - } - - if p.CodeHash != nil && !bytes.Equal(checksum, p.CodeHash) { - return errorsmod.Wrap(fmt.Errorf("code-hash mismatch: %X, checksum: %X", p.CodeHash, checksum), "code-hash mismatch") - } - - if !p.UnpinCode { - if err := k.PinCode(ctx, codeID); err != nil { - return err - } - } - - _, data, err := k.Instantiate(ctx, codeID, runAsAddr, adminAddr, p.Msg, p.Label, p.Funds) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleMigrateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.MigrateContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - - // runAs is not used if this is permissioned, so just put any valid address there (second contractAddr) - data, err := k.Migrate(ctx, contractAddr, contractAddr, p.CodeID, p.Msg) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleSudoProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.SudoContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - data, err := k.Sudo(ctx, contractAddr, p.Msg) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleExecuteProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.ExecuteContractProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - data, err := k.Execute(ctx, contractAddr, runAsAddr, p.Msg, p.Funds) - if err != nil { - return err - } - - ctx.EventManager().EmitEvent(sdk.NewEvent( - types.EventTypeGovContractResult, - sdk.NewAttribute(types.AttributeKeyResultDataHex, hex.EncodeToString(data)), - )) - return nil -} - -//nolint:staticcheck -func handleUpdateAdminProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.UpdateAdminProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - newAdminAddr, err := sdk.AccAddressFromBech32(p.NewAdmin) - if err != nil { - return errorsmod.Wrap(err, "run as address") - } - - return k.UpdateContractAdmin(ctx, contractAddr, nil, newAdminAddr) -} - -//nolint:staticcheck -func handleClearAdminProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.ClearAdminProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - contractAddr, err := sdk.AccAddressFromBech32(p.Contract) - if err != nil { - return errorsmod.Wrap(err, "contract") - } - err = k.ClearContractAdmin(ctx, contractAddr, nil) - return err -} - -//nolint:staticcheck -func handlePinCodesProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.PinCodesProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - for _, v := range p.CodeIDs { - if err := k.PinCode(ctx, v); err != nil { - return errorsmod.Wrapf(err, "code id: %d", v) - } - } - return nil -} - -//nolint:staticcheck -func handleUnpinCodesProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.UnpinCodesProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - for _, v := range p.CodeIDs { - if err := k.UnpinCode(ctx, v); err != nil { - return errorsmod.Wrapf(err, "code id: %d", v) - } - } - return nil -} - -//nolint:staticcheck -func handleUpdateInstantiateConfigProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.UpdateInstantiateConfigProposal) error { - if err := p.ValidateBasic(); err != nil { - return err - } - - var emptyCaller sdk.AccAddress - for _, accessConfigUpdate := range p.AccessConfigUpdates { - if err := k.SetAccessConfig(ctx, accessConfigUpdate.CodeID, emptyCaller, accessConfigUpdate.InstantiatePermission); err != nil { - return errorsmod.Wrapf(err, "code id: %d", accessConfigUpdate.CodeID) - } - } - return nil -} diff --git a/x/wasm/keeper/proposal_integration_test.go b/x/wasm/keeper/proposal_integration_test.go deleted file mode 100644 index 1b8d93d..0000000 --- a/x/wasm/keeper/proposal_integration_test.go +++ /dev/null @@ -1,926 +0,0 @@ -package keeper - -import ( - "bytes" - "encoding/hex" - "encoding/json" - "errors" - "os" - "testing" - - wasmvm "github.com/CosmWasm/wasmvm" - sdk "github.com/cosmos/cosmos-sdk/types" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - v1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const myTestLabel = "testing" - -func TestStoreCodeProposal(t *testing.T) { - parentCtx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(parentCtx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - rawWasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - gzippedWasmCode, err := os.ReadFile("./testdata/hackatom.wasm.gzip") - require.NoError(t, err) - checksum, err := hex.DecodeString("beb3de5e9b93b52e514c74ce87ccddb594b9bcd33b7f1af1bb6da63fc883917b") - require.NoError(t, err) - - specs := map[string]struct { - codeID int64 - code []byte - unpinCode bool - }{ - "upload with pinning (default)": { - unpinCode: false, - code: rawWasmCode, - }, - "upload with code unpin": { - unpinCode: true, - code: rawWasmCode, - }, - "upload with raw wasm code": { - code: rawWasmCode, - }, - "upload with zipped wasm code": { - code: gzippedWasmCode, - }, - } - - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - myActorAddress := RandomBech32AccountAddress(t) - - src := types.StoreCodeProposalFixture(func(p *types.StoreCodeProposal) { //nolint:staticcheck // testing a deprecated library - p.RunAs = myActorAddress - p.WASMByteCode = spec.code - p.UnpinCode = spec.unpinCode - p.CodeHash = checksum - }) - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx, src, myActorAddress, keepers) - - // then - cInfo := wasmKeeper.GetCodeInfo(ctx, 1) - require.NotNil(t, cInfo) - assert.Equal(t, myActorAddress, cInfo.Creator) - assert.Equal(t, !spec.unpinCode, wasmKeeper.IsPinnedCode(ctx, 1)) - - storedCode, err := wasmKeeper.GetByteCode(ctx, 1) - require.NoError(t, err) - assert.Equal(t, rawWasmCode, storedCode) - }) - } -} - -func mustSubmitAndExecuteLegacyProposal(t *testing.T, ctx sdk.Context, content v1beta1.Content, myActorAddress string, keepers TestKeepers) { - t.Helper() - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - // ignore all submit events - contentMsg, err := submitLegacyProposal(t, ctx.WithEventManager(sdk.NewEventManager()), content, myActorAddress, govAuthority, msgServer) - require.NoError(t, err) - - _, err = msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - require.NoError(t, err) -} - -// does not fail on submit proposal -func submitLegacyProposal(t *testing.T, ctx sdk.Context, content v1beta1.Content, myActorAddress string, govAuthority string, msgServer v1.MsgServer) (*v1.MsgExecLegacyContent, error) { - t.Helper() - contentMsg, err := v1.NewLegacyContent(content, govAuthority) - require.NoError(t, err) - - proposal, err := v1.NewMsgSubmitProposal( - []sdk.Msg{contentMsg}, - sdk.Coins{}, - myActorAddress, - "", - "my title", - "my description", - ) - require.NoError(t, err) - - // when stored - _, err = msgServer.SubmitProposal(sdk.WrapSDKContext(ctx), proposal) - return contentMsg, err -} - -func TestInstantiateProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - require.NoError(t, wasmKeeper.importCode(ctx, 1, - types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)), - wasmCode), - ) - - var ( - oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - ) - src := types.InstantiateContractProposalFixture(func(p *types.InstantiateContractProposal) { //nolint:staticcheck // testing a deprecated library - p.CodeID = firstCodeID - p.RunAs = oneAddress.String() - p.Admin = otherAddress.String() - p.Label = myTestLabel - }) - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, oneAddress.String(), keepers) - - // then - contractAddr, err := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") - require.NoError(t, err) - - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, uint64(1), cInfo.CodeID) - assert.Equal(t, oneAddress.String(), cInfo.Creator) - assert.Equal(t, otherAddress.String(), cInfo.Admin) - assert.Equal(t, myTestLabel, cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: src.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) - // and event - require.Len(t, em.Events(), 3, "%#v", em.Events()) - require.Equal(t, types.EventTypeInstantiate, em.Events()[0].Type) - require.Equal(t, types.WasmModuleEventType, em.Events()[1].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[2].Type) - require.Len(t, em.Events()[2].Attributes, 1) - require.NotEmpty(t, em.Events()[2].Attributes[0]) -} - -func TestInstantiate2Proposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - err = wasmKeeper.importCode(ctx, 1, codeInfo, wasmCode) - require.NoError(t, err) - - var ( - oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - label = "label" - salt = []byte("mySalt") - ) - src := types.InstantiateContract2ProposalFixture(func(p *types.InstantiateContract2Proposal) { //nolint:staticcheck // testing a deprecated library - p.CodeID = firstCodeID - p.RunAs = oneAddress.String() - p.Admin = otherAddress.String() - p.Label = label - p.Salt = salt - }) - contractAddress := BuildContractAddressPredictable(codeInfo.CodeHash, oneAddress, salt, []byte{}) - - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, oneAddress.String(), keepers) - - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddress) - require.NotNil(t, cInfo) - - assert.Equal(t, uint64(1), cInfo.CodeID) - assert.Equal(t, oneAddress.String(), cInfo.Creator) - assert.Equal(t, otherAddress.String(), cInfo.Admin) - assert.Equal(t, "label", cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: src.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddress)) - // and event - require.Len(t, em.Events(), 3, prettyEvents(t, em.Events())) - require.Equal(t, types.EventTypeInstantiate, em.Events()[0].Type) - require.Equal(t, types.WasmModuleEventType, em.Events()[1].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[2].Type) - require.Len(t, em.Events()[2].Attributes, 1) - require.NotEmpty(t, em.Events()[2].Attributes[0]) -} - -func TestInstantiateProposal_NoAdmin(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - require.NoError(t, wasmKeeper.importCode(ctx, 1, - types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)), - wasmCode), - ) - - var oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) - - specs := map[string]struct { - srcAdmin string - expErr bool - }{ - "empty admin": { - srcAdmin: "", - }, - "invalid admin": { - srcAdmin: "invalid", - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - src := types.InstantiateContractProposalFixture(func(p *types.InstantiateContractProposal) { //nolint:staticcheck // testing a deprecated library - p.CodeID = firstCodeID - p.RunAs = oneAddress.String() - p.Admin = spec.srcAdmin - p.Label = myTestLabel - }) - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - // when - contentMsg, gotErr := submitLegacyProposal(t, ctx, src, oneAddress.String(), govAuthority, msgServer) - // then - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - // and when - em := sdk.NewEventManager() - _, err = msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx.WithEventManager(em)), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - // then - require.NoError(t, err) - contractAddr, err := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") - require.NoError(t, err) - - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, uint64(1), cInfo.CodeID) - assert.Equal(t, oneAddress.String(), cInfo.Creator) - assert.Equal(t, "", cInfo.Admin) - assert.Equal(t, myTestLabel, cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: src.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) - // and event - require.Len(t, em.Events(), 3, "%#v", em.Events()) - require.Equal(t, types.EventTypeInstantiate, em.Events()[0].Type) - require.Equal(t, types.WasmModuleEventType, em.Events()[1].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[2].Type) - require.Len(t, em.Events()[2].Attributes, 1) - require.NotEmpty(t, em.Events()[2].Attributes[0]) - }) - } -} - -func TestStoreAndInstantiateContractProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - checksum, err := hex.DecodeString("beb3de5e9b93b52e514c74ce87ccddb594b9bcd33b7f1af1bb6da63fc883917b") - require.NoError(t, err) - - var ( - oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - ) - - src := types.StoreAndInstantiateContractProposalFixture(func(p *types.StoreAndInstantiateContractProposal) { //nolint:staticcheck // testing a deprecated library - p.WASMByteCode = wasmCode - p.RunAs = oneAddress.String() - p.Admin = otherAddress.String() - p.Label = myTestLabel - p.CodeHash = checksum - }) - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, oneAddress.String(), keepers) - - // then - contractAddr, err := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") - require.NoError(t, err) - - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, oneAddress.String(), cInfo.Creator) - assert.Equal(t, otherAddress.String(), cInfo.Admin) - assert.Equal(t, myTestLabel, cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: cInfo.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) - // and event - require.Len(t, em.Events(), 5, "%#v", em.Events()) - require.Equal(t, types.EventTypeStoreCode, em.Events()[0].Type) - require.Equal(t, types.EventTypePinCode, em.Events()[1].Type) - require.Equal(t, types.EventTypeInstantiate, em.Events()[2].Type) - require.Equal(t, types.WasmModuleEventType, em.Events()[3].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[4].Type) - require.Len(t, em.Events()[4].Attributes, 1) - require.NotEmpty(t, em.Events()[4].Attributes[0]) -} - -func TestMigrateProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - codeInfoFixture := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - require.NoError(t, wasmKeeper.importCode(ctx, 1, codeInfoFixture, wasmCode)) - require.NoError(t, wasmKeeper.importCode(ctx, 2, codeInfoFixture, wasmCode)) - - var ( - anyAddress = DeterministicAccountAddress(t, 1) - otherAddress = DeterministicAccountAddress(t, 2) - contractAddr = BuildContractAddressClassic(1, 1) - ) - - contractInfo := types.ContractInfoFixture(func(c *types.ContractInfo) { - c.Label = myTestLabel - c.Admin = anyAddress.String() - c.Created = types.NewAbsoluteTxPosition(ctx) - }) - entries := []types.ContractCodeHistoryEntry{ - {Operation: types.ContractCodeHistoryOperationTypeInit, CodeID: 1, Updated: contractInfo.Created}, - } - key, err := hex.DecodeString("636F6E666967") - require.NoError(t, err) - m := types.Model{Key: key, Value: []byte(`{"verifier":"AAAAAAAAAAAAAAAAAAAAAAAAAAA=","beneficiary":"AAAAAAAAAAAAAAAAAAAAAAAAAAA=","funder":"AQEBAQEBAQEBAQEBAQEBAQEBAQE="}`)} - require.NoError(t, wasmKeeper.importContract(ctx, contractAddr, &contractInfo, []types.Model{m}, entries)) - - migMsg := struct { - Verifier sdk.AccAddress `json:"verifier"` - }{Verifier: otherAddress} - migMsgBz, err := json.Marshal(migMsg) - require.NoError(t, err) - - src := &types.MigrateContractProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - CodeID: 2, - Contract: contractAddr.String(), - Msg: migMsgBz, - } - - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, anyAddress.String(), keepers) - - // then - require.NoError(t, err) - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, uint64(2), cInfo.CodeID) - assert.Equal(t, anyAddress.String(), cInfo.Admin) - assert.Equal(t, myTestLabel, cInfo.Label) - expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: src.CodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: src.Msg, - }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) - // and events emitted - require.Len(t, em.Events(), 2) - assert.Equal(t, types.EventTypeMigrate, em.Events()[0].Type) - require.Equal(t, types.EventTypeGovContractResult, em.Events()[1].Type) - require.Len(t, em.Events()[1].Attributes, 1) - assert.Equal(t, types.AttributeKeyResultDataHex, em.Events()[1].Attributes[0].Key) -} - -func TestExecuteProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - bankKeeper := keepers.BankKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract - - // check balance - bal := bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(100)) - - releaseMsg := struct { - Release struct{} `json:"release"` - }{} - releaseMsgBz, err := json.Marshal(releaseMsg) - require.NoError(t, err) - - // try with runAs that doesn't have pemission - badSrc := &types.ExecuteContractProposal{ //nolint:staticcheck // testing a deprecated library - Title: "First", - Description: "Beneficiary has no permission to run", - Contract: contractAddr.String(), - Msg: releaseMsgBz, - RunAs: exampleContract.BeneficiaryAddr.String(), - } - - // fails on store - this doesn't have permission - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - _, err = submitLegacyProposal(t, ctx, badSrc, exampleContract.BeneficiaryAddr.String(), govAuthority, msgServer) - require.Error(t, err) - - // balance should not change - bal = bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(100)) - - // try again with the proper run-as - src := &types.ExecuteContractProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Second", - Description: "Verifier can execute", - Contract: contractAddr.String(), - Msg: releaseMsgBz, - RunAs: exampleContract.VerifierAddr.String(), - } - - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, exampleContract.BeneficiaryAddr.String(), keepers) - - // balance should be empty (proper release) - bal = bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(0)) -} - -func TestSudoProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - bankKeeper := keepers.BankKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract - _, anyAddr := keyPubAddr() - - // check balance - bal := bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(100)) - bal = bankKeeper.GetBalance(ctx, anyAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(0)) - - type StealMsg struct { - Recipient string `json:"recipient"` - Amount []sdk.Coin `json:"amount"` - } - stealMsg := struct { - Steal StealMsg `json:"steal_funds"` - }{Steal: StealMsg{ - Recipient: anyAddr.String(), - Amount: []sdk.Coin{sdk.NewInt64Coin("denom", 75)}, - }} - stealMsgBz, err := json.Marshal(stealMsg) - require.NoError(t, err) - - // sudo can do anything - src := &types.SudoContractProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Sudo", - Description: "Steal funds for the verifier", - Contract: contractAddr.String(), - Msg: stealMsgBz, - } - - em := sdk.NewEventManager() - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, exampleContract.BeneficiaryAddr.String(), keepers) - - // balance should be empty (and verifier richer) - bal = bankKeeper.GetBalance(ctx, contractAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(25)) - bal = bankKeeper.GetBalance(ctx, anyAddr, "denom") - require.Equal(t, bal.Amount, sdk.NewInt(75)) -} - -func TestAdminProposals(t *testing.T) { - var ( - otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - contractAddr = BuildContractAddressClassic(1, 1) - ) - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - specs := map[string]struct { - state types.ContractInfo - srcProposal v1beta1.Content - expAdmin sdk.AccAddress - }{ - "update with different admin": { - state: types.ContractInfoFixture(), - srcProposal: &types.UpdateAdminProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - Contract: contractAddr.String(), - NewAdmin: otherAddress.String(), - }, - expAdmin: otherAddress, - }, - "update with old admin empty": { - state: types.ContractInfoFixture(func(info *types.ContractInfo) { - info.Admin = "" - }), - srcProposal: &types.UpdateAdminProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - Contract: contractAddr.String(), - NewAdmin: otherAddress.String(), - }, - expAdmin: otherAddress, - }, - "clear admin": { - state: types.ContractInfoFixture(), - srcProposal: &types.ClearAdminProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - Contract: contractAddr.String(), - }, - expAdmin: nil, - }, - "clear with old admin empty": { - state: types.ContractInfoFixture(func(info *types.ContractInfo) { - info.Admin = "" - }), - srcProposal: &types.ClearAdminProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - Contract: contractAddr.String(), - }, - expAdmin: nil, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - err := wasmKeeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - require.NoError(t, wasmKeeper.importCode(ctx, 1, codeInfo, wasmCode)) - - entries := []types.ContractCodeHistoryEntry{ - { - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: 1, - Updated: spec.state.Created, - }, - } - - require.NoError(t, wasmKeeper.importContract(ctx, contractAddr, &spec.state, []types.Model{}, entries)) - - // when - mustSubmitAndExecuteLegacyProposal(t, ctx, spec.srcProposal, otherAddress.String(), keepers) - - // then - cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) - require.NotNil(t, cInfo) - assert.Equal(t, spec.expAdmin.String(), cInfo.Admin) - }) - } -} - -func TestPinCodesProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - - mock := wasmtesting.MockWasmer{ - CreateFn: wasmtesting.NoOpCreateFn, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - } - var ( - hackatom = StoreHackatomExampleContract(t, ctx, keepers) - hackatomDuplicate = StoreHackatomExampleContract(t, ctx, keepers) - otherContract = StoreRandomContract(t, ctx, keepers, &mock) - gotPinnedChecksums []wasmvm.Checksum - ) - checksumCollector := func(checksum wasmvm.Checksum) error { - gotPinnedChecksums = append(gotPinnedChecksums, checksum) - return nil - } - specs := map[string]struct { - srcCodeIDs []uint64 - mockFn func(checksum wasmvm.Checksum) error - expPinned []wasmvm.Checksum - expErr bool - }{ - "pin one": { - srcCodeIDs: []uint64{hackatom.CodeID}, - mockFn: checksumCollector, - }, - "pin multiple": { - srcCodeIDs: []uint64{hackatom.CodeID, otherContract.CodeID}, - mockFn: checksumCollector, - }, - "pin same code id": { - srcCodeIDs: []uint64{hackatom.CodeID, hackatomDuplicate.CodeID}, - mockFn: checksumCollector, - }, - "pin non existing code id": { - srcCodeIDs: []uint64{999}, - mockFn: checksumCollector, - expErr: true, - }, - "pin empty code id list": { - srcCodeIDs: []uint64{}, - mockFn: checksumCollector, - expErr: true, - }, - "wasmvm failed with error": { - srcCodeIDs: []uint64{hackatom.CodeID}, - mockFn: func(_ wasmvm.Checksum) error { - return errors.New("test, ignore") - }, - expErr: true, - }, - } - parentCtx := ctx - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - myActorAddress := RandomBech32AccountAddress(t) - gotPinnedChecksums = nil - ctx, _ := parentCtx.CacheContext() - mock.PinFn = spec.mockFn - proposal := &types.PinCodesProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - CodeIDs: spec.srcCodeIDs, - } - - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - - // when - contentMsg, gotErr := submitLegacyProposal(t, ctx, proposal, myActorAddress, govAuthority, msgServer) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - - // and proposal execute - _, err := msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - require.NoError(t, err) - - // then - for i := range spec.srcCodeIDs { - c := wasmKeeper.GetCodeInfo(ctx, spec.srcCodeIDs[i]) - require.Equal(t, wasmvm.Checksum(c.CodeHash), gotPinnedChecksums[i]) - } - }) - } -} - -func TestUnpinCodesProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - - mock := wasmtesting.MockWasmer{ - CreateFn: wasmtesting.NoOpCreateFn, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - } - var ( - hackatom = StoreHackatomExampleContract(t, ctx, keepers) - hackatomDuplicate = StoreHackatomExampleContract(t, ctx, keepers) - otherContract = StoreRandomContract(t, ctx, keepers, &mock) - gotUnpinnedChecksums []wasmvm.Checksum - ) - checksumCollector := func(checksum wasmvm.Checksum) error { - gotUnpinnedChecksums = append(gotUnpinnedChecksums, checksum) - return nil - } - specs := map[string]struct { - srcCodeIDs []uint64 - mockFn func(checksum wasmvm.Checksum) error - expUnpinned []wasmvm.Checksum - expErr bool - }{ - "unpin one": { - srcCodeIDs: []uint64{hackatom.CodeID}, - mockFn: checksumCollector, - }, - "unpin multiple": { - srcCodeIDs: []uint64{hackatom.CodeID, otherContract.CodeID}, - mockFn: checksumCollector, - }, - "unpin same code id": { - srcCodeIDs: []uint64{hackatom.CodeID, hackatomDuplicate.CodeID}, - mockFn: checksumCollector, - }, - "unpin non existing code id": { - srcCodeIDs: []uint64{999}, - mockFn: checksumCollector, - expErr: true, - }, - "unpin empty code id list": { - srcCodeIDs: []uint64{}, - mockFn: checksumCollector, - expErr: true, - }, - "wasmvm failed with error": { - srcCodeIDs: []uint64{hackatom.CodeID}, - mockFn: func(_ wasmvm.Checksum) error { - return errors.New("test, ignore") - }, - expErr: true, - }, - } - parentCtx := ctx - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - gotUnpinnedChecksums = nil - ctx, _ := parentCtx.CacheContext() - mock.UnpinFn = spec.mockFn - proposal := &types.UnpinCodesProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - CodeIDs: spec.srcCodeIDs, - } - - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - - // when - contentMsg, gotErr := submitLegacyProposal(t, ctx, proposal, RandomBech32AccountAddress(t), govAuthority, msgServer) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - - // and proposal execute - _, err := msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - require.NoError(t, err) - - // then - for i := range spec.srcCodeIDs { - c := wasmKeeper.GetCodeInfo(ctx, spec.srcCodeIDs[i]) - require.Equal(t, wasmvm.Checksum(c.CodeHash), gotUnpinnedChecksums[i]) - } - }) - } -} - -func TestUpdateInstantiateConfigProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - wasmKeeper := keepers.WasmKeeper - - mock := wasmtesting.MockWasmer{ - CreateFn: wasmtesting.NoOpCreateFn, - AnalyzeCodeFn: wasmtesting.WithoutIBCAnalyzeFn, - } - anyAddress, err := sdk.AccAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz") - require.NoError(t, err) - - withAddressAccessConfig := types.AccessTypeAnyOfAddresses.With(anyAddress) - var ( - nobody = StoreRandomContractWithAccessConfig(t, ctx, keepers, &mock, &types.AllowNobody) - everybody = StoreRandomContractWithAccessConfig(t, ctx, keepers, &mock, &types.AllowEverybody) - withAddress = StoreRandomContractWithAccessConfig(t, ctx, keepers, &mock, &withAddressAccessConfig) - ) - - specs := map[string]struct { - accessConfigUpdates []types.AccessConfigUpdate - expErr bool - }{ - "update one": { - accessConfigUpdates: []types.AccessConfigUpdate{ - {CodeID: nobody.CodeID, InstantiatePermission: types.AllowEverybody}, - }, - }, - "update multiple": { - accessConfigUpdates: []types.AccessConfigUpdate{ - {CodeID: everybody.CodeID, InstantiatePermission: types.AllowNobody}, - {CodeID: nobody.CodeID, InstantiatePermission: withAddressAccessConfig}, - {CodeID: withAddress.CodeID, InstantiatePermission: types.AllowEverybody}, - }, - }, - "update same code id": { - accessConfigUpdates: []types.AccessConfigUpdate{ - {CodeID: everybody.CodeID, InstantiatePermission: types.AllowNobody}, - {CodeID: everybody.CodeID, InstantiatePermission: types.AllowEverybody}, - }, - expErr: true, - }, - "update non existing code id": { - accessConfigUpdates: []types.AccessConfigUpdate{ - {CodeID: 100, InstantiatePermission: types.AllowNobody}, - {CodeID: everybody.CodeID, InstantiatePermission: types.AllowEverybody}, - }, - expErr: true, - }, - "update empty list": { - accessConfigUpdates: make([]types.AccessConfigUpdate, 0), - expErr: true, - }, - } - parentCtx := ctx - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, _ := parentCtx.CacheContext() - - updates := make([]types.AccessConfigUpdate, 0) - for _, cu := range spec.accessConfigUpdates { - updates = append(updates, types.AccessConfigUpdate{ - CodeID: cu.CodeID, - InstantiatePermission: cu.InstantiatePermission, - }) - } - - govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() - msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) - proposal := &types.UpdateInstantiateConfigProposal{ //nolint:staticcheck // testing a deprecated library - Title: "Foo", - Description: "Bar", - AccessConfigUpdates: updates, - } - - // when - contentMsg, gotErr := submitLegacyProposal(t, ctx, proposal, RandomBech32AccountAddress(t), govAuthority, msgServer) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - - // and proposal execute - _, err := msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) - require.NoError(t, err) - - // then - for i := range spec.accessConfigUpdates { - c := wasmKeeper.GetCodeInfo(ctx, spec.accessConfigUpdates[i].CodeID) - require.Equal(t, spec.accessConfigUpdates[i].InstantiatePermission, c.InstantiateConfig) - } - }) - } -} diff --git a/x/wasm/keeper/querier.go b/x/wasm/keeper/querier.go deleted file mode 100644 index ae90461..0000000 --- a/x/wasm/keeper/querier.go +++ /dev/null @@ -1,347 +0,0 @@ -package keeper - -import ( - "context" - "encoding/binary" - "runtime/debug" - - errorsmod "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.QueryServer = &GrpcQuerier{} - -type GrpcQuerier struct { - cdc codec.Codec - storeKey storetypes.StoreKey - keeper types.ViewKeeper - queryGasLimit sdk.Gas -} - -// NewGrpcQuerier constructor -func NewGrpcQuerier(cdc codec.Codec, storeKey storetypes.StoreKey, keeper types.ViewKeeper, queryGasLimit sdk.Gas) *GrpcQuerier { - return &GrpcQuerier{cdc: cdc, storeKey: storeKey, keeper: keeper, queryGasLimit: queryGasLimit} -} - -func (q GrpcQuerier) ContractInfo(c context.Context, req *types.QueryContractInfoRequest) (*types.QueryContractInfoResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - rsp, err := queryContractInfo(sdk.UnwrapSDKContext(c), contractAddr, q.keeper) - switch { - case err != nil: - return nil, err - case rsp == nil: - return nil, types.ErrNotFound - } - return rsp, nil -} - -func (q GrpcQuerier) ContractHistory(c context.Context, req *types.QueryContractHistoryRequest) (*types.QueryContractHistoryResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - - ctx := sdk.UnwrapSDKContext(c) - r := make([]types.ContractCodeHistoryEntry, 0) - - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractCodeHistoryElementPrefix(contractAddr)) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - if accumulate { - var e types.ContractCodeHistoryEntry - if err := q.cdc.Unmarshal(value, &e); err != nil { - return false, err - } - r = append(r, e) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryContractHistoryResponse{ - Entries: r, - Pagination: pageRes, - }, nil -} - -// ContractsByCode lists all smart contracts for a code id -func (q GrpcQuerier) ContractsByCode(c context.Context, req *types.QueryContractsByCodeRequest) (*types.QueryContractsByCodeResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - if req.CodeId == 0 { - return nil, errorsmod.Wrap(types.ErrInvalid, "code id") - } - ctx := sdk.UnwrapSDKContext(c) - r := make([]string, 0) - - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractByCodeIDSecondaryIndexPrefix(req.CodeId)) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - if accumulate { - var contractAddr sdk.AccAddress = key[types.AbsoluteTxPositionLen:] - r = append(r, contractAddr.String()) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryContractsByCodeResponse{ - Contracts: r, - Pagination: pageRes, - }, nil -} - -func (q GrpcQuerier) AllContractState(c context.Context, req *types.QueryAllContractStateRequest) (*types.QueryAllContractStateResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(c) - if !q.keeper.HasContractInfo(ctx, contractAddr) { - return nil, types.ErrNotFound - } - - r := make([]types.Model, 0) - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractStorePrefix(contractAddr)) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - if accumulate { - r = append(r, types.Model{ - Key: key, - Value: value, - }) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryAllContractStateResponse{ - Models: r, - Pagination: pageRes, - }, nil -} - -func (q GrpcQuerier) RawContractState(c context.Context, req *types.QueryRawContractStateRequest) (*types.QueryRawContractStateResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - - if !q.keeper.HasContractInfo(ctx, contractAddr) { - return nil, types.ErrNotFound - } - rsp := q.keeper.QueryRaw(ctx, contractAddr, req.QueryData) - return &types.QueryRawContractStateResponse{Data: rsp}, nil -} - -func (q GrpcQuerier) SmartContractState(c context.Context, req *types.QuerySmartContractStateRequest) (rsp *types.QuerySmartContractStateResponse, err error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - if err := req.QueryData.ValidateBasic(); err != nil { - return nil, status.Error(codes.InvalidArgument, "invalid query data") - } - contractAddr, err := sdk.AccAddressFromBech32(req.Address) - if err != nil { - return nil, err - } - ctx := sdk.UnwrapSDKContext(c).WithGasMeter(sdk.NewGasMeter(q.queryGasLimit)) - // recover from out-of-gas panic - defer func() { - if r := recover(); r != nil { - switch rType := r.(type) { - case sdk.ErrorOutOfGas: - err = errorsmod.Wrapf(sdkerrors.ErrOutOfGas, - "out of gas in location: %v; gasWanted: %d, gasUsed: %d", - rType.Descriptor, ctx.GasMeter().Limit(), ctx.GasMeter().GasConsumed(), - ) - default: - err = sdkerrors.ErrPanic - } - rsp = nil - moduleLogger(ctx). - Debug("smart query contract", - "error", "recovering panic", - "contract-address", req.Address, - "stacktrace", string(debug.Stack())) - } - }() - - bz, err := q.keeper.QuerySmart(ctx, contractAddr, req.QueryData) - switch { - case err != nil: - return nil, err - case bz == nil: - return nil, types.ErrNotFound - } - return &types.QuerySmartContractStateResponse{Data: bz}, nil -} - -func (q GrpcQuerier) Code(c context.Context, req *types.QueryCodeRequest) (*types.QueryCodeResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - if req.CodeId == 0 { - return nil, errorsmod.Wrap(types.ErrInvalid, "code id") - } - rsp, err := queryCode(sdk.UnwrapSDKContext(c), req.CodeId, q.keeper) - switch { - case err != nil: - return nil, err - case rsp == nil: - return nil, types.ErrNotFound - } - return &types.QueryCodeResponse{ - CodeInfoResponse: rsp.CodeInfoResponse, - Data: rsp.Data, - }, nil -} - -func (q GrpcQuerier) Codes(c context.Context, req *types.QueryCodesRequest) (*types.QueryCodesResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - r := make([]types.CodeInfoResponse, 0) - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.CodeKeyPrefix) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { - if accumulate { - var c types.CodeInfo - if err := q.cdc.Unmarshal(value, &c); err != nil { - return false, err - } - r = append(r, types.CodeInfoResponse{ - CodeID: binary.BigEndian.Uint64(key), - Creator: c.Creator, - DataHash: c.CodeHash, - InstantiatePermission: c.InstantiateConfig, - }) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryCodesResponse{CodeInfos: r, Pagination: pageRes}, nil -} - -func queryContractInfo(ctx sdk.Context, addr sdk.AccAddress, keeper types.ViewKeeper) (*types.QueryContractInfoResponse, error) { - info := keeper.GetContractInfo(ctx, addr) - if info == nil { - return nil, types.ErrNotFound - } - return &types.QueryContractInfoResponse{ - Address: addr.String(), - ContractInfo: *info, - }, nil -} - -func queryCode(ctx sdk.Context, codeID uint64, keeper types.ViewKeeper) (*types.QueryCodeResponse, error) { - if codeID == 0 { - return nil, nil - } - res := keeper.GetCodeInfo(ctx, codeID) - if res == nil { - // nil, nil leads to 404 in rest handler - return nil, nil - } - info := types.CodeInfoResponse{ - CodeID: codeID, - Creator: res.Creator, - DataHash: res.CodeHash, - InstantiatePermission: res.InstantiateConfig, - } - - code, err := keeper.GetByteCode(ctx, codeID) - if err != nil { - return nil, errorsmod.Wrap(err, "loading wasm code") - } - - return &types.QueryCodeResponse{CodeInfoResponse: &info, Data: code}, nil -} - -func (q GrpcQuerier) PinnedCodes(c context.Context, req *types.QueryPinnedCodesRequest) (*types.QueryPinnedCodesResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - r := make([]uint64, 0) - - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.PinnedCodeIndexPrefix) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, _ []byte, accumulate bool) (bool, error) { - if accumulate { - r = append(r, sdk.BigEndianToUint64(key)) - } - return true, nil - }) - if err != nil { - return nil, err - } - return &types.QueryPinnedCodesResponse{ - CodeIDs: r, - Pagination: pageRes, - }, nil -} - -// Params returns params of the module. -func (q GrpcQuerier) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - ctx := sdk.UnwrapSDKContext(c) - params := q.keeper.GetParams(ctx) - return &types.QueryParamsResponse{Params: params}, nil -} - -func (q GrpcQuerier) ContractsByCreator(c context.Context, req *types.QueryContractsByCreatorRequest) (*types.QueryContractsByCreatorResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "empty request") - } - ctx := sdk.UnwrapSDKContext(c) - contracts := make([]string, 0) - - creatorAddress, err := sdk.AccAddressFromBech32(req.CreatorAddress) - if err != nil { - return nil, err - } - prefixStore := prefix.NewStore(ctx.KVStore(q.storeKey), types.GetContractsByCreatorPrefix(creatorAddress)) - pageRes, err := query.FilteredPaginate(prefixStore, req.Pagination, func(key []byte, _ []byte, accumulate bool) (bool, error) { - if accumulate { - accAddres := sdk.AccAddress(key[types.AbsoluteTxPositionLen:]) - contracts = append(contracts, accAddres.String()) - } - return true, nil - }) - if err != nil { - return nil, err - } - - return &types.QueryContractsByCreatorResponse{ - ContractAddresses: contracts, - Pagination: pageRes, - }, nil -} diff --git a/x/wasm/keeper/querier_test.go b/x/wasm/keeper/querier_test.go deleted file mode 100644 index 31cd190..0000000 --- a/x/wasm/keeper/querier_test.go +++ /dev/null @@ -1,919 +0,0 @@ -package keeper - -import ( - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "os" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/log" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestQueryAllContractState(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract - contractModel := []types.Model{ - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - } - require.NoError(t, keeper.importContractState(ctx, contractAddr, contractModel)) - - q := Querier(keeper) - specs := map[string]struct { - srcQuery *types.QueryAllContractStateRequest - expModelContains []types.Model - expModelContainsNot []types.Model - expErr *errorsmod.Error - }{ - "query all": { - srcQuery: &types.QueryAllContractStateRequest{Address: contractAddr.String()}, - expModelContains: contractModel, - }, - "query all with unknown address": { - srcQuery: &types.QueryAllContractStateRequest{Address: RandomBech32AccountAddress(t)}, - expErr: types.ErrNotFound, - }, - "with pagination offset": { - srcQuery: &types.QueryAllContractStateRequest{ - Address: contractAddr.String(), - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expModelContains: []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - }, - expModelContainsNot: []types.Model{ - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - }, - }, - "with pagination limit": { - srcQuery: &types.QueryAllContractStateRequest{ - Address: contractAddr.String(), - Pagination: &query.PageRequest{ - Limit: 1, - }, - }, - expModelContains: []types.Model{ - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - }, - expModelContainsNot: []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - }, - }, - "with pagination next key": { - srcQuery: &types.QueryAllContractStateRequest{ - Address: contractAddr.String(), - Pagination: &query.PageRequest{ - Key: fromBase64("Y29uZmln"), - }, - }, - expModelContains: []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - }, - expModelContainsNot: []types.Model{ - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - }, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.AllContractState(sdk.WrapSDKContext(ctx), spec.srcQuery) - require.True(t, spec.expErr.Is(err), err) - if spec.expErr != nil { - return - } - for _, exp := range spec.expModelContains { - assert.Contains(t, got.Models, exp) - } - for _, exp := range spec.expModelContainsNot { - assert.NotContains(t, got.Models, exp) - } - }) - } -} - -func TestQuerySmartContractState(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract.String() - - q := Querier(keeper) - specs := map[string]struct { - srcAddr sdk.AccAddress - srcQuery *types.QuerySmartContractStateRequest - expResp string - expErr error - }{ - "query smart": { - srcQuery: &types.QuerySmartContractStateRequest{Address: contractAddr, QueryData: []byte(`{"verifier":{}}`)}, - expResp: fmt.Sprintf(`{"verifier":"%s"}`, exampleContract.VerifierAddr.String()), - }, - "query smart invalid request": { - srcQuery: &types.QuerySmartContractStateRequest{Address: contractAddr, QueryData: []byte(`{"raw":{"key":"config"}}`)}, - expErr: types.ErrQueryFailed, - }, - "query smart with invalid json": { - srcQuery: &types.QuerySmartContractStateRequest{Address: contractAddr, QueryData: []byte(`not a json string`)}, - expErr: status.Error(codes.InvalidArgument, "invalid query data"), - }, - "query smart with unknown address": { - srcQuery: &types.QuerySmartContractStateRequest{Address: RandomBech32AccountAddress(t), QueryData: []byte(`{"verifier":{}}`)}, - expErr: types.ErrNotFound, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.SmartContractState(sdk.WrapSDKContext(ctx), spec.srcQuery) - require.True(t, errors.Is(err, spec.expErr), "but got %+v", err) - if spec.expErr != nil { - return - } - assert.JSONEq(t, string(got.Data), spec.expResp) - }) - } -} - -func TestQuerySmartContractPanics(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - contractAddr := BuildContractAddressClassic(1, 1) - keepers.WasmKeeper.storeCodeInfo(ctx, 1, types.CodeInfo{}) - keepers.WasmKeeper.storeContractInfo(ctx, contractAddr, &types.ContractInfo{ - CodeID: 1, - Created: types.NewAbsoluteTxPosition(ctx), - }) - ctx = ctx.WithGasMeter(sdk.NewGasMeter(DefaultInstanceCost)).WithLogger(log.TestingLogger()) - - specs := map[string]struct { - doInContract func() - expErr *errorsmod.Error - }{ - "out of gas": { - doInContract: func() { - ctx.GasMeter().ConsumeGas(ctx.GasMeter().Limit()+1, "test - consume more than limit") - }, - expErr: sdkErrors.ErrOutOfGas, - }, - "other panic": { - doInContract: func() { - panic("my panic") - }, - expErr: sdkErrors.ErrPanic, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - keepers.WasmKeeper.wasmVM = &wasmtesting.MockWasmer{QueryFn: func(checksum wasmvm.Checksum, env wasmvmtypes.Env, queryMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) ([]byte, uint64, error) { - spec.doInContract() - return nil, 0, nil - }} - // when - q := Querier(keepers.WasmKeeper) - got, err := q.SmartContractState(sdk.WrapSDKContext(ctx), &types.QuerySmartContractStateRequest{ - Address: contractAddr.String(), - QueryData: types.RawContractMessage("{}"), - }) - require.True(t, spec.expErr.Is(err), "got error: %+v", err) - assert.Nil(t, got) - }) - } -} - -func TestQueryRawContractState(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - contractAddr := exampleContract.Contract.String() - contractModel := []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - } - require.NoError(t, keeper.importContractState(ctx, exampleContract.Contract, contractModel)) - - q := Querier(keeper) - specs := map[string]struct { - srcQuery *types.QueryRawContractStateRequest - expData []byte - expErr *errorsmod.Error - }{ - "query raw key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("foo")}, - expData: []byte(`"bar"`), - }, - "query raw contract binary key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte{0x0, 0x1}}, - expData: []byte(`{"count":8}`), - }, - "query non-existent raw key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("not existing key")}, - expData: nil, - }, - "query empty raw key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("")}, - expData: nil, - }, - "query nil raw key": { - srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr}, - expData: nil, - }, - "query raw with unknown address": { - srcQuery: &types.QueryRawContractStateRequest{Address: RandomBech32AccountAddress(t), QueryData: []byte("foo")}, - expErr: types.ErrNotFound, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.RawContractState(sdk.WrapSDKContext(ctx), spec.srcQuery) - require.True(t, spec.expErr.Is(err), err) - if spec.expErr != nil { - return - } - assert.Equal(t, spec.expData, got.Data) - }) - } -} - -func TestQueryContractListByCodeOrdering(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 500)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - anyAddr := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, wasmCode, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: anyAddr, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - // manage some realistic block settings - var h int64 = 10 - setBlock := func(ctx sdk.Context, height int64) sdk.Context { - ctx = ctx.WithBlockHeight(height) - meter := sdk.NewGasMeter(1000000) - ctx = ctx.WithGasMeter(meter) - ctx = ctx.WithBlockGasMeter(meter) - return ctx - } - - // create 10 contracts with real block/gas setup - for i := 0; i < 10; i++ { - // 3 tx per block, so we ensure both comparisons work - if i%3 == 0 { - ctx = setBlock(ctx, h) - h++ - } - _, _, err = keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, fmt.Sprintf("contract %d", i), topUp) - require.NoError(t, err) - } - - // query and check the results are properly sorted - q := Querier(keeper) - res, err := q.ContractsByCode(sdk.WrapSDKContext(ctx), &types.QueryContractsByCodeRequest{CodeId: codeID}) - require.NoError(t, err) - - require.Equal(t, 10, len(res.Contracts)) - - for _, contractAddr := range res.Contracts { - assert.NotEmpty(t, contractAddr) - } -} - -func TestQueryContractHistory(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - var ( - myContractBech32Addr = RandomBech32AccountAddress(t) - otherBech32Addr = RandomBech32AccountAddress(t) - ) - - specs := map[string]struct { - srcHistory []types.ContractCodeHistoryEntry - req types.QueryContractHistoryRequest - expContent []types.ContractCodeHistoryEntry - }{ - "response with internal fields cleared": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - Msg: []byte(`"init message"`), - }}, - req: types.QueryContractHistoryRequest{Address: myContractBech32Addr}, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Msg: []byte(`"init message"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - }}, - }, - "response with multiple entries": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - Msg: []byte(`"init message"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - Msg: []byte(`"migrate message 1"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 3, - Updated: &types.AbsoluteTxPosition{BlockHeight: 5, TxIndex: 6}, - Msg: []byte(`"migrate message 2"`), - }}, - req: types.QueryContractHistoryRequest{Address: myContractBech32Addr}, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Msg: []byte(`"init message"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Msg: []byte(`"migrate message 1"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 3, - Msg: []byte(`"migrate message 2"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 5, TxIndex: 6}, - }}, - }, - "with pagination offset": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - Msg: []byte(`"init message"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - Msg: []byte(`"migrate message 1"`), - }}, - req: types.QueryContractHistoryRequest{ - Address: myContractBech32Addr, - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Msg: []byte(`"migrate message 1"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - }}, - }, - "with pagination limit": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - Msg: []byte(`"init message"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Updated: &types.AbsoluteTxPosition{BlockHeight: 3, TxIndex: 4}, - Msg: []byte(`"migrate message 1"`), - }}, - req: types.QueryContractHistoryRequest{ - Address: myContractBech32Addr, - Pagination: &query.PageRequest{ - Limit: 1, - }, - }, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Msg: []byte(`"init message"`), - Updated: &types.AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2}, - }}, - }, - "unknown contract address": { - req: types.QueryContractHistoryRequest{Address: otherBech32Addr}, - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: []byte(`"init message"`), - }}, - expContent: nil, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - xCtx, _ := ctx.CacheContext() - - cAddr, _ := sdk.AccAddressFromBech32(myContractBech32Addr) - keeper.appendToContractHistory(xCtx, cAddr, spec.srcHistory...) - - // when - q := Querier(keeper) - got, err := q.ContractHistory(sdk.WrapSDKContext(xCtx), &spec.req) - - // then - if spec.expContent == nil { - require.Error(t, types.ErrEmpty) - return - } - require.NoError(t, err) - assert.Equal(t, spec.expContent, got.Entries) - }) - } -} - -func TestQueryCodeList(t *testing.T) { - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - specs := map[string]struct { - storedCodeIDs []uint64 - req types.QueryCodesRequest - expCodeIDs []uint64 - }{ - "none": {}, - "no gaps": { - storedCodeIDs: []uint64{1, 2, 3}, - expCodeIDs: []uint64{1, 2, 3}, - }, - "with gaps": { - storedCodeIDs: []uint64{2, 4, 6}, - expCodeIDs: []uint64{2, 4, 6}, - }, - "with pagination offset": { - storedCodeIDs: []uint64{1, 2, 3}, - req: types.QueryCodesRequest{ - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expCodeIDs: []uint64{2, 3}, - }, - "with pagination limit": { - storedCodeIDs: []uint64{1, 2, 3}, - req: types.QueryCodesRequest{ - Pagination: &query.PageRequest{ - Limit: 2, - }, - }, - expCodeIDs: []uint64{1, 2}, - }, - "with pagination next key": { - storedCodeIDs: []uint64{1, 2, 3}, - req: types.QueryCodesRequest{ - Pagination: &query.PageRequest{ - Key: fromBase64("AAAAAAAAAAI="), - }, - }, - expCodeIDs: []uint64{2, 3}, - }, - } - - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - xCtx, _ := ctx.CacheContext() - - for _, codeID := range spec.storedCodeIDs { - require.NoError(t, keeper.importCode(xCtx, codeID, - types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)), - wasmCode), - ) - } - // when - q := Querier(keeper) - got, err := q.Codes(sdk.WrapSDKContext(xCtx), &spec.req) - - // then - require.NoError(t, err) - require.NotNil(t, got.CodeInfos) - require.Len(t, got.CodeInfos, len(spec.expCodeIDs)) - for i, exp := range spec.expCodeIDs { - assert.EqualValues(t, exp, got.CodeInfos[i].CodeID) - } - }) - } -} - -func TestQueryContractInfo(t *testing.T) { - var ( - contractAddr = RandomAccountAddress(t) - anyDate = time.Now().UTC() - ) - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - // register an example extension. must be protobuf - keepers.EncodingConfig.InterfaceRegistry.RegisterImplementations( - (*types.ContractInfoExtension)(nil), - &govv1beta1.Proposal{}, - ) - govv1beta1.RegisterInterfaces(keepers.EncodingConfig.InterfaceRegistry) - - k := keepers.WasmKeeper - querier := NewGrpcQuerier(k.cdc, k.storeKey, k, k.queryGasLimit) - myExtension := func(info *types.ContractInfo) { - // abuse gov proposal as a random protobuf extension with an Any type - myExt, err := govv1beta1.NewProposal(&govv1beta1.TextProposal{Title: "foo", Description: "bar"}, 1, anyDate, anyDate) - require.NoError(t, err) - myExt.TotalDeposit = nil - err = info.SetExtension(&myExt) - require.NoError(t, err) - } - specs := map[string]struct { - src *types.QueryContractInfoRequest - stored types.ContractInfo - expRsp *types.QueryContractInfoResponse - expErr bool - }{ - "found": { - src: &types.QueryContractInfoRequest{Address: contractAddr.String()}, - stored: types.ContractInfoFixture(), - expRsp: &types.QueryContractInfoResponse{ - Address: contractAddr.String(), - ContractInfo: types.ContractInfoFixture(), - }, - }, - "with extension": { - src: &types.QueryContractInfoRequest{Address: contractAddr.String()}, - stored: types.ContractInfoFixture(myExtension), - expRsp: &types.QueryContractInfoResponse{ - Address: contractAddr.String(), - ContractInfo: types.ContractInfoFixture(myExtension), - }, - }, - "not found": { - src: &types.QueryContractInfoRequest{Address: RandomBech32AccountAddress(t)}, - stored: types.ContractInfoFixture(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - xCtx, _ := ctx.CacheContext() - k.storeContractInfo(xCtx, contractAddr, &spec.stored) - // when - gotRsp, gotErr := querier.ContractInfo(sdk.WrapSDKContext(xCtx), spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expRsp, gotRsp) - }) - } -} - -func TestQueryPinnedCodes(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - exampleContract1 := InstantiateHackatomExampleContract(t, ctx, keepers) - exampleContract2 := InstantiateIBCReflectContract(t, ctx, keepers) - require.NoError(t, keeper.pinCode(ctx, exampleContract1.CodeID)) - require.NoError(t, keeper.pinCode(ctx, exampleContract2.CodeID)) - - q := Querier(keeper) - specs := map[string]struct { - srcQuery *types.QueryPinnedCodesRequest - expCodeIDs []uint64 - expErr *errorsmod.Error - }{ - "query all": { - srcQuery: &types.QueryPinnedCodesRequest{}, - expCodeIDs: []uint64{exampleContract1.CodeID, exampleContract2.CodeID}, - }, - "with pagination offset": { - srcQuery: &types.QueryPinnedCodesRequest{ - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expCodeIDs: []uint64{exampleContract2.CodeID}, - }, - "with pagination limit": { - srcQuery: &types.QueryPinnedCodesRequest{ - Pagination: &query.PageRequest{ - Limit: 1, - }, - }, - expCodeIDs: []uint64{exampleContract1.CodeID}, - }, - "with pagination next key": { - srcQuery: &types.QueryPinnedCodesRequest{ - Pagination: &query.PageRequest{ - Key: fromBase64("AAAAAAAAAAM="), - }, - }, - expCodeIDs: []uint64{exampleContract2.CodeID}, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.PinnedCodes(sdk.WrapSDKContext(ctx), spec.srcQuery) - require.True(t, spec.expErr.Is(err), err) - if spec.expErr != nil { - return - } - require.NotNil(t, got) - assert.Equal(t, spec.expCodeIDs, got.CodeIDs) - }) - } -} - -func TestQueryParams(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - q := Querier(keeper) - - paramsResponse, err := q.Params(sdk.WrapSDKContext(ctx), &types.QueryParamsRequest{}) - require.NoError(t, err) - require.NotNil(t, paramsResponse) - - defaultParams := types.DefaultParams() - - require.Equal(t, paramsResponse.Params.CodeUploadAccess, defaultParams.CodeUploadAccess) - require.Equal(t, paramsResponse.Params.InstantiateDefaultPermission, defaultParams.InstantiateDefaultPermission) - - err = keeper.SetParams(ctx, types.Params{ - CodeUploadAccess: types.AllowNobody, - InstantiateDefaultPermission: types.AccessTypeNobody, - }) - require.NoError(t, err) - - paramsResponse, err = q.Params(sdk.WrapSDKContext(ctx), &types.QueryParamsRequest{}) - require.NoError(t, err) - require.NotNil(t, paramsResponse) - - require.Equal(t, paramsResponse.Params.CodeUploadAccess, types.AllowNobody) - require.Equal(t, paramsResponse.Params.InstantiateDefaultPermission, types.AccessTypeNobody) -} - -func TestQueryCodeInfo(t *testing.T) { - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - anyAddress, err := sdk.AccAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz") - require.NoError(t, err) - specs := map[string]struct { - codeID uint64 - accessConfig types.AccessConfig - }{ - "everybody": { - codeID: 1, - accessConfig: types.AllowEverybody, - }, - "nobody": { - codeID: 10, - accessConfig: types.AllowNobody, - }, - "with_address": { - codeID: 20, - accessConfig: types.AccessTypeOnlyAddress.With(anyAddress), - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - codeInfo.InstantiateConfig = spec.accessConfig - require.NoError(t, keeper.importCode(ctx, spec.codeID, - codeInfo, - wasmCode), - ) - - q := Querier(keeper) - got, err := q.Code(sdk.WrapSDKContext(ctx), &types.QueryCodeRequest{ - CodeId: spec.codeID, - }) - require.NoError(t, err) - expectedResponse := &types.QueryCodeResponse{ - CodeInfoResponse: &types.CodeInfoResponse{ - CodeID: spec.codeID, - Creator: codeInfo.Creator, - DataHash: codeInfo.CodeHash, - InstantiatePermission: spec.accessConfig, - }, - Data: wasmCode, - } - require.NotNil(t, got.CodeInfoResponse) - require.EqualValues(t, expectedResponse, got) - }) - } -} - -func TestQueryCodeInfoList(t *testing.T) { - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - anyAddress, err := sdk.AccAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz") - require.NoError(t, err) - codeInfoWithConfig := func(accessConfig types.AccessConfig) types.CodeInfo { - codeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) - codeInfo.InstantiateConfig = accessConfig - return codeInfo - } - - codes := []struct { - name string - codeID uint64 - codeInfo types.CodeInfo - }{ - { - name: "everybody", - codeID: 1, - codeInfo: codeInfoWithConfig(types.AllowEverybody), - }, - { - codeID: 10, - name: "nobody", - codeInfo: codeInfoWithConfig(types.AllowNobody), - }, - { - name: "with_address", - codeID: 20, - codeInfo: codeInfoWithConfig(types.AccessTypeOnlyAddress.With(anyAddress)), - }, - } - - allCodesResponse := make([]types.CodeInfoResponse, 0) - for _, code := range codes { - t.Run(fmt.Sprintf("import_%s", code.name), func(t *testing.T) { - require.NoError(t, keeper.importCode(ctx, code.codeID, - code.codeInfo, - wasmCode), - ) - }) - - allCodesResponse = append(allCodesResponse, types.CodeInfoResponse{ - CodeID: code.codeID, - Creator: code.codeInfo.Creator, - DataHash: code.codeInfo.CodeHash, - InstantiatePermission: code.codeInfo.InstantiateConfig, - }) - } - q := Querier(keeper) - got, err := q.Codes(sdk.WrapSDKContext(ctx), &types.QueryCodesRequest{ - Pagination: &query.PageRequest{ - Limit: 3, - }, - }) - require.NoError(t, err) - require.Len(t, got.CodeInfos, 3) - require.EqualValues(t, allCodesResponse, got.CodeInfos) -} - -func TestQueryContractsByCreatorList(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 500)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - anyAddr := keepers.Faucet.NewFundedRandomAccount(ctx, topUp...) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, wasmCode, nil) - require.NoError(t, err) - - _, bob := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: anyAddr, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - // manage some realistic block settings - var h int64 = 10 - setBlock := func(ctx sdk.Context, height int64) sdk.Context { - ctx = ctx.WithBlockHeight(height) - meter := sdk.NewGasMeter(1000000) - ctx = ctx.WithGasMeter(meter) - ctx = ctx.WithBlockGasMeter(meter) - return ctx - } - - var allExpecedContracts []string - // create 10 contracts with real block/gas setup - for i := 0; i < 10; i++ { - ctx = setBlock(ctx, h) - h++ - contract, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, fmt.Sprintf("contract %d", i), topUp) - allExpecedContracts = append(allExpecedContracts, contract.String()) - require.NoError(t, err) - } - - specs := map[string]struct { - srcQuery *types.QueryContractsByCreatorRequest - expContractAddr []string - expErr error - }{ - "query all": { - srcQuery: &types.QueryContractsByCreatorRequest{ - CreatorAddress: creator.String(), - }, - expContractAddr: allExpecedContracts, - expErr: nil, - }, - "with pagination offset": { - srcQuery: &types.QueryContractsByCreatorRequest{ - CreatorAddress: creator.String(), - Pagination: &query.PageRequest{ - Offset: 1, - }, - }, - expContractAddr: allExpecedContracts[1:], - expErr: nil, - }, - "with pagination limit": { - srcQuery: &types.QueryContractsByCreatorRequest{ - CreatorAddress: creator.String(), - Pagination: &query.PageRequest{ - Limit: 1, - }, - }, - expContractAddr: allExpecedContracts[0:1], - expErr: nil, - }, - "nil creator": { - srcQuery: &types.QueryContractsByCreatorRequest{ - Pagination: &query.PageRequest{}, - }, - expContractAddr: allExpecedContracts, - expErr: errors.New("empty address string is not allowed"), - }, - "nil req": { - srcQuery: nil, - expContractAddr: allExpecedContracts, - expErr: status.Error(codes.InvalidArgument, "empty request"), - }, - } - - q := Querier(keepers.WasmKeeper) - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := q.ContractsByCreator(sdk.WrapSDKContext(ctx), spec.srcQuery) - - if spec.expErr != nil { - require.Equal(t, spec.expErr, err) - return - } - require.NoError(t, err) - require.NotNil(t, got) - assert.Equal(t, spec.expContractAddr, got.ContractAddresses) - }) - } -} - -func fromBase64(s string) []byte { - r, err := base64.StdEncoding.DecodeString(s) - if err != nil { - panic(err) - } - return r -} diff --git a/x/wasm/keeper/query_plugins.go b/x/wasm/keeper/query_plugins.go deleted file mode 100644 index b85c582..0000000 --- a/x/wasm/keeper/query_plugins.go +++ /dev/null @@ -1,614 +0,0 @@ -package keeper - -import ( - "encoding/json" - "errors" - "fmt" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type QueryHandler struct { - Ctx sdk.Context - Plugins WasmVMQueryHandler - Caller sdk.AccAddress - gasRegister GasRegister -} - -func NewQueryHandler(ctx sdk.Context, vmQueryHandler WasmVMQueryHandler, caller sdk.AccAddress, gasRegister GasRegister) QueryHandler { - return QueryHandler{ - Ctx: ctx, - Plugins: vmQueryHandler, - Caller: caller, - gasRegister: gasRegister, - } -} - -type GRPCQueryRouter interface { - Route(path string) baseapp.GRPCQueryHandler -} - -// -- end baseapp interfaces -- - -var _ wasmvmtypes.Querier = QueryHandler{} - -func (q QueryHandler) Query(request wasmvmtypes.QueryRequest, gasLimit uint64) ([]byte, error) { - // set a limit for a subCtx - sdkGas := q.gasRegister.FromWasmVMGas(gasLimit) - // discard all changes/ events in subCtx by not committing the cached context - subCtx, _ := q.Ctx.WithGasMeter(sdk.NewGasMeter(sdkGas)).CacheContext() - - // make sure we charge the higher level context even on panic - defer func() { - q.Ctx.GasMeter().ConsumeGas(subCtx.GasMeter().GasConsumed(), "contract sub-query") - }() - - res, err := q.Plugins.HandleQuery(subCtx, q.Caller, request) - if err == nil { - // short-circuit, the rest is dealing with handling existing errors - return res, nil - } - - // special mappings to wasmvm system error (which are not redacted) - var wasmvmErr types.WasmVMErrorable - if ok := errors.As(err, &wasmvmErr); ok { - err = wasmvmErr.ToWasmVMError() - } - - // Issue #759 - we don't return error string for worries of non-determinism - return nil, redactError(err) -} - -func (q QueryHandler) GasConsumed() uint64 { - return q.Ctx.GasMeter().GasConsumed() -} - -type CustomQuerier func(ctx sdk.Context, request json.RawMessage) ([]byte, error) - -type QueryPlugins struct { - Bank func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) - Custom CustomQuerier - IBC func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error) - Staking func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) - Stargate func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) - Wasm func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) -} - -type contractMetaDataSource interface { - GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo -} - -type wasmQueryKeeper interface { - contractMetaDataSource - GetCodeInfo(ctx sdk.Context, codeID uint64) *types.CodeInfo - QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte - QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) - IsPinnedCode(ctx sdk.Context, codeID uint64) bool -} - -func DefaultQueryPlugins( - bank types.BankViewKeeper, - staking types.StakingKeeper, - distKeeper types.DistributionKeeper, - channelKeeper types.ChannelKeeper, - wasm wasmQueryKeeper, -) QueryPlugins { - return QueryPlugins{ - Bank: BankQuerier(bank), - Custom: NoCustomQuerier, - IBC: IBCQuerier(wasm, channelKeeper), - Staking: StakingQuerier(staking, distKeeper), - Stargate: RejectStargateQuerier(), - Wasm: WasmQuerier(wasm), - } -} - -func (e QueryPlugins) Merge(o *QueryPlugins) QueryPlugins { - // only update if this is non-nil and then only set values - if o == nil { - return e - } - if o.Bank != nil { - e.Bank = o.Bank - } - if o.Custom != nil { - e.Custom = o.Custom - } - if o.IBC != nil { - e.IBC = o.IBC - } - if o.Staking != nil { - e.Staking = o.Staking - } - if o.Stargate != nil { - e.Stargate = o.Stargate - } - if o.Wasm != nil { - e.Wasm = o.Wasm - } - return e -} - -// HandleQuery executes the requested query -func (e QueryPlugins) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - // do the query - if request.Bank != nil { - return e.Bank(ctx, request.Bank) - } - if request.Custom != nil { - return e.Custom(ctx, request.Custom) - } - if request.IBC != nil { - return e.IBC(ctx, caller, request.IBC) - } - if request.Staking != nil { - return e.Staking(ctx, request.Staking) - } - if request.Stargate != nil { - return e.Stargate(ctx, request.Stargate) - } - if request.Wasm != nil { - return e.Wasm(ctx, request.Wasm) - } - return nil, wasmvmtypes.Unknown{} -} - -func BankQuerier(bankKeeper types.BankViewKeeper) func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) { - if request.AllBalances != nil { - addr, err := sdk.AccAddressFromBech32(request.AllBalances.Address) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.AllBalances.Address) - } - coins := bankKeeper.GetAllBalances(ctx, addr) - res := wasmvmtypes.AllBalancesResponse{ - Amount: ConvertSdkCoinsToWasmCoins(coins), - } - return json.Marshal(res) - } - if request.Balance != nil { - addr, err := sdk.AccAddressFromBech32(request.Balance.Address) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Balance.Address) - } - coin := bankKeeper.GetBalance(ctx, addr, request.Balance.Denom) - res := wasmvmtypes.BalanceResponse{ - Amount: wasmvmtypes.Coin{ - Denom: coin.Denom, - Amount: coin.Amount.String(), - }, - } - return json.Marshal(res) - } - if request.Supply != nil { - coin := bankKeeper.GetSupply(ctx, request.Supply.Denom) - res := wasmvmtypes.SupplyResponse{ - Amount: wasmvmtypes.Coin{ - Denom: coin.Denom, - Amount: coin.Amount.String(), - }, - } - return json.Marshal(res) - } - return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown BankQuery variant"} - } -} - -func NoCustomQuerier(sdk.Context, json.RawMessage) ([]byte, error) { - return nil, wasmvmtypes.UnsupportedRequest{Kind: "custom"} -} - -func IBCQuerier(wasm contractMetaDataSource, channelKeeper types.ChannelKeeper) func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error) { - return func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error) { - if request.PortID != nil { - contractInfo := wasm.GetContractInfo(ctx, caller) - res := wasmvmtypes.PortIDResponse{ - PortID: contractInfo.IBCPortID, - } - return json.Marshal(res) - } - if request.ListChannels != nil { - portID := request.ListChannels.PortID - channels := make(wasmvmtypes.IBCChannels, 0) - channelKeeper.IterateChannels(ctx, func(ch channeltypes.IdentifiedChannel) bool { - // it must match the port and be in open state - if (portID == "" || portID == ch.PortId) && ch.State == channeltypes.OPEN { - newChan := wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{ - PortID: ch.PortId, - ChannelID: ch.ChannelId, - }, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{ - PortID: ch.Counterparty.PortId, - ChannelID: ch.Counterparty.ChannelId, - }, - Order: ch.Ordering.String(), - Version: ch.Version, - ConnectionID: ch.ConnectionHops[0], - } - channels = append(channels, newChan) - } - return false - }) - res := wasmvmtypes.ListChannelsResponse{ - Channels: channels, - } - return json.Marshal(res) - } - if request.Channel != nil { - channelID := request.Channel.ChannelID - portID := request.Channel.PortID - if portID == "" { - contractInfo := wasm.GetContractInfo(ctx, caller) - portID = contractInfo.IBCPortID - } - got, found := channelKeeper.GetChannel(ctx, portID, channelID) - var channel *wasmvmtypes.IBCChannel - // it must be in open state - if found && got.State == channeltypes.OPEN { - channel = &wasmvmtypes.IBCChannel{ - Endpoint: wasmvmtypes.IBCEndpoint{ - PortID: portID, - ChannelID: channelID, - }, - CounterpartyEndpoint: wasmvmtypes.IBCEndpoint{ - PortID: got.Counterparty.PortId, - ChannelID: got.Counterparty.ChannelId, - }, - Order: got.Ordering.String(), - Version: got.Version, - ConnectionID: got.ConnectionHops[0], - } - } - res := wasmvmtypes.ChannelResponse{ - Channel: channel, - } - return json.Marshal(res) - } - return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown IBCQuery variant"} - } -} - -// RejectStargateQuerier rejects all stargate queries -func RejectStargateQuerier() func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { - return nil, wasmvmtypes.UnsupportedRequest{Kind: "Stargate queries are disabled"} - } -} - -// AcceptedStargateQueries define accepted Stargate queries as a map with path as key and response type as value. -// For example: -// acceptList["/cosmos.auth.v1beta1.Query/Account"]= &authtypes.QueryAccountResponse{} -type AcceptedStargateQueries map[string]codec.ProtoMarshaler - -// AcceptListStargateQuerier supports a preconfigured set of stargate queries only. -// All arguments must be non nil. -// -// Warning: Chains need to test and maintain their accept list carefully. -// There were critical consensus breaking issues in the past with non-deterministic behaviour in the SDK. -// -// This queries can be set via WithQueryPlugins option in the wasm keeper constructor: -// WithQueryPlugins(&QueryPlugins{Stargate: AcceptListStargateQuerier(acceptList, queryRouter, codec)}) -func AcceptListStargateQuerier(acceptList AcceptedStargateQueries, queryRouter GRPCQueryRouter, codec codec.Codec) func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error) { - protoResponse, accepted := acceptList[request.Path] - if !accepted { - return nil, wasmvmtypes.UnsupportedRequest{Kind: fmt.Sprintf("'%s' path is not allowed from the contract", request.Path)} - } - - route := queryRouter.Route(request.Path) - if route == nil { - return nil, wasmvmtypes.UnsupportedRequest{Kind: fmt.Sprintf("No route to query '%s'", request.Path)} - } - - res, err := route(ctx, abci.RequestQuery{ - Data: request.Data, - Path: request.Path, - }) - if err != nil { - return nil, err - } - - return ConvertProtoToJSONMarshal(codec, protoResponse, res.Value) - } -} - -func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKeeper) func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) { - if request.BondedDenom != nil { - denom := keeper.BondDenom(ctx) - res := wasmvmtypes.BondedDenomResponse{ - Denom: denom, - } - return json.Marshal(res) - } - if request.AllValidators != nil { - validators := keeper.GetBondedValidatorsByPower(ctx) - // validators := keeper.GetAllValidators(ctx) - wasmVals := make([]wasmvmtypes.Validator, len(validators)) - for i, v := range validators { - wasmVals[i] = wasmvmtypes.Validator{ - Address: v.OperatorAddress, - Commission: v.Commission.Rate.String(), - MaxCommission: v.Commission.MaxRate.String(), - MaxChangeRate: v.Commission.MaxChangeRate.String(), - } - } - res := wasmvmtypes.AllValidatorsResponse{ - Validators: wasmVals, - } - return json.Marshal(res) - } - if request.Validator != nil { - valAddr, err := sdk.ValAddressFromBech32(request.Validator.Address) - if err != nil { - return nil, err - } - v, found := keeper.GetValidator(ctx, valAddr) - res := wasmvmtypes.ValidatorResponse{} - if found { - res.Validator = &wasmvmtypes.Validator{ - Address: v.OperatorAddress, - Commission: v.Commission.Rate.String(), - MaxCommission: v.Commission.MaxRate.String(), - MaxChangeRate: v.Commission.MaxChangeRate.String(), - } - } - return json.Marshal(res) - } - if request.AllDelegations != nil { - delegator, err := sdk.AccAddressFromBech32(request.AllDelegations.Delegator) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.AllDelegations.Delegator) - } - sdkDels := keeper.GetAllDelegatorDelegations(ctx, delegator) - delegations, err := sdkToDelegations(ctx, keeper, sdkDels) - if err != nil { - return nil, err - } - res := wasmvmtypes.AllDelegationsResponse{ - Delegations: delegations, - } - return json.Marshal(res) - } - if request.Delegation != nil { - delegator, err := sdk.AccAddressFromBech32(request.Delegation.Delegator) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Delegator) - } - validator, err := sdk.ValAddressFromBech32(request.Delegation.Validator) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Validator) - } - - var res wasmvmtypes.DelegationResponse - d, found := keeper.GetDelegation(ctx, delegator, validator) - if found { - res.Delegation, err = sdkToFullDelegation(ctx, keeper, distKeeper, d) - if err != nil { - return nil, err - } - } - return json.Marshal(res) - } - return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown Staking variant"} - } -} - -func sdkToDelegations(ctx sdk.Context, keeper types.StakingKeeper, delegations []stakingtypes.Delegation) (wasmvmtypes.Delegations, error) { - result := make([]wasmvmtypes.Delegation, len(delegations)) - bondDenom := keeper.BondDenom(ctx) - - for i, d := range delegations { - delAddr, err := sdk.AccAddressFromBech32(d.DelegatorAddress) - if err != nil { - return nil, errorsmod.Wrap(err, "delegator address") - } - valAddr, err := sdk.ValAddressFromBech32(d.ValidatorAddress) - if err != nil { - return nil, errorsmod.Wrap(err, "validator address") - } - - // shares to amount logic comes from here: - // https://github.com/cosmos/cosmos-sdk/blob/v0.38.3/x/staking/keeper/querier.go#L404 - val, found := keeper.GetValidator(ctx, valAddr) - if !found { - return nil, errorsmod.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") - } - amount := sdk.NewCoin(bondDenom, val.TokensFromShares(d.Shares).TruncateInt()) - - result[i] = wasmvmtypes.Delegation{ - Delegator: delAddr.String(), - Validator: valAddr.String(), - Amount: ConvertSdkCoinToWasmCoin(amount), - } - } - return result, nil -} - -func sdkToFullDelegation(ctx sdk.Context, keeper types.StakingKeeper, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) (*wasmvmtypes.FullDelegation, error) { - delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { - return nil, errorsmod.Wrap(err, "delegator address") - } - valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) - if err != nil { - return nil, errorsmod.Wrap(err, "validator address") - } - val, found := keeper.GetValidator(ctx, valAddr) - if !found { - return nil, errorsmod.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") - } - bondDenom := keeper.BondDenom(ctx) - amount := sdk.NewCoin(bondDenom, val.TokensFromShares(delegation.Shares).TruncateInt()) - - delegationCoins := ConvertSdkCoinToWasmCoin(amount) - - // FIXME: this is very rough but better than nothing... - // https://github.com/CosmWasm/wasmd/issues/282 - // if this (val, delegate) pair is receiving a redelegation, it cannot redelegate more - // otherwise, it can redelegate the full amount - // (there are cases of partial funds redelegated, but this is a start) - redelegateCoins := wasmvmtypes.NewCoin(0, bondDenom) - if !keeper.HasReceivingRedelegation(ctx, delAddr, valAddr) { - redelegateCoins = delegationCoins - } - - // FIXME: make a cleaner way to do this (modify the sdk) - // we need the info from `distKeeper.calculateDelegationRewards()`, but it is not public - // neither is `queryDelegationRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper)` - // so we go through the front door of the querier.... - accRewards, err := getAccumulatedRewards(ctx, distKeeper, delegation) - if err != nil { - return nil, err - } - - return &wasmvmtypes.FullDelegation{ - Delegator: delAddr.String(), - Validator: valAddr.String(), - Amount: delegationCoins, - AccumulatedRewards: accRewards, - CanRedelegate: redelegateCoins, - }, nil -} - -// FIXME: simplify this enormously when -// https://github.com/cosmos/cosmos-sdk/issues/7466 is merged -func getAccumulatedRewards(ctx sdk.Context, distKeeper types.DistributionKeeper, delegation stakingtypes.Delegation) ([]wasmvmtypes.Coin, error) { - // Try to get *delegator* reward info! - params := distributiontypes.QueryDelegationRewardsRequest{ - DelegatorAddress: delegation.DelegatorAddress, - ValidatorAddress: delegation.ValidatorAddress, - } - cache, _ := ctx.CacheContext() - qres, err := distKeeper.DelegationRewards(sdk.WrapSDKContext(cache), ¶ms) - if err != nil { - return nil, err - } - - // now we have it, convert it into wasmvm types - rewards := make([]wasmvmtypes.Coin, len(qres.Rewards)) - for i, r := range qres.Rewards { - rewards[i] = wasmvmtypes.Coin{ - Denom: r.Denom, - Amount: r.Amount.TruncateInt().String(), - } - } - return rewards, nil -} - -func WasmQuerier(k wasmQueryKeeper) func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { - switch { - case request.Smart != nil: - addr, err := sdk.AccAddressFromBech32(request.Smart.ContractAddr) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Smart.ContractAddr) - } - msg := types.RawContractMessage(request.Smart.Msg) - if err := msg.ValidateBasic(); err != nil { - return nil, errorsmod.Wrap(err, "json msg") - } - return k.QuerySmart(ctx, addr, msg) - case request.Raw != nil: - addr, err := sdk.AccAddressFromBech32(request.Raw.ContractAddr) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Raw.ContractAddr) - } - return k.QueryRaw(ctx, addr, request.Raw.Key), nil - case request.ContractInfo != nil: - contractAddr := request.ContractInfo.ContractAddr - addr, err := sdk.AccAddressFromBech32(contractAddr) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, contractAddr) - } - info := k.GetContractInfo(ctx, addr) - if info == nil { - return nil, types.ErrNoSuchContractFn(contractAddr). - Wrapf("address %s", contractAddr) - } - res := wasmvmtypes.ContractInfoResponse{ - CodeID: info.CodeID, - Creator: info.Creator, - Admin: info.Admin, - Pinned: k.IsPinnedCode(ctx, info.CodeID), - IBCPort: info.IBCPortID, - } - return json.Marshal(res) - case request.CodeInfo != nil: - if request.CodeInfo.CodeID == 0 { - return nil, types.ErrEmpty.Wrap("code id") - } - info := k.GetCodeInfo(ctx, request.CodeInfo.CodeID) - if info == nil { - return nil, types.ErrNoSuchCodeFn(request.CodeInfo.CodeID). - Wrapf("code id %d", request.CodeInfo.CodeID) - } - - res := wasmvmtypes.CodeInfoResponse{ - CodeID: request.CodeInfo.CodeID, - Creator: info.Creator, - Checksum: info.CodeHash, - } - return json.Marshal(res) - } - return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown WasmQuery variant"} - } -} - -// ConvertSdkCoinsToWasmCoins covert sdk type to wasmvm coins type -func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins { - converted := make(wasmvmtypes.Coins, len(coins)) - for i, c := range coins { - converted[i] = ConvertSdkCoinToWasmCoin(c) - } - return converted -} - -// ConvertSdkCoinToWasmCoin covert sdk type to wasmvm coin type -func ConvertSdkCoinToWasmCoin(coin sdk.Coin) wasmvmtypes.Coin { - return wasmvmtypes.Coin{ - Denom: coin.Denom, - Amount: coin.Amount.String(), - } -} - -// ConvertProtoToJSONMarshal unmarshals the given bytes into a proto message and then marshals it to json. -// This is done so that clients calling stargate queries do not need to define their own proto unmarshalers, -// being able to use response directly by json marshalling, which is supported in cosmwasm. -func ConvertProtoToJSONMarshal(cdc codec.Codec, protoResponse codec.ProtoMarshaler, bz []byte) ([]byte, error) { - // unmarshal binary into stargate response data structure - err := cdc.Unmarshal(bz, protoResponse) - if err != nil { - return nil, errorsmod.Wrap(err, "to proto") - } - - bz, err = cdc.MarshalJSON(protoResponse) - if err != nil { - return nil, errorsmod.Wrap(err, "to json") - } - - protoResponse.Reset() - return bz, nil -} - -var _ WasmVMQueryHandler = WasmVMQueryHandlerFn(nil) - -// WasmVMQueryHandlerFn is a helper to construct a function based query handler. -type WasmVMQueryHandlerFn func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) - -// HandleQuery delegates call into wrapped WasmVMQueryHandlerFn -func (w WasmVMQueryHandlerFn) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - return w(ctx, caller, request) -} diff --git a/x/wasm/keeper/query_plugins_test.go b/x/wasm/keeper/query_plugins_test.go deleted file mode 100644 index f90b926..0000000 --- a/x/wasm/keeper/query_plugins_test.go +++ /dev/null @@ -1,851 +0,0 @@ -package keeper_test - -import ( - "encoding/hex" - "encoding/json" - "fmt" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - dbm "github.com/cometbft/cometbft-db" - 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/crypto/keys/ed25519" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - 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" - "github.com/cosmos/gogoproto/proto" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestIBCQuerier(t *testing.T) { - myExampleChannels := []channeltypes.IdentifiedChannel{ - // this is returned - { - State: channeltypes.OPEN, - Ordering: channeltypes.ORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "counterPartyPortID", - ChannelId: "counterPartyChannelID", - }, - ConnectionHops: []string{"one"}, - Version: "v1", - PortId: "myPortID", - ChannelId: "myChannelID", - }, - // this is filtered out - { - State: channeltypes.INIT, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "foobar", - }, - ConnectionHops: []string{"one"}, - Version: "initversion", - PortId: "initPortID", - ChannelId: "initChannelID", - }, - // this is returned - { - State: channeltypes.OPEN, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "otherCounterPartyPortID", - ChannelId: "otherCounterPartyChannelID", - }, - ConnectionHops: []string{"other", "second"}, - Version: "otherVersion", - PortId: "otherPortID", - ChannelId: "otherChannelID", - }, - // this is filtered out - { - State: channeltypes.CLOSED, - Ordering: channeltypes.ORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "super", - ChannelId: "duper", - }, - ConnectionHops: []string{"no-more"}, - Version: "closedVersion", - PortId: "closedPortID", - ChannelId: "closedChannelID", - }, - } - specs := map[string]struct { - srcQuery *wasmvmtypes.IBCQuery - wasmKeeper *mockWasmQueryKeeper - channelKeeper *wasmtesting.MockChannelKeeper - expJSONResult string - expErr *errorsmod.Error - }{ - "query port id": { - srcQuery: &wasmvmtypes.IBCQuery{ - PortID: &wasmvmtypes.PortIDQuery{}, - }, - wasmKeeper: &mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - return &types.ContractInfo{IBCPortID: "myIBCPortID"} - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{}, - expJSONResult: `{"port_id":"myIBCPortID"}`, - }, - "query list channels - all": { - srcQuery: &wasmvmtypes.IBCQuery{ - ListChannels: &wasmvmtypes.ListChannelsQuery{}, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - IterateChannelsFn: wasmtesting.MockChannelKeeperIterator(myExampleChannels), - }, - expJSONResult: `{ - "channels": [ - { - "endpoint": { - "port_id": "myPortID", - "channel_id": "myChannelID" - }, - "counterparty_endpoint": { - "port_id": "counterPartyPortID", - "channel_id": "counterPartyChannelID" - }, - "order": "ORDER_ORDERED", - "version": "v1", - "connection_id": "one" - }, - { - "endpoint": { - "port_id": "otherPortID", - "channel_id": "otherChannelID" - }, - "counterparty_endpoint": { - "port_id": "otherCounterPartyPortID", - "channel_id": "otherCounterPartyChannelID" - }, - "order": "ORDER_UNORDERED", - "version": "otherVersion", - "connection_id": "other" - } - ] -}`, - }, - "query list channels - filtered": { - srcQuery: &wasmvmtypes.IBCQuery{ - ListChannels: &wasmvmtypes.ListChannelsQuery{ - PortID: "otherPortID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - IterateChannelsFn: wasmtesting.MockChannelKeeperIterator(myExampleChannels), - }, - expJSONResult: `{ - "channels": [ - { - "endpoint": { - "port_id": "otherPortID", - "channel_id": "otherChannelID" - }, - "counterparty_endpoint": { - "port_id": "otherCounterPartyPortID", - "channel_id": "otherCounterPartyChannelID" - }, - "order": "ORDER_UNORDERED", - "version": "otherVersion", - "connection_id": "other" - } - ] -}`, - }, - "query list channels - filtered empty": { - srcQuery: &wasmvmtypes.IBCQuery{ - ListChannels: &wasmvmtypes.ListChannelsQuery{ - PortID: "none-existing", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - IterateChannelsFn: wasmtesting.MockChannelKeeperIterator(myExampleChannels), - }, - expJSONResult: `{"channels": []}`, - }, - "query channel": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - PortID: "myQueryPortID", - ChannelID: "myQueryChannelID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{ - State: channeltypes.OPEN, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "counterPartyPortID", - ChannelId: "otherCounterPartyChannelID", - }, - ConnectionHops: []string{"one"}, - Version: "version", - }, true - }, - }, - expJSONResult: `{ - "channel": { - "endpoint": { - "port_id": "myQueryPortID", - "channel_id": "myQueryChannelID" - }, - "counterparty_endpoint": { - "port_id": "counterPartyPortID", - "channel_id": "otherCounterPartyChannelID" - }, - "order": "ORDER_UNORDERED", - "version": "version", - "connection_id": "one" - } -}`, - }, - "query channel - without port set": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - ChannelID: "myQueryChannelID", - }, - }, - wasmKeeper: &mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - return &types.ContractInfo{IBCPortID: "myLoadedPortID"} - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{ - State: channeltypes.OPEN, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "counterPartyPortID", - ChannelId: "otherCounterPartyChannelID", - }, - ConnectionHops: []string{"one"}, - Version: "version", - }, true - }, - }, - expJSONResult: `{ - "channel": { - "endpoint": { - "port_id": "myLoadedPortID", - "channel_id": "myQueryChannelID" - }, - "counterparty_endpoint": { - "port_id": "counterPartyPortID", - "channel_id": "otherCounterPartyChannelID" - }, - "order": "ORDER_UNORDERED", - "version": "version", - "connection_id": "one" - } -}`, - }, - "query channel in init state": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - PortID: "myQueryPortID", - ChannelID: "myQueryChannelID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{ - State: channeltypes.INIT, - Ordering: channeltypes.UNORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "foobar", - }, - ConnectionHops: []string{"one"}, - Version: "initversion", - }, true - }, - }, - expJSONResult: "{}", - }, - "query channel in closed state": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - PortID: "myQueryPortID", - ChannelID: "myQueryChannelID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{ - State: channeltypes.CLOSED, - Ordering: channeltypes.ORDERED, - Counterparty: channeltypes.Counterparty{ - PortId: "super", - ChannelId: "duper", - }, - ConnectionHops: []string{"no-more"}, - Version: "closedVersion", - }, true - }, - }, - expJSONResult: "{}", - }, - "query channel - empty result": { - srcQuery: &wasmvmtypes.IBCQuery{ - Channel: &wasmvmtypes.ChannelQuery{ - PortID: "myQueryPortID", - ChannelID: "myQueryChannelID", - }, - }, - channelKeeper: &wasmtesting.MockChannelKeeper{ - GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - return channeltypes.Channel{}, false - }, - }, - expJSONResult: "{}", - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - h := keeper.IBCQuerier(spec.wasmKeeper, spec.channelKeeper) - gotResult, gotErr := h(sdk.Context{}, keeper.RandomAccountAddress(t), spec.srcQuery) - require.True(t, spec.expErr.Is(gotErr), "exp %v but got %#+v", spec.expErr, gotErr) - if spec.expErr != nil { - return - } - assert.JSONEq(t, spec.expJSONResult, string(gotResult), string(gotResult)) - }) - } -} - -func TestBankQuerierBalance(t *testing.T) { - mock := bankKeeperMock{GetBalanceFn: func(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { - return sdk.NewCoin(denom, sdk.NewInt(1)) - }} - - ctx := sdk.Context{} - q := keeper.BankQuerier(mock) - gotBz, gotErr := q(ctx, &wasmvmtypes.BankQuery{ - Balance: &wasmvmtypes.BalanceQuery{ - Address: keeper.RandomBech32AccountAddress(t), - Denom: "ALX", - }, - }) - require.NoError(t, gotErr) - var got wasmvmtypes.BalanceResponse - require.NoError(t, json.Unmarshal(gotBz, &got)) - exp := wasmvmtypes.BalanceResponse{ - Amount: wasmvmtypes.Coin{ - Denom: "ALX", - Amount: "1", - }, - } - assert.Equal(t, exp, got) -} - -func TestContractInfoWasmQuerier(t *testing.T) { - myValidContractAddr := keeper.RandomBech32AccountAddress(t) - myCreatorAddr := keeper.RandomBech32AccountAddress(t) - myAdminAddr := keeper.RandomBech32AccountAddress(t) - var ctx sdk.Context - - specs := map[string]struct { - req *wasmvmtypes.WasmQuery - mock mockWasmQueryKeeper - expRes wasmvmtypes.ContractInfoResponse - expErr bool - }{ - "all good": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: myValidContractAddr}, - }, - mock: mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - val := types.ContractInfoFixture(func(i *types.ContractInfo) { - i.Admin, i.Creator, i.IBCPortID = myAdminAddr, myCreatorAddr, "myIBCPort" - }) - return &val - }, - IsPinnedCodeFn: func(ctx sdk.Context, codeID uint64) bool { return true }, - }, - expRes: wasmvmtypes.ContractInfoResponse{ - CodeID: 1, - Creator: myCreatorAddr, - Admin: myAdminAddr, - Pinned: true, - IBCPort: "myIBCPort", - }, - }, - "invalid addr": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: "not a valid addr"}, - }, - expErr: true, - }, - "unknown addr": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: myValidContractAddr}, - }, - mock: mockWasmQueryKeeper{GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - return nil - }}, - expErr: true, - }, - "not pinned": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: myValidContractAddr}, - }, - mock: mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - val := types.ContractInfoFixture(func(i *types.ContractInfo) { - i.Admin, i.Creator = myAdminAddr, myCreatorAddr - }) - return &val - }, - IsPinnedCodeFn: func(ctx sdk.Context, codeID uint64) bool { return false }, - }, - expRes: wasmvmtypes.ContractInfoResponse{ - CodeID: 1, - Creator: myCreatorAddr, - Admin: myAdminAddr, - Pinned: false, - }, - }, - "without admin": { - req: &wasmvmtypes.WasmQuery{ - ContractInfo: &wasmvmtypes.ContractInfoQuery{ContractAddr: myValidContractAddr}, - }, - mock: mockWasmQueryKeeper{ - GetContractInfoFn: func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - val := types.ContractInfoFixture(func(i *types.ContractInfo) { - i.Creator = myCreatorAddr - }) - return &val - }, - IsPinnedCodeFn: func(ctx sdk.Context, codeID uint64) bool { return true }, - }, - expRes: wasmvmtypes.ContractInfoResponse{ - CodeID: 1, - Creator: myCreatorAddr, - Pinned: true, - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - q := keeper.WasmQuerier(spec.mock) - gotBz, gotErr := q(ctx, spec.req) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - var gotRes wasmvmtypes.ContractInfoResponse - require.NoError(t, json.Unmarshal(gotBz, &gotRes)) - assert.Equal(t, spec.expRes, gotRes) - }) - } -} - -func TestCodeInfoWasmQuerier(t *testing.T) { - myCreatorAddr := keeper.RandomBech32AccountAddress(t) - var ctx sdk.Context - - myRawChecksum := []byte("myHash78901234567890123456789012") - specs := map[string]struct { - req *wasmvmtypes.WasmQuery - mock mockWasmQueryKeeper - expRes wasmvmtypes.CodeInfoResponse - expErr bool - }{ - "all good": { - req: &wasmvmtypes.WasmQuery{ - CodeInfo: &wasmvmtypes.CodeInfoQuery{CodeID: 1}, - }, - mock: mockWasmQueryKeeper{ - GetCodeInfoFn: func(ctx sdk.Context, codeID uint64) *types.CodeInfo { - return &types.CodeInfo{ - CodeHash: myRawChecksum, - Creator: myCreatorAddr, - InstantiateConfig: types.AccessConfig{ - Permission: types.AccessTypeNobody, - Addresses: []string{myCreatorAddr}, - }, - } - }, - }, - expRes: wasmvmtypes.CodeInfoResponse{ - CodeID: 1, - Creator: myCreatorAddr, - Checksum: myRawChecksum, - }, - }, - "empty code id": { - req: &wasmvmtypes.WasmQuery{ - CodeInfo: &wasmvmtypes.CodeInfoQuery{}, - }, - expErr: true, - }, - "unknown code id": { - req: &wasmvmtypes.WasmQuery{ - CodeInfo: &wasmvmtypes.CodeInfoQuery{CodeID: 1}, - }, - mock: mockWasmQueryKeeper{ - GetCodeInfoFn: func(ctx sdk.Context, codeID uint64) *types.CodeInfo { - return nil - }, - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - q := keeper.WasmQuerier(spec.mock) - gotBz, gotErr := q(ctx, spec.req) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - var gotRes wasmvmtypes.CodeInfoResponse - require.NoError(t, json.Unmarshal(gotBz, &gotRes), string(gotBz)) - assert.Equal(t, spec.expRes, gotRes) - }) - } -} - -func TestQueryErrors(t *testing.T) { - specs := map[string]struct { - src error - expErr error - }{ - "no error": {}, - "no such contract": { - src: types.ErrNoSuchContractFn("contract-addr"), - expErr: wasmvmtypes.NoSuchContract{Addr: "contract-addr"}, - }, - "no such contract - wrapped": { - src: errorsmod.Wrap(types.ErrNoSuchContractFn("contract-addr"), "my additional data"), - expErr: wasmvmtypes.NoSuchContract{Addr: "contract-addr"}, - }, - "no such code": { - src: types.ErrNoSuchCodeFn(123), - expErr: wasmvmtypes.NoSuchCode{CodeID: 123}, - }, - "no such code - wrapped": { - src: errorsmod.Wrap(types.ErrNoSuchCodeFn(123), "my additional data"), - expErr: wasmvmtypes.NoSuchCode{CodeID: 123}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - mock := keeper.WasmVMQueryHandlerFn(func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - return nil, spec.src - }) - ctx := sdk.Context{}.WithGasMeter(sdk.NewInfiniteGasMeter()).WithMultiStore(store.NewCommitMultiStore(dbm.NewMemDB())) - q := keeper.NewQueryHandler(ctx, mock, sdk.AccAddress{}, keeper.NewDefaultWasmGasRegister()) - _, gotErr := q.Query(wasmvmtypes.QueryRequest{}, 1) - assert.Equal(t, spec.expErr, gotErr) - }) - } -} - -func TestAcceptListStargateQuerier(t *testing.T) { - wasmApp := app.SetupWithEmptyStore(t) - ctx := wasmApp.NewUncachedContext(false, tmproto.Header{ChainID: "foo", Height: 1, Time: time.Now()}) - err := wasmApp.StakingKeeper.SetParams(ctx, stakingtypes.DefaultParams()) - require.NoError(t, err) - - addrs := app.AddTestAddrsIncremental(wasmApp, ctx, 2, sdk.NewInt(1_000_000)) - accepted := keeper.AcceptedStargateQueries{ - "/cosmos.auth.v1beta1.Query/Account": &authtypes.QueryAccountResponse{}, - "/no/route/to/this": &authtypes.QueryAccountResponse{}, - } - - marshal := func(pb proto.Message) []byte { - b, err := proto.Marshal(pb) - require.NoError(t, err) - return b - } - - specs := map[string]struct { - req *wasmvmtypes.StargateQuery - expErr bool - expResp string - }{ - "in accept list - success result": { - req: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.auth.v1beta1.Query/Account", - Data: marshal(&authtypes.QueryAccountRequest{Address: addrs[0].String()}), - }, - expResp: fmt.Sprintf(`{"account":{"@type":"/cosmos.auth.v1beta1.BaseAccount","address":%q,"pub_key":null,"account_number":"1","sequence":"0"}}`, addrs[0].String()), - }, - "in accept list - error result": { - req: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.auth.v1beta1.Query/Account", - Data: marshal(&authtypes.QueryAccountRequest{Address: sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address()).String()}), - }, - expErr: true, - }, - "not in accept list": { - req: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.bank.v1beta1.Query/AllBalances", - Data: marshal(&banktypes.QueryAllBalancesRequest{Address: addrs[0].String()}), - }, - expErr: true, - }, - "unknown route": { - req: &wasmvmtypes.StargateQuery{ - Path: "/no/route/to/this", - Data: marshal(&banktypes.QueryAllBalancesRequest{Address: addrs[0].String()}), - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - q := keeper.AcceptListStargateQuerier(accepted, wasmApp.GRPCQueryRouter(), wasmApp.AppCodec()) - gotBz, gotErr := q(ctx, spec.req) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.JSONEq(t, spec.expResp, string(gotBz), string(gotBz)) - }) - } -} - -type mockWasmQueryKeeper struct { - GetContractInfoFn func(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo - QueryRawFn func(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte - QuerySmartFn func(ctx sdk.Context, contractAddr sdk.AccAddress, req types.RawContractMessage) ([]byte, error) - IsPinnedCodeFn func(ctx sdk.Context, codeID uint64) bool - GetCodeInfoFn func(ctx sdk.Context, codeID uint64) *types.CodeInfo -} - -func (m mockWasmQueryKeeper) GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { - if m.GetContractInfoFn == nil { - panic("not expected to be called") - } - return m.GetContractInfoFn(ctx, contractAddress) -} - -func (m mockWasmQueryKeeper) QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte { - if m.QueryRawFn == nil { - panic("not expected to be called") - } - return m.QueryRawFn(ctx, contractAddress, key) -} - -func (m mockWasmQueryKeeper) QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) { - if m.QuerySmartFn == nil { - panic("not expected to be called") - } - return m.QuerySmartFn(ctx, contractAddr, req) -} - -func (m mockWasmQueryKeeper) IsPinnedCode(ctx sdk.Context, codeID uint64) bool { - if m.IsPinnedCodeFn == nil { - panic("not expected to be called") - } - return m.IsPinnedCodeFn(ctx, codeID) -} - -func (m mockWasmQueryKeeper) GetCodeInfo(ctx sdk.Context, codeID uint64) *types.CodeInfo { - if m.GetCodeInfoFn == nil { - panic("not expected to be called") - } - return m.GetCodeInfoFn(ctx, codeID) -} - -type bankKeeperMock struct { - GetSupplyFn func(ctx sdk.Context, denom string) sdk.Coin - GetBalanceFn func(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetAllBalancesFn func(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins -} - -func (m bankKeeperMock) GetSupply(ctx sdk.Context, denom string) sdk.Coin { - if m.GetSupplyFn == nil { - panic("not expected to be called") - } - return m.GetSupplyFn(ctx, denom) -} - -func (m bankKeeperMock) GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin { - if m.GetBalanceFn == nil { - panic("not expected to be called") - } - return m.GetBalanceFn(ctx, addr, denom) -} - -func (m bankKeeperMock) GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins { - if m.GetAllBalancesFn == nil { - panic("not expected to be called") - } - return m.GetAllBalancesFn(ctx, addr) -} - -func TestConvertProtoToJSONMarshal(t *testing.T) { - testCases := []struct { - name string - queryPath string - protoResponseStruct codec.ProtoMarshaler - originalResponse string - expectedProtoResponse codec.ProtoMarshaler - expectedError bool - }{ - { - name: "successful conversion from proto response to json marshalled response", - queryPath: "/cosmos.bank.v1beta1.Query/AllBalances", - originalResponse: "0a090a036261721202333012050a03666f6f", - protoResponseStruct: &banktypes.QueryAllBalancesResponse{}, - expectedProtoResponse: &banktypes.QueryAllBalancesResponse{ - Balances: sdk.NewCoins(sdk.NewCoin("bar", sdk.NewInt(30))), - Pagination: &query.PageResponse{ - NextKey: []byte("foo"), - }, - }, - }, - { - name: "invalid proto response struct", - queryPath: "/cosmos.bank.v1beta1.Query/AllBalances", - originalResponse: "0a090a036261721202333012050a03666f6f", - protoResponseStruct: &authtypes.QueryAccountResponse{}, - expectedError: true, - }, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { - originalVersionBz, err := hex.DecodeString(tc.originalResponse) - require.NoError(t, err) - appCodec := app.MakeEncodingConfig().Marshaler - - jsonMarshalledResponse, err := keeper.ConvertProtoToJSONMarshal(appCodec, tc.protoResponseStruct, originalVersionBz) - if tc.expectedError { - require.Error(t, err) - return - } - require.NoError(t, err) - - // check response by json marshalling proto response into json response manually - jsonMarshalExpectedResponse, err := appCodec.MarshalJSON(tc.expectedProtoResponse) - require.NoError(t, err) - require.JSONEq(t, string(jsonMarshalledResponse), string(jsonMarshalExpectedResponse)) - }) - } -} - -func TestResetProtoMarshalerAfterJsonMarshal(t *testing.T) { - appCodec := app.MakeEncodingConfig().Marshaler - - protoMarshaler := &banktypes.QueryAllBalancesResponse{} - expected := appCodec.MustMarshalJSON(&banktypes.QueryAllBalancesResponse{ - Balances: sdk.NewCoins(sdk.NewCoin("bar", sdk.NewInt(30))), - Pagination: &query.PageResponse{ - NextKey: []byte("foo"), - }, - }) - - bz, err := hex.DecodeString("0a090a036261721202333012050a03666f6f") - require.NoError(t, err) - - // first marshal - response, err := keeper.ConvertProtoToJSONMarshal(appCodec, protoMarshaler, bz) - require.NoError(t, err) - require.Equal(t, expected, response) - - // second marshal - response, err = keeper.ConvertProtoToJSONMarshal(appCodec, protoMarshaler, bz) - require.NoError(t, err) - require.Equal(t, expected, response) -} - -// TestDeterministicJsonMarshal tests that we get deterministic JSON marshalled response upon -// proto struct update in the state machine. -func TestDeterministicJsonMarshal(t *testing.T) { - testCases := []struct { - name string - originalResponse string - updatedResponse string - queryPath string - responseProtoStruct codec.ProtoMarshaler - expectedProto func() codec.ProtoMarshaler - }{ - /** - * - * Origin Response - * 0a530a202f636f736d6f732e617574682e763162657461312e426173654163636f756e74122f0a2d636f736d6f7331346c3268686a6e676c3939367772703935673867646a6871653038326375367a7732706c686b - * - * Updated Response - * 0a530a202f636f736d6f732e617574682e763162657461312e426173654163636f756e74122f0a2d636f736d6f7331646a783375676866736d6b6135386676673076616a6e6533766c72776b7a6a346e6377747271122d636f736d6f7331646a783375676866736d6b6135386676673076616a6e6533766c72776b7a6a346e6377747271 - // Origin proto - message QueryAccountResponse { - // account defines the account of the corresponding address. - google.protobuf.Any account = 1 [(cosmos_proto.accepts_interface) = "AccountI"]; - } - // Updated proto - message QueryAccountResponse { - // account defines the account of the corresponding address. - google.protobuf.Any account = 1 [(cosmos_proto.accepts_interface) = "AccountI"]; - // address is the address to query for. - string address = 2; - } - */ - { - "Query Account", - "0a530a202f636f736d6f732e617574682e763162657461312e426173654163636f756e74122f0a2d636f736d6f733166387578756c746e3873717a687a6e72737a3371373778776171756867727367366a79766679", - "0a530a202f636f736d6f732e617574682e763162657461312e426173654163636f756e74122f0a2d636f736d6f733166387578756c746e3873717a687a6e72737a3371373778776171756867727367366a79766679122d636f736d6f733166387578756c746e3873717a687a6e72737a3371373778776171756867727367366a79766679", - "/cosmos.auth.v1beta1.Query/Account", - &authtypes.QueryAccountResponse{}, - func() codec.ProtoMarshaler { - account := authtypes.BaseAccount{ - Address: "cosmos1f8uxultn8sqzhznrsz3q77xwaquhgrsg6jyvfy", - } - accountResponse, err := codectypes.NewAnyWithValue(&account) - require.NoError(t, err) - return &authtypes.QueryAccountResponse{ - Account: accountResponse, - } - }, - }, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) { - appCodec := app.MakeEncodingConfig().Marshaler - - originVersionBz, err := hex.DecodeString(tc.originalResponse) - require.NoError(t, err) - jsonMarshalledOriginalBz, err := keeper.ConvertProtoToJSONMarshal(appCodec, tc.responseProtoStruct, originVersionBz) - require.NoError(t, err) - - newVersionBz, err := hex.DecodeString(tc.updatedResponse) - require.NoError(t, err) - jsonMarshalledUpdatedBz, err := keeper.ConvertProtoToJSONMarshal(appCodec, tc.responseProtoStruct, newVersionBz) - require.NoError(t, err) - - // json marshalled bytes should be the same since we use the same proto struct for unmarshalling - require.Equal(t, jsonMarshalledOriginalBz, jsonMarshalledUpdatedBz) - - // raw build also make same result - jsonMarshalExpectedResponse, err := appCodec.MarshalJSON(tc.expectedProto()) - require.NoError(t, err) - require.Equal(t, jsonMarshalledUpdatedBz, jsonMarshalExpectedResponse) - }) - } -} diff --git a/x/wasm/keeper/recurse_test.go b/x/wasm/keeper/recurse_test.go deleted file mode 100644 index d520294..0000000 --- a/x/wasm/keeper/recurse_test.go +++ /dev/null @@ -1,306 +0,0 @@ -package keeper - -import ( - "encoding/json" - "testing" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type Recurse struct { - Depth uint32 `json:"depth"` - Work uint32 `json:"work"` -} - -type recurseWrapper struct { - Recurse Recurse `json:"recurse"` -} - -func buildRecurseQuery(t *testing.T, msg Recurse) []byte { - wrapper := recurseWrapper{Recurse: msg} - bz, err := json.Marshal(wrapper) - require.NoError(t, err) - return bz -} - -type recurseResponse struct { - Hashed []byte `json:"hashed"` -} - -// number os wasm queries called from a contract -var totalWasmQueryCounter int - -func initRecurseContract(t *testing.T) (contract sdk.AccAddress, ctx sdk.Context, keeper *Keeper) { - countingQuerierDec := func(realWasmQuerier WasmVMQueryHandler) WasmVMQueryHandler { - return WasmVMQueryHandlerFn(func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - totalWasmQueryCounter++ - return realWasmQuerier.HandleQuery(ctx, caller, request) - }) - } - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithQueryHandlerDecorator(countingQuerierDec)) - keeper = keepers.WasmKeeper - exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - return exampleContract.Contract, ctx, keeper -} - -func TestGasCostOnQuery(t *testing.T) { - const ( - GasNoWork uint64 = 63_950 - // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork50 uint64 = 64_218 // this is a little shy of 50k gas - to keep an eye on the limit - - GasReturnUnhashed uint64 = 32 - GasReturnHashed uint64 = 27 - ) - - cases := map[string]struct { - gasLimit uint64 - msg Recurse - expectedGas uint64 - }{ - "no recursion, no work": { - gasLimit: 400_000, - msg: Recurse{}, - expectedGas: GasNoWork, - }, - "no recursion, some work": { - gasLimit: 400_000, - msg: Recurse{ - Work: 50, // 50 rounds of sha256 inside the contract - }, - expectedGas: GasWork50, - }, - "recursion 1, no work": { - gasLimit: 400_000, - msg: Recurse{ - Depth: 1, - }, - expectedGas: 2*GasNoWork + GasReturnUnhashed, - }, - "recursion 1, some work": { - gasLimit: 400_000, - msg: Recurse{ - Depth: 1, - Work: 50, - }, - expectedGas: 2*GasWork50 + GasReturnHashed, - }, - "recursion 4, some work": { - gasLimit: 400_000, - msg: Recurse{ - Depth: 4, - Work: 50, - }, - expectedGas: 5*GasWork50 + 4*GasReturnHashed, - }, - } - - contractAddr, ctx, keeper := initRecurseContract(t) - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - // external limit has no effect (we get a panic if this is enforced) - keeper.queryGasLimit = 1000 - - // make sure we set a limit before calling - ctx = ctx.WithGasMeter(sdk.NewGasMeter(tc.gasLimit)) - require.Equal(t, uint64(0), ctx.GasMeter().GasConsumed()) - - // do the query - recurse := tc.msg - msg := buildRecurseQuery(t, recurse) - data, err := keeper.QuerySmart(ctx, contractAddr, msg) - require.NoError(t, err) - - // check the gas is what we expected - if types.EnableGasVerification { - assert.Equal(t, tc.expectedGas, ctx.GasMeter().GasConsumed()) - } - // assert result is 32 byte sha256 hash (if hashed), or contractAddr if not - var resp recurseResponse - err = json.Unmarshal(data, &resp) - require.NoError(t, err) - if recurse.Work == 0 { - assert.Equal(t, len(contractAddr.String()), len(resp.Hashed)) - } else { - assert.Equal(t, 32, len(resp.Hashed)) - } - }) - } -} - -func TestGasOnExternalQuery(t *testing.T) { - const ( - GasWork50 uint64 = DefaultInstanceCost + 8_464 - ) - - cases := map[string]struct { - gasLimit uint64 - msg Recurse - expOutOfGas bool - }{ - "no recursion, plenty gas": { - gasLimit: 400_000, - msg: Recurse{ - Work: 50, // 50 rounds of sha256 inside the contract - }, - }, - "recursion 4, plenty gas": { - // this uses 244708 gas - gasLimit: 400_000, - msg: Recurse{ - Depth: 4, - Work: 50, - }, - }, - "no recursion, external gas limit": { - gasLimit: 5000, // this is not enough - msg: Recurse{ - Work: 50, - }, - expOutOfGas: true, - }, - "recursion 4, external gas limit": { - // this uses 244708 gas but give less - gasLimit: 4 * GasWork50, - msg: Recurse{ - Depth: 4, - Work: 50, - }, - expOutOfGas: true, - }, - } - - contractAddr, ctx, keeper := initRecurseContract(t) - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - recurse := tc.msg - msg := buildRecurseQuery(t, recurse) - - querier := NewGrpcQuerier(keeper.cdc, keeper.storeKey, keeper, tc.gasLimit) - req := &types.QuerySmartContractStateRequest{Address: contractAddr.String(), QueryData: msg} - _, gotErr := querier.SmartContractState(sdk.WrapSDKContext(ctx), req) - if tc.expOutOfGas { - require.Error(t, gotErr, sdkerrors.ErrOutOfGas) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestLimitRecursiveQueryGas(t *testing.T) { - // The point of this test from https://github.com/CosmWasm/cosmwasm/issues/456 - // Basically, if I burn 90% of gas in CPU loop, then query out (to my self) - // the sub-query will have all the original gas (minus the 40k instance charge) - // and can burn 90% and call a sub-contract again... - // This attack would allow us to use far more than the provided gas before - // eventually hitting an OutOfGas panic. - - const ( - // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork2k uint64 = 77_206 // = NewContractInstanceCosts + x // we have 6x gas used in cpu than in the instance - // This is overhead for calling into a sub-contract - GasReturnHashed uint64 = 27 - ) - - cases := map[string]struct { - gasLimit uint64 - msg Recurse - expectQueriesFromContract int - expectedGas uint64 - expectOutOfGas bool - expectError string - }{ - "no recursion, lots of work": { - gasLimit: 4_000_000, - msg: Recurse{ - Depth: 0, - Work: 2000, - }, - expectQueriesFromContract: 0, - expectedGas: GasWork2k, - }, - "recursion 5, lots of work": { - gasLimit: 4_000_000, - msg: Recurse{ - Depth: 5, - Work: 2000, - }, - expectQueriesFromContract: 5, - // FIXME: why -1 ... confused a bit by calculations, seems like rounding issues - expectedGas: GasWork2k + 5*(GasWork2k+GasReturnHashed), - }, - // this is where we expect an error... - // it has enough gas to run 5 times and die on the 6th (5th time dispatching to sub-contract) - // however, if we don't charge the cpu gas before sub-dispatching, we can recurse over 20 times - "deep recursion, should die on 5th level": { - gasLimit: 400_000, - msg: Recurse{ - Depth: 50, - Work: 2000, - }, - expectQueriesFromContract: 5, - expectOutOfGas: true, - }, - "very deep recursion, hits recursion limit": { - gasLimit: 10_000_000, - msg: Recurse{ - Depth: 100, - Work: 2000, - }, - expectQueriesFromContract: 10, - expectOutOfGas: false, - expectError: "query wasm contract failed", // Error we get from the contract instance doing the failing query, not wasmd - expectedGas: 10*(GasWork2k+GasReturnHashed) - 247, - }, - } - - contractAddr, ctx, keeper := initRecurseContract(t) - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - // reset the counter before test - totalWasmQueryCounter = 0 - - // make sure we set a limit before calling - ctx = ctx.WithGasMeter(sdk.NewGasMeter(tc.gasLimit)) - require.Equal(t, uint64(0), ctx.GasMeter().GasConsumed()) - - // prepare the query - recurse := tc.msg - msg := buildRecurseQuery(t, recurse) - - // if we expect out of gas, make sure this panics - if tc.expectOutOfGas { - require.Panics(t, func() { - _, err := keeper.QuerySmart(ctx, contractAddr, msg) - t.Logf("Got error not panic: %#v", err) - }) - assert.Equal(t, tc.expectQueriesFromContract, totalWasmQueryCounter) - return - } - - // otherwise, we expect a successful call - _, err := keeper.QuerySmart(ctx, contractAddr, msg) - if tc.expectError != "" { - require.ErrorContains(t, err, tc.expectError) - } else { - require.NoError(t, err) - } - if types.EnableGasVerification { - assert.Equal(t, tc.expectedGas, ctx.GasMeter().GasConsumed()) - } - assert.Equal(t, tc.expectQueriesFromContract, totalWasmQueryCounter) - }) - } -} diff --git a/x/wasm/keeper/reflect_test.go b/x/wasm/keeper/reflect_test.go deleted file mode 100644 index 608d705..0000000 --- a/x/wasm/keeper/reflect_test.go +++ /dev/null @@ -1,683 +0,0 @@ -package keeper - -import ( - "encoding/json" - "os" - "strings" - "testing" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/gogoproto/proto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// ReflectInitMsg is {} - -func buildReflectQuery(t *testing.T, query *testdata.ReflectQueryMsg) []byte { - bz, err := json.Marshal(query) - require.NoError(t, err) - return bz -} - -func mustParse(t *testing.T, data []byte, res interface{}) { - err := json.Unmarshal(data, res) - require.NoError(t, err) -} - -const ReflectFeatures = "staking,mask,stargate,cosmwasm_1_1" - -func TestReflectContractSend(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc))) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, bob := keyPubAddr() - - // upload reflect code - reflectID, _, err := keeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), reflectID) - - // upload hackatom escrow code - escrowCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - escrowID, _, err := keeper.Create(ctx, creator, escrowCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(2), escrowID) - - // creator instantiates a contract and gives it tokens - reflectStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - reflectAddr, _, err := keeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) - require.NoError(t, err) - require.NotEmpty(t, reflectAddr) - - // now we set contract as verifier of an escrow - initMsg := HackatomExampleInitMsg{ - Verifier: reflectAddr, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - escrowStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 25000)) - escrowAddr, _, err := keeper.Instantiate(ctx, escrowID, creator, nil, initMsgBz, "escrow contract 2", escrowStart) - require.NoError(t, err) - require.NotEmpty(t, escrowAddr) - - // let's make sure all balances make sense - checkAccount(t, ctx, accKeeper, bankKeeper, creator, sdk.NewCoins(sdk.NewInt64Coin("denom", 35000))) // 100k - 40k - 25k - checkAccount(t, ctx, accKeeper, bankKeeper, reflectAddr, reflectStart) - checkAccount(t, ctx, accKeeper, bankKeeper, escrowAddr, escrowStart) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, nil) - - // now for the trick.... we reflect a message through the reflect to call the escrow - // we also send an additional 14k tokens there. - // this should reduce the reflect balance by 14k (to 26k) - // this 14k is added to the escrow, then the entire balance is sent to bob (total: 39k) - approveMsg := []byte(`{"release":{}}`) - msgs := []wasmvmtypes.CosmosMsg{{ - Wasm: &wasmvmtypes.WasmMsg{ - Execute: &wasmvmtypes.ExecuteMsg{ - ContractAddr: escrowAddr.String(), - Msg: approveMsg, - Funds: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "14000", - }}, - }, - }, - }} - reflectSend := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{ - Msgs: msgs, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keeper.Execute(ctx, reflectAddr, creator, reflectSendBz, nil) - require.NoError(t, err) - - // did this work??? - checkAccount(t, ctx, accKeeper, bankKeeper, creator, sdk.NewCoins(sdk.NewInt64Coin("denom", 35000))) // same as before - checkAccount(t, ctx, accKeeper, bankKeeper, reflectAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 26000))) // 40k - 14k (from send) - checkAccount(t, ctx, accKeeper, bankKeeper, escrowAddr, sdk.Coins{}) // emptied reserved - checkAccount(t, ctx, accKeeper, bankKeeper, bob, sdk.NewCoins(sdk.NewInt64Coin("denom", 39000))) // all escrow of 25k + 14k -} - -func TestReflectCustomMsg(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - bob := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, fred := keyPubAddr() - - // upload code - codeID, _, err := keeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - contractAddr, _, err := keeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // set owner to bob - transfer := testdata.ReflectHandleMsg{ - ChangeOwner: &testdata.OwnerPayload{ - Owner: bob, - }, - } - transferBz, err := json.Marshal(transfer) - require.NoError(t, err) - _, err = keeper.Execute(ctx, contractAddr, creator, transferBz, nil) - require.NoError(t, err) - - // check some account values - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, contractStart) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, deposit) - checkAccount(t, ctx, accKeeper, bankKeeper, fred, nil) - - // bob can send contract's tokens to fred (using SendMsg) - msgs := []wasmvmtypes.CosmosMsg{{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "15000", - }}, - }, - }, - }} - reflectSend := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{ - Msgs: msgs, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keeper.Execute(ctx, contractAddr, bob, reflectSendBz, nil) - require.NoError(t, err) - - // fred got coins - checkAccount(t, ctx, accKeeper, bankKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 15000))) - // contract lost them - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 25000))) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, deposit) - - // construct an opaque message - var sdkSendMsg sdk.Msg = &banktypes.MsgSend{ - FromAddress: contractAddr.String(), - ToAddress: fred.String(), - Amount: sdk.NewCoins(sdk.NewInt64Coin("denom", 23000)), - } - opaque, err := toReflectRawMsg(cdc, sdkSendMsg) - require.NoError(t, err) - reflectOpaque := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{ - Msgs: []wasmvmtypes.CosmosMsg{opaque}, - }, - } - reflectOpaqueBz, err := json.Marshal(reflectOpaque) - require.NoError(t, err) - - _, err = keeper.Execute(ctx, contractAddr, bob, reflectOpaqueBz, nil) - require.NoError(t, err) - - // fred got more coins - checkAccount(t, ctx, accKeeper, bankKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 38000))) - // contract lost them - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 2000))) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, deposit) -} - -func TestMaskReflectCustomQuery(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // let's perform a normal query of state - ownerQuery := testdata.ReflectQueryMsg{ - Owner: &struct{}{}, - } - ownerQueryBz, err := json.Marshal(ownerQuery) - require.NoError(t, err) - ownerRes, err := keeper.QuerySmart(ctx, contractAddr, ownerQueryBz) - require.NoError(t, err) - var res testdata.OwnerResponse - err = json.Unmarshal(ownerRes, &res) - require.NoError(t, err) - assert.Equal(t, res.Owner, creator.String()) - - // and now making use of the custom querier callbacks - customQuery := testdata.ReflectQueryMsg{ - Capitalized: &testdata.Text{ - Text: "all Caps noW", - }, - } - customQueryBz, err := json.Marshal(customQuery) - require.NoError(t, err) - custom, err := keeper.QuerySmart(ctx, contractAddr, customQueryBz) - require.NoError(t, err) - var resp capitalizedResponse - err = json.Unmarshal(custom, &resp) - require.NoError(t, err) - assert.Equal(t, resp.Text, "ALL CAPS NOW") -} - -func TestReflectStargateQuery(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - funds := sdk.NewCoins(sdk.NewInt64Coin("denom", 320000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - expectedBalance := funds.Sub(contractStart...) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, funds...) - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // first, normal query for the bank balance (to make sure our query is proper) - bankQuery := wasmvmtypes.QueryRequest{ - Bank: &wasmvmtypes.BankQuery{ - AllBalances: &wasmvmtypes.AllBalancesQuery{ - Address: creator.String(), - }, - }, - } - simpleQueryBz, err := json.Marshal(testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{Request: &bankQuery}, - }) - require.NoError(t, err) - simpleRes, err := keeper.QuerySmart(ctx, contractAddr, simpleQueryBz) - require.NoError(t, err) - var simpleChain testdata.ChainResponse - mustParse(t, simpleRes, &simpleChain) - var simpleBalance wasmvmtypes.AllBalancesResponse - mustParse(t, simpleChain.Data, &simpleBalance) - require.Equal(t, len(expectedBalance), len(simpleBalance.Amount)) - assert.Equal(t, simpleBalance.Amount[0].Amount, expectedBalance[0].Amount.String()) - assert.Equal(t, simpleBalance.Amount[0].Denom, expectedBalance[0].Denom) -} - -func TestReflectTotalSupplyQuery(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - // upload code - codeID := StoreReflectContract(t, ctx, keepers).CodeID - // creator instantiates a contract and gives it tokens - creator := RandomAccountAddress(t) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "testing", nil) - require.NoError(t, err) - - currentStakeSupply := keepers.BankKeeper.GetSupply(ctx, "stake") - require.NotEmpty(t, currentStakeSupply.Amount) // ensure we have real data - specs := map[string]struct { - denom string - expAmount wasmvmtypes.Coin - }{ - "known denom": { - denom: "stake", - expAmount: ConvertSdkCoinToWasmCoin(currentStakeSupply), - }, - "unknown denom": { - denom: "unknown", - expAmount: wasmvmtypes.Coin{Denom: "unknown", Amount: "0"}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // when - queryBz := mustMarshal(t, testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{ - Request: &wasmvmtypes.QueryRequest{ - Bank: &wasmvmtypes.BankQuery{ - Supply: &wasmvmtypes.SupplyQuery{Denom: spec.denom}, - }, - }, - }, - }) - simpleRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - - // then - require.NoError(t, err) - var rsp testdata.ChainResponse - mustParse(t, simpleRes, &rsp) - var supplyRsp wasmvmtypes.SupplyResponse - mustParse(t, rsp.Data, &supplyRsp) - assert.Equal(t, spec.expAmount, supplyRsp.Amount, spec.expAmount) - }) - } -} - -func TestReflectInvalidStargateQuery(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - funds := sdk.NewCoins(sdk.NewInt64Coin("denom", 320000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, funds...) - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // now, try to build a protobuf query - protoQuery := banktypes.QueryAllBalancesRequest{ - Address: creator.String(), - } - protoQueryBin, err := proto.Marshal(&protoQuery) - require.NoError(t, err) - - protoRequest := wasmvmtypes.QueryRequest{ - Stargate: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.bank.v1beta1.Query/AllBalances", - Data: protoQueryBin, - }, - } - protoQueryBz, err := json.Marshal(testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{Request: &protoRequest}, - }) - require.NoError(t, err) - - // make a query on the chain, should not be whitelisted - _, err = keeper.QuerySmart(ctx, contractAddr, protoQueryBz) - require.Error(t, err) - require.Contains(t, err.Error(), "Unsupported query") - - // now, try to build a protobuf query - protoRequest = wasmvmtypes.QueryRequest{ - Stargate: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.tx.v1beta1.Service/GetTx", - Data: []byte{}, - }, - } - protoQueryBz, err = json.Marshal(testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{Request: &protoRequest}, - }) - require.NoError(t, err) - - // make a query on the chain, should be blacklisted - _, err = keeper.QuerySmart(ctx, contractAddr, protoQueryBz) - require.Error(t, err) - require.Contains(t, err.Error(), "Unsupported query") - - // and another one - protoRequest = wasmvmtypes.QueryRequest{ - Stargate: &wasmvmtypes.StargateQuery{ - Path: "/cosmos.base.tendermint.v1beta1.Service/GetNodeInfo", - Data: []byte{}, - }, - } - protoQueryBz, err = json.Marshal(testdata.ReflectQueryMsg{ - Chain: &testdata.ChainQuery{Request: &protoRequest}, - }) - require.NoError(t, err) - - // make a query on the chain, should be blacklisted - _, err = keeper.QuerySmart(ctx, contractAddr, protoQueryBz) - require.Error(t, err) - require.Contains(t, err.Error(), "Unsupported query") -} - -type reflectState struct { - Owner string `json:"owner"` -} - -func TestMaskReflectWasmQueries(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload reflect code - reflectID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), reflectID) - - // creator instantiates a contract and gives it tokens - reflectStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) - require.NoError(t, err) - require.NotEmpty(t, reflectAddr) - - // for control, let's make some queries directly on the reflect - ownerQuery := buildReflectQuery(t, &testdata.ReflectQueryMsg{Owner: &struct{}{}}) - res, err := keeper.QuerySmart(ctx, reflectAddr, ownerQuery) - require.NoError(t, err) - var ownerRes testdata.OwnerResponse - mustParse(t, res, &ownerRes) - require.Equal(t, ownerRes.Owner, creator.String()) - - // and a raw query: cosmwasm_storage::Singleton uses 2 byte big-endian length-prefixed to store data - configKey := append([]byte{0, 6}, []byte("config")...) - raw := keeper.QueryRaw(ctx, reflectAddr, configKey) - var stateRes reflectState - mustParse(t, raw, &stateRes) - require.Equal(t, stateRes.Owner, creator.String()) - - // now, let's reflect a smart query into the x/wasm handlers and see if we get the same result - reflectOwnerQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Wasm: &wasmvmtypes.WasmQuery{ - Smart: &wasmvmtypes.SmartQuery{ - ContractAddr: reflectAddr.String(), - Msg: ownerQuery, - }, - }}}} - reflectOwnerBin := buildReflectQuery(t, &reflectOwnerQuery) - res, err = keeper.QuerySmart(ctx, reflectAddr, reflectOwnerBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - var reflectRes testdata.ChainResponse - mustParse(t, res, &reflectRes) - var reflectOwnerRes testdata.OwnerResponse - mustParse(t, reflectRes.Data, &reflectOwnerRes) - require.Equal(t, reflectOwnerRes.Owner, creator.String()) - - // and with queryRaw - reflectStateQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Wasm: &wasmvmtypes.WasmQuery{ - Raw: &wasmvmtypes.RawQuery{ - ContractAddr: reflectAddr.String(), - Key: configKey, - }, - }}}} - reflectStateBin := buildReflectQuery(t, &reflectStateQuery) - res, err = keeper.QuerySmart(ctx, reflectAddr, reflectStateBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - var reflectRawRes testdata.ChainResponse - mustParse(t, res, &reflectRawRes) - // now, with the raw data, we can parse it into state - var reflectStateRes reflectState - mustParse(t, reflectRawRes.Data, &reflectStateRes) - require.Equal(t, reflectStateRes.Owner, creator.String()) -} - -func TestWasmRawQueryWithNil(t *testing.T) { - cdc := MakeEncodingConfig(t).Marshaler - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageEncoders(reflectEncoders(cdc)), WithQueryPlugins(reflectPlugins())) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload reflect code - reflectID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), reflectID) - - // creator instantiates a contract and gives it tokens - reflectStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - reflectAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), "reflect contract 2", reflectStart) - require.NoError(t, err) - require.NotEmpty(t, reflectAddr) - - // control: query directly - missingKey := []byte{0, 1, 2, 3, 4} - raw := keeper.QueryRaw(ctx, reflectAddr, missingKey) - require.Nil(t, raw) - - // and with queryRaw - reflectQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Wasm: &wasmvmtypes.WasmQuery{ - Raw: &wasmvmtypes.RawQuery{ - ContractAddr: reflectAddr.String(), - Key: missingKey, - }, - }}}} - reflectStateBin := buildReflectQuery(t, &reflectQuery) - res, err := keeper.QuerySmart(ctx, reflectAddr, reflectStateBin) - require.NoError(t, err) - - // first we pull out the data from chain response, before parsing the original response - var reflectRawRes testdata.ChainResponse - mustParse(t, res, &reflectRawRes) - // and make sure there is no data - require.Empty(t, reflectRawRes.Data) - // we get an empty byte slice not nil (if anyone care in go-land) - require.Equal(t, []byte{}, reflectRawRes.Data) -} - -func TestRustPanicIsHandled(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, ReflectFeatures) - keeper := keepers.ContractKeeper - - creator := keepers.Faucet.NewFundedRandomAccount(ctx, sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))...) - - // upload code - codeID, _, err := keeper.Create(ctx, creator, testdata.CyberpunkContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - contractAddr, _, err := keeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "cyberpunk contract", nil) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // when panic is triggered - msg := []byte(`{"panic":{}}`) - gotData, err := keeper.Execute(ctx, contractAddr, creator, msg, nil) - require.ErrorIs(t, err, types.ErrExecuteFailed) - assert.Contains(t, err.Error(), "panicked at 'This page intentionally faulted'") - assert.Nil(t, gotData) -} - -func checkAccount(t *testing.T, ctx sdk.Context, accKeeper authkeeper.AccountKeeper, bankKeeper bankkeeper.Keeper, addr sdk.AccAddress, expected sdk.Coins) { - acct := accKeeper.GetAccount(ctx, addr) - if expected == nil { - assert.Nil(t, acct) - } else { - assert.NotNil(t, acct) - if expected.Empty() { - // there is confusion between nil and empty slice... let's just treat them the same - assert.True(t, bankKeeper.GetAllBalances(ctx, acct.GetAddress()).Empty()) - } else { - assert.Equal(t, bankKeeper.GetAllBalances(ctx, acct.GetAddress()), expected) - } - } -} - -/**** Code to support custom messages *****/ - -type reflectCustomMsg struct { - Debug string `json:"debug,omitempty"` - Raw []byte `json:"raw,omitempty"` -} - -// toReflectRawMsg encodes an sdk msg using any type with json encoding. -// Then wraps it as an opaque message -func toReflectRawMsg(cdc codec.Codec, msg sdk.Msg) (wasmvmtypes.CosmosMsg, error) { - codecAny, err := codectypes.NewAnyWithValue(msg) - if err != nil { - return wasmvmtypes.CosmosMsg{}, err - } - rawBz, err := cdc.MarshalJSON(codecAny) - if err != nil { - return wasmvmtypes.CosmosMsg{}, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - customMsg, _ := json.Marshal(reflectCustomMsg{ - Raw: rawBz, - }) - res := wasmvmtypes.CosmosMsg{ - Custom: customMsg, - } - return res, err -} - -// reflectEncoders needs to be registered in test setup to handle custom message callbacks -func reflectEncoders(cdc codec.Codec) *MessageEncoders { - return &MessageEncoders{ - Custom: fromReflectRawMsg(cdc), - } -} - -// fromReflectRawMsg decodes msg.Data to an sdk.Msg using proto Any and json encoding. -// this needs to be registered on the Encoders -func fromReflectRawMsg(cdc codec.Codec) CustomEncoder { - return func(_sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - var custom reflectCustomMsg - err := json.Unmarshal(msg, &custom) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - if custom.Raw != nil { - var codecAny codectypes.Any - if err := cdc.UnmarshalJSON(custom.Raw, &codecAny); err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - var msg sdk.Msg - if err := cdc.UnpackAny(&codecAny, &msg); err != nil { - return nil, err - } - return []sdk.Msg{msg}, nil - } - if custom.Debug != "" { - return nil, errorsmod.Wrapf(types.ErrInvalidMsg, "Custom Debug: %s", custom.Debug) - } - return nil, errorsmod.Wrap(types.ErrInvalidMsg, "Unknown Custom message variant") - } -} - -type reflectCustomQuery struct { - Ping *struct{} `json:"ping,omitempty"` - Capitalized *testdata.Text `json:"capitalized,omitempty"` -} - -// this is from the go code back to the contract (capitalized or ping) -type customQueryResponse struct { - Msg string `json:"msg"` -} - -// this is from the contract to the go code (capitalized or ping) -type capitalizedResponse struct { - Text string `json:"text"` -} - -// reflectPlugins needs to be registered in test setup to handle custom query callbacks -func reflectPlugins() *QueryPlugins { - return &QueryPlugins{ - Custom: performCustomQuery, - } -} - -func performCustomQuery(_ sdk.Context, request json.RawMessage) ([]byte, error) { - var custom reflectCustomQuery - err := json.Unmarshal(request, &custom) - if err != nil { - return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) - } - if custom.Capitalized != nil { - msg := strings.ToUpper(custom.Capitalized.Text) - return json.Marshal(customQueryResponse{Msg: msg}) - } - if custom.Ping != nil { - return json.Marshal(customQueryResponse{Msg: "pong"}) - } - return nil, errorsmod.Wrap(types.ErrInvalidMsg, "Unknown Custom query variant") -} diff --git a/x/wasm/keeper/relay.go b/x/wasm/keeper/relay.go deleted file mode 100644 index a265179..0000000 --- a/x/wasm/keeper/relay.go +++ /dev/null @@ -1,203 +0,0 @@ -package keeper - -import ( - "time" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/telemetry" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.IBCContractKeeper = (*Keeper)(nil) - -// OnOpenChannel calls the contract to participate in the IBC channel handshake step. -// In the IBC protocol this is either the `Channel Open Init` event on the initiating chain or -// `Channel Open Try` on the counterparty chain. -// Protocol version and channel ordering should be verified for example. -// See https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#channel-lifecycle-management -func (k Keeper) OnOpenChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelOpenMsg, -) (string, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-open-channel") - _, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return "", err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCChannelOpen(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return "", errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - if res != nil { - return res.Version, nil - } - return "", nil -} - -// OnConnectChannel calls the contract to let it know the IBC channel was established. -// In the IBC protocol this is either the `Channel Open Ack` event on the initiating chain or -// `Channel Open Confirm` on the counterparty chain. -// -// There is an open issue with the [cosmos-sdk](https://github.com/cosmos/cosmos-sdk/issues/8334) -// that the counterparty channelID is empty on the initiating chain -// See https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#channel-lifecycle-management -func (k Keeper) OnConnectChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelConnectMsg, -) error { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-connect-channel") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCChannelConnect(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) -} - -// OnCloseChannel calls the contract to let it know the IBC channel is closed. -// Calling modules MAY atomically execute appropriate application logic in conjunction with calling chanCloseConfirm. -// -// Once closed, channels cannot be reopened and identifiers cannot be reused. Identifier reuse is prevented because -// we want to prevent potential replay of previously sent packets -// See https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#channel-lifecycle-management -func (k Keeper) OnCloseChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelCloseMsg, -) error { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-close-channel") - - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return err - } - - params := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCChannelClose(codeInfo.CodeHash, params, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) -} - -// OnRecvPacket calls the contract to process the incoming IBC packet. The contract fully owns the data processing and -// returns the acknowledgement data for the chain level. This allows custom applications and protocols on top -// of IBC. Although it is recommended to use the standard acknowledgement envelope defined in -// https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#acknowledgement-envelope -// -// For more information see: https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#packet-flow--handling -func (k Keeper) OnRecvPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketReceiveMsg, -) ([]byte, error) { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-recv-packet") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return nil, err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCPacketReceive(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - panic(execErr) - } - if res.Err != "" { // handle error case as before https://github.com/CosmWasm/wasmvm/commit/c300106fe5c9426a495f8e10821e00a9330c56c6 - return nil, errorsmod.Wrap(types.ErrExecuteFailed, res.Err) - } - // note submessage reply results can overwrite the `Acknowledgement` data - return k.handleContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res.Ok.Messages, res.Ok.Attributes, res.Ok.Acknowledgement, res.Ok.Events) -} - -// OnAckPacket calls the contract to handle the "acknowledgement" data which can contain success or failure of a packet -// acknowledgement written on the receiving chain for example. This is application level data and fully owned by the -// contract. The use of the standard acknowledgement envelope is recommended: https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#acknowledgement-envelope -// -// On application errors the contract can revert an operation like returning tokens as in ibc-transfer. -// -// For more information see: https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#packet-flow--handling -func (k Keeper) OnAckPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketAckMsg, -) error { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-ack-packet") - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCPacketAck(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) -} - -// OnTimeoutPacket calls the contract to let it know the packet was never received on the destination chain within -// the timeout boundaries. -// The contract should handle this on the application level and undo the original operation -func (k Keeper) OnTimeoutPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketTimeoutMsg, -) error { - defer telemetry.MeasureSince(time.Now(), "wasm", "contract", "ibc-timeout-packet") - - contractInfo, codeInfo, prefixStore, err := k.contractInstance(ctx, contractAddr) - if err != nil { - return err - } - - env := types.NewEnv(ctx, contractAddr) - querier := k.newQueryHandler(ctx, contractAddr) - - gas := k.runtimeGasForContract(ctx) - res, gasUsed, execErr := k.wasmVM.IBCPacketTimeout(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) - k.consumeRuntimeGas(ctx, gasUsed) - if execErr != nil { - return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) - } - - return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) -} - -func (k Keeper) handleIBCBasicContractResponse(ctx sdk.Context, addr sdk.AccAddress, id string, res *wasmvmtypes.IBCBasicResponse) error { - _, err := k.handleContractResponse(ctx, addr, id, res.Messages, res.Attributes, nil, res.Events) - return err -} diff --git a/x/wasm/keeper/relay_test.go b/x/wasm/keeper/relay_test.go deleted file mode 100644 index c9c72ad..0000000 --- a/x/wasm/keeper/relay_test.go +++ /dev/null @@ -1,711 +0,0 @@ -package keeper - -import ( - "encoding/json" - "errors" - "math" - "testing" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestOnOpenChannel(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractGas sdk.Gas - contractErr error - expGas uint64 - expErr bool - }{ - "consume contract gas": { - contractAddr: example.Contract, - contractGas: myContractGas, - expGas: myContractGas, - }, - "consume max gas": { - contractAddr: example.Contract, - contractGas: math.MaxUint64 / DefaultGasMultiplier, - expGas: math.MaxUint64 / DefaultGasMultiplier, - }, - "consume gas on error": { - contractAddr: example.Contract, - contractGas: myContractGas, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myChannel := wasmvmtypes.IBCChannel{Version: "my test channel"} - myMsg := wasmvmtypes.IBCChannelOpenMsg{OpenTry: &wasmvmtypes.IBCOpenTry{Channel: myChannel, CounterpartyVersion: "foo"}} - m.IBCChannelOpenFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - assert.Equal(t, myMsg, msg) - return &wasmvmtypes.IBC3ChannelOpenResponse{}, spec.contractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - - // when - msg := wasmvmtypes.IBCChannelOpenMsg{ - OpenTry: &wasmvmtypes.IBCOpenTry{ - Channel: myChannel, - CounterpartyVersion: "foo", - }, - } - _, err := keepers.WasmKeeper.OnOpenChannel(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - }) - } -} - -func TestOnConnectChannel(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCBasicResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - expContractGas sdk.Gas - expErr bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "messenger errors returned, events stored": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myChannel := wasmvmtypes.IBCChannel{Version: "my test channel"} - myMsg := wasmvmtypes.IBCChannelConnectMsg{OpenConfirm: &wasmvmtypes.IBCOpenConfirm{Channel: myChannel}} - m.IBCChannelConnectFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - assert.Equal(t, msg, myMsg) - return spec.contractResp, myContractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - ctx = ctx.WithEventManager(sdk.NewEventManager()) - - before := ctx.GasMeter().GasConsumed() - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - msg := wasmvmtypes.IBCChannelConnectMsg{ - OpenConfirm: &wasmvmtypes.IBCOpenConfirm{ - Channel: myChannel, - }, - } - - err := keepers.WasmKeeper.OnConnectChannel(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func TestOnCloseChannel(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCBasicResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - expContractGas sdk.Gas - expErr bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "messenger errors returned, events stored": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myChannel := wasmvmtypes.IBCChannel{Version: "my test channel"} - myMsg := wasmvmtypes.IBCChannelCloseMsg{CloseInit: &wasmvmtypes.IBCCloseInit{Channel: myChannel}} - m.IBCChannelCloseFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - assert.Equal(t, msg, myMsg) - return spec.contractResp, myContractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - msg := wasmvmtypes.IBCChannelCloseMsg{ - CloseInit: &wasmvmtypes.IBCCloseInit{ - Channel: myChannel, - }, - } - err := keepers.WasmKeeper.OnCloseChannel(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func TestOnRecvPacket(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - const storageCosts = sdk.Gas(2903) - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCReceiveResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - mockReplyFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - expContractGas sdk.Gas - expAck []byte - expErr bool - expPanic bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - }, - expAck: []byte("myAck"), - }, - "can return empty ack": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCReceiveResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expPanic: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - expAck: []byte("myAck"), - }, - "emit contract attributes on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - expAck: []byte("myAck"), - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 46, // charge or custom event as well - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - Events: []wasmvmtypes.Event{{ - Type: "custom", - Attributes: []wasmvmtypes.EventAttribute{{ - Key: "message", - Value: "to rudi", - }}, - }}, - }, - expEventTypes: []string{types.WasmModuleEventType, "wasm-custom"}, - expAck: []byte("myAck"), - }, - "messenger errors returned, events stored": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "submessage reply can overwrite ack data": { - contractAddr: example.Contract, - expContractGas: myContractGas + storageCosts, - contractResp: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: []byte("myAck"), - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyAlways, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - }, - mockReplyFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{Data: []byte("myBetterAck")}, 0, nil - }, - expAck: []byte("myBetterAck"), - expEventTypes: []string{types.EventTypeReply}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myPacket := wasmvmtypes.IBCPacket{Data: []byte("my data")} - - m.IBCPacketReceiveFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - assert.Equal(t, myPacket, msg.Packet) - return &wasmvmtypes.IBCReceiveResult{Ok: spec.contractResp}, myContractGas * DefaultGasMultiplier, spec.contractErr - } - if spec.mockReplyFn != nil { - m.ReplyFn = spec.mockReplyFn - h, ok := keepers.WasmKeeper.wasmVMResponseHandler.(*DefaultWasmVMContractResponseHandler) - require.True(t, ok) - h.md = NewMessageDispatcher(messenger, keepers.WasmKeeper) - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - msg := wasmvmtypes.IBCPacketReceiveMsg{Packet: myPacket} - if spec.expPanic { - assert.Panics(t, func() { - keepers.WasmKeeper.OnRecvPacket(ctx, spec.contractAddr, msg) //nolint:errcheck // we are checking for a panic here - }) - return - } - gotAck, err := keepers.WasmKeeper.OnRecvPacket(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - require.Equal(t, spec.expAck, gotAck) - - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func TestOnAckPacket(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCBasicResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - expContractGas sdk.Gas - expErr bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "messenger errors returned, events stored": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myAck := wasmvmtypes.IBCPacketAckMsg{Acknowledgement: wasmvmtypes.IBCAcknowledgement{Data: []byte("myAck")}} - m.IBCPacketAckFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - assert.Equal(t, myAck, msg) - return spec.contractResp, myContractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - err := keepers.WasmKeeper.OnAckPacket(ctx, spec.contractAddr, myAck) - - // then - - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func TestOnTimeoutPacket(t *testing.T) { - var m wasmtesting.MockWasmer - wasmtesting.MakeIBCInstantiable(&m) - messenger := &wasmtesting.MockMessageHandler{} - parentCtx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithMessageHandler(messenger)) - example := SeedNewContractInstance(t, parentCtx, keepers, &m) - const myContractGas = 40 - - specs := map[string]struct { - contractAddr sdk.AccAddress - contractResp *wasmvmtypes.IBCBasicResponse - contractErr error - overwriteMessenger *wasmtesting.MockMessageHandler - expContractGas sdk.Gas - expErr bool - expEventTypes []string - }{ - "consume contract gas": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{}, - }, - "consume gas on error, ignore events + messages": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - contractErr: errors.New("test, ignore"), - expErr: true, - }, - "dispatch contract messages on success": { - contractAddr: example.Contract, - expContractGas: myContractGas, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - }, - }, - "emit contract attributes on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "emit contract events on success": { - contractAddr: example.Contract, - expContractGas: myContractGas + 46, // cost for custom events - contractResp: &wasmvmtypes.IBCBasicResponse{ - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - Events: []wasmvmtypes.Event{{ - Type: "custom", - Attributes: []wasmvmtypes.EventAttribute{{ - Key: "message", - Value: "to rudi", - }}, - }}, - }, - expEventTypes: []string{types.WasmModuleEventType, "wasm-custom"}, - }, - "messenger errors returned, events stored before": { - contractAddr: example.Contract, - expContractGas: myContractGas + 10, - contractResp: &wasmvmtypes.IBCBasicResponse{ - Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: &wasmvmtypes.BankMsg{}}}, {ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Custom: json.RawMessage(`{"foo":"bar"}`)}}}, - Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, - }, - overwriteMessenger: wasmtesting.NewErroringMessageHandler(), - expErr: true, - expEventTypes: []string{types.WasmModuleEventType}, - }, - "unknown contract address": { - contractAddr: RandomAccountAddress(t), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - myPacket := wasmvmtypes.IBCPacket{Data: []byte("my test packet")} - m.IBCPacketTimeoutFn = func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - assert.Equal(t, myPacket, msg.Packet) - return spec.contractResp, myContractGas * DefaultGasMultiplier, spec.contractErr - } - - ctx, _ := parentCtx.CacheContext() - before := ctx.GasMeter().GasConsumed() - msger, capturedMsgs := wasmtesting.NewCapturingMessageHandler() - *messenger = *msger - - if spec.overwriteMessenger != nil { - *messenger = *spec.overwriteMessenger - } - - // when - msg := wasmvmtypes.IBCPacketTimeoutMsg{Packet: myPacket} - err := keepers.WasmKeeper.OnTimeoutPacket(ctx, spec.contractAddr, msg) - - // then - if spec.expErr { - require.Error(t, err) - assert.Empty(t, capturedMsgs) // no messages captured on error - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - return - } - require.NoError(t, err) - // verify gas consumed - const storageCosts = sdk.Gas(2903) - assert.Equal(t, spec.expContractGas, ctx.GasMeter().GasConsumed()-before-storageCosts) - // verify msgs dispatched - require.Len(t, *capturedMsgs, len(spec.contractResp.Messages)) - for i, m := range spec.contractResp.Messages { - assert.Equal(t, (*capturedMsgs)[i], m.Msg) - } - assert.Equal(t, spec.expEventTypes, stripTypes(ctx.EventManager().Events())) - }) - } -} - -func stripTypes(events sdk.Events) []string { - var r []string - for _, e := range events { - r = append(r, e.Type) - } - return r -} diff --git a/x/wasm/keeper/snapshotter.go b/x/wasm/keeper/snapshotter.go deleted file mode 100644 index 3642c51..0000000 --- a/x/wasm/keeper/snapshotter.go +++ /dev/null @@ -1,141 +0,0 @@ -package keeper - -import ( - "encoding/hex" - "io" - - errorsmod "cosmossdk.io/errors" - "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - snapshot "github.com/cosmos/cosmos-sdk/snapshots/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/ioutils" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ snapshot.ExtensionSnapshotter = &WasmSnapshotter{} - -// SnapshotFormat format 1 is just gzipped wasm byte code for each item payload. No protobuf envelope, no metadata. -const SnapshotFormat = 1 - -type WasmSnapshotter struct { - wasm *Keeper - cms sdk.MultiStore -} - -func NewWasmSnapshotter(cms sdk.MultiStore, wasm *Keeper) *WasmSnapshotter { - return &WasmSnapshotter{ - wasm: wasm, - cms: cms, - } -} - -func (ws *WasmSnapshotter) SnapshotName() string { - return types.ModuleName -} - -func (ws *WasmSnapshotter) SnapshotFormat() uint32 { - return SnapshotFormat -} - -func (ws *WasmSnapshotter) SupportedFormats() []uint32 { - // If we support older formats, add them here and handle them in Restore - return []uint32{SnapshotFormat} -} - -func (ws *WasmSnapshotter) SnapshotExtension(height uint64, payloadWriter snapshot.ExtensionPayloadWriter) error { - cacheMS, err := ws.cms.CacheMultiStoreWithVersion(int64(height)) - if err != nil { - return err - } - - ctx := sdk.NewContext(cacheMS, tmproto.Header{}, false, log.NewNopLogger()) - seenBefore := make(map[string]bool) - var rerr error - - ws.wasm.IterateCodeInfos(ctx, func(id uint64, info types.CodeInfo) bool { - // Many code ids may point to the same code hash... only sync it once - hexHash := hex.EncodeToString(info.CodeHash) - // if seenBefore, just skip this one and move to the next - if seenBefore[hexHash] { - return false - } - seenBefore[hexHash] = true - - // load code and abort on error - wasmBytes, err := ws.wasm.GetByteCode(ctx, id) - if err != nil { - rerr = err - return true - } - - compressedWasm, err := ioutils.GzipIt(wasmBytes) - if err != nil { - rerr = err - return true - } - - err = payloadWriter(compressedWasm) - if err != nil { - rerr = err - return true - } - - return false - }) - - return rerr -} - -func (ws *WasmSnapshotter) RestoreExtension(height uint64, format uint32, payloadReader snapshot.ExtensionPayloadReader) error { - if format == SnapshotFormat { - return ws.processAllItems(height, payloadReader, restoreV1, finalizeV1) - } - return snapshot.ErrUnknownFormat -} - -func restoreV1(_ sdk.Context, k *Keeper, compressedCode []byte) error { - if !ioutils.IsGzip(compressedCode) { - return types.ErrInvalid.Wrap("not a gzip") - } - wasmCode, err := ioutils.Uncompress(compressedCode, uint64(types.MaxWasmSize)) - if err != nil { - return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - - // FIXME: check which codeIDs the checksum matches?? - _, err = k.wasmVM.Create(wasmCode) - if err != nil { - return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) - } - return nil -} - -func finalizeV1(ctx sdk.Context, k *Keeper) error { - // FIXME: ensure all codes have been uploaded? - return k.InitializePinnedCodes(ctx) -} - -func (ws *WasmSnapshotter) processAllItems( - height uint64, - payloadReader snapshot.ExtensionPayloadReader, - cb func(sdk.Context, *Keeper, []byte) error, - finalize func(sdk.Context, *Keeper) error, -) error { - ctx := sdk.NewContext(ws.cms, tmproto.Header{Height: int64(height)}, false, log.NewNopLogger()) - for { - payload, err := payloadReader() - if err == io.EOF { - break - } else if err != nil { - return err - } - - if err := cb(ctx, ws.wasm, payload); err != nil { - return errorsmod.Wrap(err, "processing snapshot item") - } - } - - return finalize(ctx, ws.wasm) -} diff --git a/x/wasm/keeper/snapshotter_integration_test.go b/x/wasm/keeper/snapshotter_integration_test.go deleted file mode 100644 index 2925f09..0000000 --- a/x/wasm/keeper/snapshotter_integration_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package keeper_test - -import ( - "crypto/sha256" - "os" - "testing" - "time" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - "github.com/stretchr/testify/assert" - - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtypes "github.com/cometbft/cometbft/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - 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" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm/keeper" -) - -func TestSnapshotter(t *testing.T) { - specs := map[string]struct { - wasmFiles []string - }{ - "single contract": { - wasmFiles: []string{"./testdata/reflect.wasm"}, - }, - "multiple contract": { - wasmFiles: []string{"./testdata/reflect.wasm", "./testdata/burner.wasm", "./testdata/reflect.wasm"}, - }, - "duplicate contracts": { - wasmFiles: []string{"./testdata/reflect.wasm", "./testdata/reflect.wasm"}, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - // setup source app - srcTerpApp, genesisAddr := newWasmExampleApp(t) - - // store wasm codes on chain - ctx := srcTerpApp.NewUncachedContext(false, tmproto.Header{ - ChainID: "foo", - Height: srcTerpApp.LastBlockHeight() + 1, - Time: time.Now(), - }) - wasmKeeper := srcTerpApp.WasmKeeper - contractKeeper := keeper.NewDefaultPermissionKeeper(&wasmKeeper) - - srcCodeIDToChecksum := make(map[uint64][]byte, len(spec.wasmFiles)) - for i, v := range spec.wasmFiles { - wasmCode, err := os.ReadFile(v) - require.NoError(t, err) - codeID, checksum, err := contractKeeper.Create(ctx, genesisAddr, wasmCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(i+1), codeID) - srcCodeIDToChecksum[codeID] = checksum - } - // create snapshot - srcTerpApp.Commit() - snapshotHeight := uint64(srcTerpApp.LastBlockHeight()) - snapshot, err := srcTerpApp.SnapshotManager().Create(snapshotHeight) - require.NoError(t, err) - assert.NotNil(t, snapshot) - - // when snapshot imported into dest app instance - destTerpApp := app.SetupWithEmptyStore(t) - require.NoError(t, destTerpApp.SnapshotManager().Restore(*snapshot)) - for i := uint32(0); i < snapshot.Chunks; i++ { - chunkBz, err := srcTerpApp.SnapshotManager().LoadChunk(snapshot.Height, snapshot.Format, i) - require.NoError(t, err) - end, err := destTerpApp.SnapshotManager().RestoreChunk(chunkBz) - require.NoError(t, err) - if end { - break - } - } - - // then all wasm contracts are imported - wasmKeeper = destTerpApp.WasmKeeper - ctx = destTerpApp.NewUncachedContext(false, tmproto.Header{ - ChainID: "foo", - Height: destTerpApp.LastBlockHeight() + 1, - Time: time.Now(), - }) - - destCodeIDToChecksum := make(map[uint64][]byte, len(spec.wasmFiles)) - wasmKeeper.IterateCodeInfos(ctx, func(id uint64, info types.CodeInfo) bool { - bz, err := wasmKeeper.GetByteCode(ctx, id) - require.NoError(t, err) - hash := sha256.Sum256(bz) - destCodeIDToChecksum[id] = hash[:] - assert.Equal(t, hash[:], info.CodeHash) - return false - }) - assert.Equal(t, srcCodeIDToChecksum, destCodeIDToChecksum) - }) - } -} - -func newWasmExampleApp(t *testing.T) (*app.TerpApp, sdk.AccAddress) { - senderPrivKey := ed25519.GenPrivKey() - pubKey, err := cryptocodec.ToTmPubKeyInterface(senderPrivKey.PubKey()) - require.NoError(t, err) - - senderAddr := senderPrivKey.PubKey().Address().Bytes() - acc := authtypes.NewBaseAccount(senderAddr, senderPrivKey.PubKey(), 0, 0) - amount, ok := sdk.NewIntFromString("10000000000000000000") - require.True(t, ok) - - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amount)), - } - validator := tmtypes.NewValidator(pubKey, 1) - valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - wasmApp := app.SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, "testing", nil, balance) - - return wasmApp, senderAddr -} diff --git a/x/wasm/keeper/staking_test.go b/x/wasm/keeper/staking_test.go deleted file mode 100644 index eb26f9c..0000000 --- a/x/wasm/keeper/staking_test.go +++ /dev/null @@ -1,739 +0,0 @@ -package keeper - -import ( - "encoding/json" - "os" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - sdk "github.com/cosmos/cosmos-sdk/types" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type StakingInitMsg struct { - Name string `json:"name"` - Symbol string `json:"symbol"` - Decimals uint8 `json:"decimals"` - Validator sdk.ValAddress `json:"validator"` - ExitTax sdk.Dec `json:"exit_tax"` - // MinWithdrawal is uint128 encoded as a string (use math.Int?) - MinWithdrawl string `json:"min_withdrawal"` -} - -// StakingHandleMsg is used to encode handle messages -type StakingHandleMsg struct { - Transfer *transferPayload `json:"transfer,omitempty"` - Bond *struct{} `json:"bond,omitempty"` - Unbond *unbondPayload `json:"unbond,omitempty"` - Claim *struct{} `json:"claim,omitempty"` - Reinvest *struct{} `json:"reinvest,omitempty"` - Change *testdata.OwnerPayload `json:"change_owner,omitempty"` -} - -type transferPayload struct { - Recipient sdk.Address `json:"recipient"` - // uint128 encoded as string - Amount string `json:"amount"` -} - -type unbondPayload struct { - // uint128 encoded as string - Amount string `json:"amount"` -} - -// StakingQueryMsg is used to encode query messages -type StakingQueryMsg struct { - Balance *addressQuery `json:"balance,omitempty"` - Claims *addressQuery `json:"claims,omitempty"` - TokenInfo *struct{} `json:"token_info,omitempty"` - Investment *struct{} `json:"investment,omitempty"` -} - -type addressQuery struct { - Address sdk.AccAddress `json:"address"` -} - -type BalanceResponse struct { - Balance string `json:"balance,omitempty"` -} - -type ClaimsResponse struct { - Claims string `json:"claims,omitempty"` -} - -type TokenInfoResponse struct { - Name string `json:"name"` - Symbol string `json:"symbol"` - Decimals uint8 `json:"decimals"` -} - -type InvestmentResponse struct { - TokenSupply string `json:"token_supply"` - StakedTokens sdk.Coin `json:"staked_tokens"` - NominalValue sdk.Dec `json:"nominal_value"` - Owner sdk.AccAddress `json:"owner"` - Validator sdk.ValAddress `json:"validator"` - ExitTax sdk.Dec `json:"exit_tax"` - // MinWithdrawl is uint128 encoded as a string (use math.Int?) - MinWithdrawl string `json:"min_withdrawal"` -} - -func TestInitializeStaking(t *testing.T) { - ctx, k := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, stakingKeeper, keeper, bankKeeper := k.AccountKeeper, k.StakingKeeper, k.ContractKeeper, k.BankKeeper - - valAddr := addValidator(t, ctx, stakingKeeper, k.Faucet, sdk.NewInt64Coin("stake", 1234567)) - ctx = nextBlock(ctx, stakingKeeper) - v, found := stakingKeeper.GetValidator(ctx, valAddr) - assert.True(t, found) - assert.Equal(t, v.GetDelegatorShares(), sdk.NewDec(1234567)) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000), sdk.NewInt64Coin("stake", 500000)) - creator := k.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload staking derivates code - stakingCode, err := os.ReadFile("./testdata/staking.wasm") - require.NoError(t, err) - stakingID, _, err := keeper.Create(ctx, creator, stakingCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), stakingID) - - // register to a valid address - initMsg := StakingInitMsg{ - Name: "Staking Derivatives", - Symbol: "DRV", - Decimals: 0, - Validator: valAddr, - ExitTax: sdk.MustNewDecFromStr("0.10"), - MinWithdrawl: "100", - } - initBz, err := json.Marshal(&initMsg) - require.NoError(t, err) - - stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, initBz, "staking derivates - DRV", nil) - require.NoError(t, err) - require.NotEmpty(t, stakingAddr) - - // nothing spent here - checkAccount(t, ctx, accKeeper, bankKeeper, creator, deposit) - - // try to register with a validator not on the list and it fails - _, bob := keyPubAddr() - badInitMsg := StakingInitMsg{ - Name: "Missing Validator", - Symbol: "MISS", - Decimals: 0, - Validator: sdk.ValAddress(bob), - ExitTax: sdk.MustNewDecFromStr("0.10"), - MinWithdrawl: "100", - } - badBz, err := json.Marshal(&badInitMsg) - require.NoError(t, err) - - _, _, err = k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, badBz, "missing validator", nil) - require.Error(t, err) - - // no changes to bonding shares - val, _ := stakingKeeper.GetValidator(ctx, valAddr) - assert.Equal(t, val.GetDelegatorShares(), sdk.NewDec(1234567)) -} - -type initInfo struct { - valAddr sdk.ValAddress - creator sdk.AccAddress - contractAddr sdk.AccAddress - - ctx sdk.Context - accKeeper authkeeper.AccountKeeper - stakingKeeper *stakingkeeper.Keeper - distKeeper distributionkeeper.Keeper - wasmKeeper Keeper - contractKeeper wasmtypes.ContractOpsKeeper - bankKeeper bankkeeper.Keeper - faucet *TestFaucet -} - -func initializeStaking(t *testing.T) initInfo { - ctx, k := CreateTestInput(t, false, AvailableCapabilities) - accKeeper, stakingKeeper, keeper, bankKeeper := k.AccountKeeper, k.StakingKeeper, k.WasmKeeper, k.BankKeeper - - valAddr := addValidator(t, ctx, stakingKeeper, k.Faucet, sdk.NewInt64Coin("stake", 1000000)) - ctx = nextBlock(ctx, stakingKeeper) - - v, found := stakingKeeper.GetValidator(ctx, valAddr) - assert.True(t, found) - assert.Equal(t, v.GetDelegatorShares(), sdk.NewDec(1000000)) - assert.Equal(t, v.Status, stakingtypes.Bonded) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000), sdk.NewInt64Coin("stake", 500000)) - creator := k.Faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload staking derivates code - stakingCode, err := os.ReadFile("./testdata/staking.wasm") - require.NoError(t, err) - stakingID, _, err := k.ContractKeeper.Create(ctx, creator, stakingCode, nil) - require.NoError(t, err) - require.Equal(t, uint64(1), stakingID) - - // register to a valid address - initMsg := StakingInitMsg{ - Name: "Staking Derivatives", - Symbol: "DRV", - Decimals: 0, - Validator: valAddr, - ExitTax: sdk.MustNewDecFromStr("0.10"), - MinWithdrawl: "100", - } - initBz, err := json.Marshal(&initMsg) - require.NoError(t, err) - - stakingAddr, _, err := k.ContractKeeper.Instantiate(ctx, stakingID, creator, nil, initBz, "staking derivates - DRV", nil) - require.NoError(t, err) - require.NotEmpty(t, stakingAddr) - - return initInfo{ - valAddr: valAddr, - creator: creator, - contractAddr: stakingAddr, - ctx: ctx, - accKeeper: accKeeper, - stakingKeeper: stakingKeeper, - wasmKeeper: *keeper, - distKeeper: k.DistKeeper, - bankKeeper: bankKeeper, - contractKeeper: k.ContractKeeper, - faucet: k.Faucet, - } -} - -func TestBonding(t *testing.T) { - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper, accKeeper, bankKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper, initInfo.bankKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - initPower := val.GetDelegatorShares() - - // bob has 160k, putting 80k into the contract - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 160000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 80000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - // check contract state before - assertBalance(t, ctx, keeper, contractAddr, bob, "0") - assertClaims(t, ctx, keeper, contractAddr, bob, "0") - assertSupply(t, ctx, keeper, contractAddr, "0", sdk.NewInt64Coin("stake", 0)) - - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // check some account values - the money is on neither account (cuz it is bonded) - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.Coins{}) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, funds) - - // make sure the proper number of tokens have been bonded - val, _ = stakingKeeper.GetValidator(ctx, valAddr) - finalPower := val.GetDelegatorShares() - assert.Equal(t, sdk.NewInt(80000), finalPower.Sub(initPower).TruncateInt()) - - // check the delegation itself - d, found := stakingKeeper.GetDelegation(ctx, contractAddr, valAddr) - require.True(t, found) - assert.Equal(t, d.Shares, sdk.MustNewDecFromStr("80000")) - - // check we have the desired balance - assertBalance(t, ctx, keeper, contractAddr, bob, "80000") - assertClaims(t, ctx, keeper, contractAddr, bob, "0") - assertSupply(t, ctx, keeper, contractAddr, "80000", sdk.NewInt64Coin("stake", 80000)) -} - -func TestUnbonding(t *testing.T) { - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper, accKeeper, bankKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper, initInfo.bankKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - initPower := val.GetDelegatorShares() - - // bob has 160k, putting 80k into the contract - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 160000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 80000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // update height a bit - ctx = nextBlock(ctx, stakingKeeper) - - // now unbond 30k - note that 3k (10%) goes to the owner as a tax, 27k unbonded and available as claims - unbond := StakingHandleMsg{ - Unbond: &unbondPayload{ - Amount: "30000", - }, - } - unbondBz, err := json.Marshal(unbond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, unbondBz, nil) - require.NoError(t, err) - - // check some account values - the money is on neither account (cuz it is bonded) - // Note: why is this immediate? just test setup? - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.Coins{}) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, funds) - - // make sure the proper number of tokens have been bonded (80k - 27k = 53k) - val, _ = stakingKeeper.GetValidator(ctx, valAddr) - finalPower := val.GetDelegatorShares() - assert.Equal(t, sdk.NewInt(53000), finalPower.Sub(initPower).TruncateInt(), finalPower.String()) - - // check the delegation itself - d, found := stakingKeeper.GetDelegation(ctx, contractAddr, valAddr) - require.True(t, found) - assert.Equal(t, d.Shares, sdk.MustNewDecFromStr("53000")) - - // check there is unbonding in progress - un, found := stakingKeeper.GetUnbondingDelegation(ctx, contractAddr, valAddr) - require.True(t, found) - require.Equal(t, 1, len(un.Entries)) - assert.Equal(t, "27000", un.Entries[0].Balance.String()) - - // check we have the desired balance - assertBalance(t, ctx, keeper, contractAddr, bob, "50000") - assertBalance(t, ctx, keeper, contractAddr, initInfo.creator, "3000") - assertClaims(t, ctx, keeper, contractAddr, bob, "27000") - assertSupply(t, ctx, keeper, contractAddr, "53000", sdk.NewInt64Coin("stake", 53000)) -} - -func TestReinvest(t *testing.T) { - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper, accKeeper, bankKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper, initInfo.bankKeeper - distKeeper := initInfo.distKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - initPower := val.GetDelegatorShares() - assert.Equal(t, val.Tokens, sdk.NewInt(1000000), "%s", val.Tokens) - - // full is 2x funds, 1x goes to the contract, other stays on his wallet - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 200000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - // we will stake 200k to a validator with 1M self-bond - // this means we should get 1/6 of the rewards - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // update height a bit to solidify the delegation - ctx = nextBlock(ctx, stakingKeeper) - // we get 1/6, our share should be 40k minus 10% commission = 36k - setValidatorRewards(ctx, stakingKeeper, distKeeper, valAddr, "240000") - - // this should withdraw our outstanding 36k of rewards and reinvest them in the same delegation - reinvest := StakingHandleMsg{ - Reinvest: &struct{}{}, - } - reinvestBz, err := json.Marshal(reinvest) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, reinvestBz, nil) - require.NoError(t, err) - - // check some account values - the money is on neither account (cuz it is bonded) - // Note: why is this immediate? just test setup? - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.Coins{}) - checkAccount(t, ctx, accKeeper, bankKeeper, bob, funds) - - // check the delegation itself - d, found := stakingKeeper.GetDelegation(ctx, contractAddr, valAddr) - require.True(t, found) - // we started with 200k and added 36k - assert.Equal(t, d.Shares, sdk.MustNewDecFromStr("236000")) - - // make sure the proper number of tokens have been bonded (80k + 40k = 120k) - val, _ = stakingKeeper.GetValidator(ctx, valAddr) - finalPower := val.GetDelegatorShares() - assert.Equal(t, sdk.NewInt(236000), finalPower.Sub(initPower).TruncateInt(), finalPower.String()) - - // check there is no unbonding in progress - un, found := stakingKeeper.GetUnbondingDelegation(ctx, contractAddr, valAddr) - assert.False(t, found, "%#v", un) - - // check we have the desired balance - assertBalance(t, ctx, keeper, contractAddr, bob, "200000") - assertBalance(t, ctx, keeper, contractAddr, initInfo.creator, "0") - assertClaims(t, ctx, keeper, contractAddr, bob, "0") - assertSupply(t, ctx, keeper, contractAddr, "200000", sdk.NewInt64Coin("stake", 236000)) -} - -func TestQueryStakingInfo(t *testing.T) { - // STEP 1: take a lot of setup from TestReinvest so we have non-zero info - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper - distKeeper := initInfo.distKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - assert.Equal(t, sdk.NewInt(1000000), val.Tokens) - - // full is 2x funds, 1x goes to the contract, other stays on his wallet - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 200000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - // we will stake 200k to a validator with 1M self-bond - // this means we should get 1/6 of the rewards - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // update height a bit to solidify the delegation - ctx = nextBlock(ctx, stakingKeeper) - // we get 1/6, our share should be 40k minus 10% commission = 36k - setValidatorRewards(ctx, stakingKeeper, distKeeper, valAddr, "240000") - - // see what the current rewards are - origReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) - - // STEP 2: Prepare the mask contract - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := initInfo.faucet.NewFundedRandomAccount(ctx, deposit...) - - // upload mask code - maskID, _, err := initInfo.contractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(2), maskID) - - // creator instantiates a contract and gives it tokens - maskAddr, _, err := initInfo.contractKeeper.Instantiate(ctx, maskID, creator, nil, []byte("{}"), "mask contract 2", nil) - require.NoError(t, err) - require.NotEmpty(t, maskAddr) - - // STEP 3: now, let's reflect some queries. - // let's get the bonded denom - reflectBondedQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - BondedDenom: &struct{}{}, - }}}} - reflectBondedBin := buildReflectQuery(t, &reflectBondedQuery) - res, err := keeper.QuerySmart(ctx, maskAddr, reflectBondedBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - var reflectRes testdata.ChainResponse - mustParse(t, res, &reflectRes) - var bondedRes wasmvmtypes.BondedDenomResponse - mustParse(t, reflectRes.Data, &bondedRes) - assert.Equal(t, "stake", bondedRes.Denom) - - // now, let's reflect a smart query into the x/wasm handlers and see if we get the same result - reflectAllValidatorsQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - AllValidators: &wasmvmtypes.AllValidatorsQuery{}, - }}}} - reflectAllValidatorsBin := buildReflectQuery(t, &reflectAllValidatorsQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectAllValidatorsBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - var allValidatorsRes wasmvmtypes.AllValidatorsResponse - mustParse(t, reflectRes.Data, &allValidatorsRes) - require.Len(t, allValidatorsRes.Validators, 1, string(res)) - valInfo := allValidatorsRes.Validators[0] - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), valInfo.Address) - require.Contains(t, valInfo.Commission, "0.100") - require.Contains(t, valInfo.MaxCommission, "0.200") - require.Contains(t, valInfo.MaxChangeRate, "0.010") - - // find a validator - reflectValidatorQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - Validator: &wasmvmtypes.ValidatorQuery{ - Address: valAddr.String(), - }, - }}}} - reflectValidatorBin := buildReflectQuery(t, &reflectValidatorQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectValidatorBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - var validatorRes wasmvmtypes.ValidatorResponse - mustParse(t, reflectRes.Data, &validatorRes) - require.NotNil(t, validatorRes.Validator) - valInfo = *validatorRes.Validator - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), valInfo.Address) - require.Contains(t, valInfo.Commission, "0.100") - require.Contains(t, valInfo.MaxCommission, "0.200") - require.Contains(t, valInfo.MaxChangeRate, "0.010") - - // missing validator - noVal := sdk.ValAddress(secp256k1.GenPrivKey().PubKey().Address()) - reflectNoValidatorQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - Validator: &wasmvmtypes.ValidatorQuery{ - Address: noVal.String(), - }, - }}}} - reflectNoValidatorBin := buildReflectQuery(t, &reflectNoValidatorQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectNoValidatorBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - var noValidatorRes wasmvmtypes.ValidatorResponse - mustParse(t, reflectRes.Data, &noValidatorRes) - require.Nil(t, noValidatorRes.Validator) - - // test to get all my delegations - reflectAllDelegationsQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - AllDelegations: &wasmvmtypes.AllDelegationsQuery{ - Delegator: contractAddr.String(), - }, - }}}} - reflectAllDelegationsBin := buildReflectQuery(t, &reflectAllDelegationsQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectAllDelegationsBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - var allDelegationsRes wasmvmtypes.AllDelegationsResponse - mustParse(t, reflectRes.Data, &allDelegationsRes) - require.Len(t, allDelegationsRes.Delegations, 1) - delInfo := allDelegationsRes.Delegations[0] - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), delInfo.Validator) - // note this is not bob (who staked to the contract), but the contract itself - require.Equal(t, contractAddr.String(), delInfo.Delegator) - // this is a different Coin type, with String not BigInt, compare field by field - require.Equal(t, funds[0].Denom, delInfo.Amount.Denom) - require.Equal(t, funds[0].Amount.String(), delInfo.Amount.Amount) - - // test to get one delegation - reflectDelegationQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ - Delegation: &wasmvmtypes.DelegationQuery{ - Validator: valAddr.String(), - Delegator: contractAddr.String(), - }, - }}}} - reflectDelegationBin := buildReflectQuery(t, &reflectDelegationQuery) - res, err = keeper.QuerySmart(ctx, maskAddr, reflectDelegationBin) - require.NoError(t, err) - // first we pull out the data from chain response, before parsing the original response - mustParse(t, res, &reflectRes) - - var delegationRes wasmvmtypes.DelegationResponse - mustParse(t, reflectRes.Data, &delegationRes) - assert.NotEmpty(t, delegationRes.Delegation) - delInfo2 := delegationRes.Delegation - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), delInfo2.Validator) - // note this is not bob (who staked to the contract), but the contract itself - require.Equal(t, contractAddr.String(), delInfo2.Delegator) - // this is a different Coin type, with String not BigInt, compare field by field - require.Equal(t, funds[0].Denom, delInfo2.Amount.Denom) - require.Equal(t, funds[0].Amount.String(), delInfo2.Amount.Amount) - - require.Equal(t, wasmvmtypes.NewCoin(200000, "stake"), delInfo2.CanRedelegate) - require.Len(t, delInfo2.AccumulatedRewards, 1) - // see bonding above to see how we calculate 36000 (240000 / 6 - 10% commission) - require.Equal(t, wasmvmtypes.NewCoin(36000, "stake"), delInfo2.AccumulatedRewards[0]) - - // ensure rewards did not change when querying (neither amount nor period) - finalReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) - require.Equal(t, origReward, finalReward) -} - -func TestQueryStakingPlugin(t *testing.T) { - // STEP 1: take a lot of setup from TestReinvest so we have non-zero info - initInfo := initializeStaking(t) - ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - stakingKeeper := initInfo.stakingKeeper - distKeeper := initInfo.distKeeper - - // initial checks of bonding state - val, found := stakingKeeper.GetValidator(ctx, valAddr) - require.True(t, found) - assert.Equal(t, sdk.NewInt(1000000), val.Tokens) - - // full is 2x funds, 1x goes to the contract, other stays on his wallet - full := sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)) - funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 200000)) - bob := initInfo.faucet.NewFundedRandomAccount(ctx, full...) - - // we will stake 200k to a validator with 1M self-bond - // this means we should get 1/6 of the rewards - bond := StakingHandleMsg{ - Bond: &struct{}{}, - } - bondBz, err := json.Marshal(bond) - require.NoError(t, err) - _, err = initInfo.contractKeeper.Execute(ctx, contractAddr, bob, bondBz, funds) - require.NoError(t, err) - - // update height a bit to solidify the delegation - ctx = nextBlock(ctx, stakingKeeper) - // we get 1/6, our share should be 40k minus 10% commission = 36k - setValidatorRewards(ctx, stakingKeeper, distKeeper, valAddr, "240000") - - // see what the current rewards are - origReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) - - // Step 2: Try out the query plugins - query := wasmvmtypes.StakingQuery{ - Delegation: &wasmvmtypes.DelegationQuery{ - Delegator: contractAddr.String(), - Validator: valAddr.String(), - }, - } - raw, err := StakingQuerier(stakingKeeper, distributionkeeper.NewQuerier(distKeeper))(ctx, &query) - require.NoError(t, err) - var res wasmvmtypes.DelegationResponse - mustParse(t, raw, &res) - assert.NotEmpty(t, res.Delegation) - delInfo := res.Delegation - // Note: this ValAddress not AccAddress, may change with #264 - require.Equal(t, valAddr.String(), delInfo.Validator) - // note this is not bob (who staked to the contract), but the contract itself - require.Equal(t, contractAddr.String(), delInfo.Delegator) - // this is a different Coin type, with String not BigInt, compare field by field - require.Equal(t, funds[0].Denom, delInfo.Amount.Denom) - require.Equal(t, funds[0].Amount.String(), delInfo.Amount.Amount) - - require.Equal(t, wasmvmtypes.NewCoin(200000, "stake"), delInfo.CanRedelegate) - require.Len(t, delInfo.AccumulatedRewards, 1) - // see bonding above to see how we calculate 36000 (240000 / 6 - 10% commission) - require.Equal(t, wasmvmtypes.NewCoin(36000, "stake"), delInfo.AccumulatedRewards[0]) - - // ensure rewards did not change when querying (neither amount nor period) - finalReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) - require.Equal(t, origReward, finalReward) -} - -// adds a few validators and returns a list of validators that are registered -func addValidator(t *testing.T, ctx sdk.Context, stakingKeeper *stakingkeeper.Keeper, faucet *TestFaucet, value sdk.Coin) sdk.ValAddress { - owner := faucet.NewFundedRandomAccount(ctx, value) - - privKey := secp256k1.GenPrivKey() - pubKey := privKey.PubKey() - addr := sdk.ValAddress(pubKey.Address()) - - pkAny, err := codectypes.NewAnyWithValue(pubKey) - require.NoError(t, err) - msg := &stakingtypes.MsgCreateValidator{ - Description: stakingtypes.Description{ - Moniker: "Validator power", - }, - Commission: stakingtypes.CommissionRates{ - Rate: sdk.MustNewDecFromStr("0.1"), - MaxRate: sdk.MustNewDecFromStr("0.2"), - MaxChangeRate: sdk.MustNewDecFromStr("0.01"), - }, - MinSelfDelegation: sdk.OneInt(), - DelegatorAddress: owner.String(), - ValidatorAddress: addr.String(), - Pubkey: pkAny, - Value: value, - } - _, err = stakingkeeper.NewMsgServerImpl(stakingKeeper).CreateValidator(sdk.WrapSDKContext(ctx), msg) - require.NoError(t, err) - return addr -} - -// this will commit the current set, update the block height and set historic info -// basically, letting two blocks pass -func nextBlock(ctx sdk.Context, stakingKeeper *stakingkeeper.Keeper) sdk.Context { - staking.EndBlocker(ctx, stakingKeeper) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - staking.BeginBlocker(ctx, stakingKeeper) - return ctx -} - -func setValidatorRewards(ctx sdk.Context, stakingKeeper *stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper, valAddr sdk.ValAddress, reward string) { - // allocate some rewards - vali := stakingKeeper.Validator(ctx, valAddr) - amount, err := sdk.NewDecFromStr(reward) - if err != nil { - panic(err) - } - payout := sdk.DecCoins{{Denom: "stake", Amount: amount}} - distKeeper.AllocateTokensToValidator(ctx, vali, payout) -} - -func assertBalance(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.AccAddress, addr sdk.AccAddress, expected string) { - query := StakingQueryMsg{ - Balance: &addressQuery{ - Address: addr, - }, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - res, err := keeper.QuerySmart(ctx, contract, queryBz) - require.NoError(t, err) - var balance BalanceResponse - err = json.Unmarshal(res, &balance) - require.NoError(t, err) - assert.Equal(t, expected, balance.Balance) -} - -func assertClaims(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.AccAddress, addr sdk.AccAddress, expected string) { - query := StakingQueryMsg{ - Claims: &addressQuery{ - Address: addr, - }, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - res, err := keeper.QuerySmart(ctx, contract, queryBz) - require.NoError(t, err) - var claims ClaimsResponse - err = json.Unmarshal(res, &claims) - require.NoError(t, err) - assert.Equal(t, expected, claims.Claims) -} - -func assertSupply(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.AccAddress, expectedIssued string, expectedBonded sdk.Coin) { - query := StakingQueryMsg{Investment: &struct{}{}} - queryBz, err := json.Marshal(query) - require.NoError(t, err) - res, err := keeper.QuerySmart(ctx, contract, queryBz) - require.NoError(t, err) - var invest InvestmentResponse - err = json.Unmarshal(res, &invest) - require.NoError(t, err) - assert.Equal(t, expectedIssued, invest.TokenSupply) - assert.Equal(t, expectedBonded, invest.StakedTokens) -} diff --git a/x/wasm/keeper/submsg_test.go b/x/wasm/keeper/submsg_test.go deleted file mode 100644 index fc14d2c..0000000 --- a/x/wasm/keeper/submsg_test.go +++ /dev/null @@ -1,552 +0,0 @@ -package keeper - -import ( - "encoding/json" - "fmt" - "os" - "strconv" - "testing" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// test handing of submessages, very closely related to the reflect_test - -// Try a simple send, no gas limit to for a sanity check before trying table tests -func TestDispatchSubMsgSuccessCase(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, ReflectFeatures) - accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - creatorBalance := deposit.Sub(contractStart...) - _, fred := keyPubAddr() - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - require.Equal(t, uint64(1), codeID) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // check some account values - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, contractStart) - checkAccount(t, ctx, accKeeper, bankKeeper, creator, creatorBalance) - checkAccount(t, ctx, accKeeper, bankKeeper, fred, nil) - - // creator can send contract's tokens to fred (using SendMsg) - msg := wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "15000", - }}, - }, - }, - } - reflectSend := testdata.ReflectHandleMsg{ - ReflectSubMsg: &testdata.ReflectSubPayload{ - Msgs: []wasmvmtypes.SubMsg{{ - ID: 7, - Msg: msg, - ReplyOn: wasmvmtypes.ReplyAlways, - }}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keepers.ContractKeeper.Execute(ctx, contractAddr, creator, reflectSendBz, nil) - require.NoError(t, err) - - // fred got coins - checkAccount(t, ctx, accKeeper, bankKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 15000))) - // contract lost them - checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 25000))) - checkAccount(t, ctx, accKeeper, bankKeeper, creator, creatorBalance) - - // query the reflect state to ensure the result was stored - query := testdata.ReflectQueryMsg{ - SubMsgResult: &testdata.SubCall{ID: 7}, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - queryRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - require.NoError(t, err) - - var res wasmvmtypes.Reply - err = json.Unmarshal(queryRes, &res) - require.NoError(t, err) - assert.Equal(t, uint64(7), res.ID) - assert.Empty(t, res.Result.Err) - require.NotNil(t, res.Result.Ok) - sub := res.Result.Ok - assert.Empty(t, sub.Data) - // as of v0.28.0 we strip out all events that don't come from wasm contracts. can't trust the sdk. - require.Len(t, sub.Events, 0) -} - -func TestDispatchSubMsgErrorHandling(t *testing.T) { - fundedDenom := "funds" - fundedAmount := 1_000_000 - ctxGasLimit := uint64(1_000_000) - subGasLimit := uint64(300_000) - - // prep - create one chain and upload the code - ctx, keepers := CreateTestInput(t, false, ReflectFeatures) - ctx = ctx.WithGasMeter(sdk.NewInfiniteGasMeter()) - ctx = ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) - keeper := keepers.WasmKeeper - contractStart := sdk.NewCoins(sdk.NewInt64Coin(fundedDenom, int64(fundedAmount))) - uploader := keepers.Faucet.NewFundedRandomAccount(ctx, contractStart.Add(contractStart...)...) - - // upload code - reflectID, _, err := keepers.ContractKeeper.Create(ctx, uploader, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - - // create hackatom contract for testing (for infinite loop) - hackatomCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - hackatomID, _, err := keepers.ContractKeeper.Create(ctx, uploader, hackatomCode, nil) - require.NoError(t, err) - _, bob := keyPubAddr() - _, fred := keyPubAddr() - initMsg := HackatomExampleInitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - hackatomAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, hackatomID, uploader, nil, initMsgBz, "hackatom demo", contractStart) - require.NoError(t, err) - - validBankSend := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { - return wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: emptyAccount, - Amount: []wasmvmtypes.Coin{{ - Denom: fundedDenom, - Amount: strconv.Itoa(fundedAmount / 2), - }}, - }, - }, - } - } - - invalidBankSend := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { - return wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: emptyAccount, - Amount: []wasmvmtypes.Coin{{ - Denom: fundedDenom, - Amount: strconv.Itoa(fundedAmount * 2), - }}, - }, - }, - } - } - - infiniteLoop := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { - return wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Execute: &wasmvmtypes.ExecuteMsg{ - ContractAddr: hackatomAddr.String(), - Msg: []byte(`{"cpu_loop":{}}`), - }, - }, - } - } - - instantiateContract := func(contract, emptyAccount string) wasmvmtypes.CosmosMsg { - return wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{ - Instantiate: &wasmvmtypes.InstantiateMsg{ - CodeID: reflectID, - Msg: []byte("{}"), - Label: "subcall reflect", - }, - }, - } - } - - type assertion func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) - - assertReturnedEvents := func(expectedEvents int) assertion { - return func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { - require.Len(t, response.Ok.Events, expectedEvents) - } - } - - assertGasUsed := func(minGas, maxGas uint64) assertion { - return func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { - gasUsed := ctx.GasMeter().GasConsumed() - assert.True(t, gasUsed >= minGas, "Used %d gas (less than expected %d)", gasUsed, minGas) - assert.True(t, gasUsed <= maxGas, "Used %d gas (more than expected %d)", gasUsed, maxGas) - } - } - - assertErrorString := func(shouldContain string) assertion { - return func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { - assert.Contains(t, response.Err, shouldContain) - } - } - - assertGotContractAddr := func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { - // should get the events emitted on new contract - event := response.Ok.Events[0] - require.Equal(t, event.Type, "instantiate") - assert.Equal(t, event.Attributes[0].Key, "_contract_address") - eventAddr := event.Attributes[0].Value - assert.NotEqual(t, contract, eventAddr) - - var res types.MsgInstantiateContractResponse - keepers.EncodingConfig.Marshaler.MustUnmarshal(response.Ok.Data, &res) - assert.Equal(t, eventAddr, res.Address) - } - - cases := map[string]struct { - submsgID uint64 - // we will generate message from the - msg func(contract, emptyAccount string) wasmvmtypes.CosmosMsg - gasLimit *uint64 - - // true if we expect this to throw out of gas panic - isOutOfGasPanic bool - // true if we expect this execute to return an error (can be false when submessage errors) - executeError bool - // true if we expect submessage to return an error (but execute to return success) - subMsgError bool - // make assertions after dispatch - resultAssertions []assertion - }{ - "send tokens": { - submsgID: 5, - msg: validBankSend, - resultAssertions: []assertion{assertReturnedEvents(0), assertGasUsed(102000, 103000)}, - }, - "not enough tokens": { - submsgID: 6, - msg: invalidBankSend, - subMsgError: true, - // uses less gas than the send tokens (cost of bank transfer) - resultAssertions: []assertion{assertGasUsed(76000, 79000), assertErrorString("codespace: sdk, code: 5")}, - }, - "out of gas panic with no gas limit": { - submsgID: 7, - msg: infiniteLoop, - isOutOfGasPanic: true, - }, - - "send tokens with limit": { - submsgID: 15, - msg: validBankSend, - gasLimit: &subGasLimit, - // uses same gas as call without limit (note we do not charge the 40k on reply) - resultAssertions: []assertion{assertReturnedEvents(0), assertGasUsed(102000, 103000)}, - }, - "not enough tokens with limit": { - submsgID: 16, - msg: invalidBankSend, - subMsgError: true, - gasLimit: &subGasLimit, - // uses same gas as call without limit (note we do not charge the 40k on reply) - resultAssertions: []assertion{assertGasUsed(77700, 77800), assertErrorString("codespace: sdk, code: 5")}, - }, - "out of gas caught with gas limit": { - submsgID: 17, - msg: infiniteLoop, - subMsgError: true, - gasLimit: &subGasLimit, - // uses all the subGasLimit, plus the 52k or so for the main contract - resultAssertions: []assertion{assertGasUsed(subGasLimit+73000, subGasLimit+74000), assertErrorString("codespace: sdk, code: 11")}, - }, - "instantiate contract gets address in data and events": { - submsgID: 21, - msg: instantiateContract, - resultAssertions: []assertion{assertReturnedEvents(1), assertGotContractAddr}, - }, - } - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - creator := keepers.Faucet.NewFundedRandomAccount(ctx, contractStart...) - _, empty := keyPubAddr() - - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), fmt.Sprintf("contract %s", name), contractStart) - require.NoError(t, err) - - msg := tc.msg(contractAddr.String(), empty.String()) - reflectSend := testdata.ReflectHandleMsg{ - ReflectSubMsg: &testdata.ReflectSubPayload{ - Msgs: []wasmvmtypes.SubMsg{{ - ID: tc.submsgID, - Msg: msg, - GasLimit: tc.gasLimit, - ReplyOn: wasmvmtypes.ReplyAlways, - }}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - - execCtx := ctx.WithGasMeter(sdk.NewGasMeter(ctxGasLimit)) - defer func() { - if tc.isOutOfGasPanic { - r := recover() - require.NotNil(t, r, "expected panic") - if _, ok := r.(sdk.ErrorOutOfGas); !ok { - t.Fatalf("Expected OutOfGas panic, got: %#v\n", r) - } - } - }() - _, err = keepers.ContractKeeper.Execute(execCtx, contractAddr, creator, reflectSendBz, nil) - - if tc.executeError { - require.Error(t, err) - } else { - require.NoError(t, err) - - // query the reply - query := testdata.ReflectQueryMsg{ - SubMsgResult: &testdata.SubCall{ID: tc.submsgID}, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - queryRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - require.NoError(t, err) - var res wasmvmtypes.Reply - err = json.Unmarshal(queryRes, &res) - require.NoError(t, err) - assert.Equal(t, tc.submsgID, res.ID) - - if tc.subMsgError { - require.NotEmpty(t, res.Result.Err) - require.Nil(t, res.Result.Ok) - } else { - require.Empty(t, res.Result.Err) - require.NotNil(t, res.Result.Ok) - } - - for _, assertion := range tc.resultAssertions { - assertion(t, execCtx, contractAddr.String(), empty.String(), res.Result) - } - - } - }) - } -} - -// Test an error case, where the Encoded doesn't return any sdk.Msg and we trigger(ed) a null pointer exception. -// This occurs with the IBC encoder. Test this. -func TestDispatchSubMsgEncodeToNoSdkMsg(t *testing.T) { - // fake out the bank handle to return success with no data - nilEncoder := func(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) { - return nil, nil - } - customEncoders := &MessageEncoders{ - Bank: nilEncoder, - } - - ctx, keepers := CreateTestInput(t, false, ReflectFeatures, WithMessageHandler(NewSDKMessageHandler(nil, customEncoders))) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, fred := keyPubAddr() - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - require.NotEmpty(t, contractAddr) - - // creator can send contract's tokens to fred (using SendMsg) - msg := wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "15000", - }}, - }, - }, - } - reflectSend := testdata.ReflectHandleMsg{ - ReflectSubMsg: &testdata.ReflectSubPayload{ - Msgs: []wasmvmtypes.SubMsg{{ - ID: 7, - Msg: msg, - ReplyOn: wasmvmtypes.ReplyAlways, - }}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keepers.ContractKeeper.Execute(ctx, contractAddr, creator, reflectSendBz, nil) - require.NoError(t, err) - - // query the reflect state to ensure the result was stored - query := testdata.ReflectQueryMsg{ - SubMsgResult: &testdata.SubCall{ID: 7}, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - queryRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - require.NoError(t, err) - - var res wasmvmtypes.Reply - err = json.Unmarshal(queryRes, &res) - require.NoError(t, err) - assert.Equal(t, uint64(7), res.ID) - assert.Empty(t, res.Result.Err) - require.NotNil(t, res.Result.Ok) - sub := res.Result.Ok - assert.Empty(t, sub.Data) - require.Len(t, sub.Events, 0) -} - -// Try a simple send, no gas limit to for a sanity check before trying table tests -func TestDispatchSubMsgConditionalReplyOn(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, ReflectFeatures) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, fred := keyPubAddr() - - // upload code - codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) - require.NoError(t, err) - - // creator instantiates a contract and gives it tokens - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, codeID, creator, nil, []byte("{}"), "reflect contract 1", contractStart) - require.NoError(t, err) - - goodSend := wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "denom", - Amount: "1000", - }}, - }, - }, - } - failSend := wasmvmtypes.CosmosMsg{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: fred.String(), - Amount: []wasmvmtypes.Coin{{ - Denom: "no-such-token", - Amount: "777777", - }}, - }, - }, - } - - cases := map[string]struct { - // true for wasmvmtypes.ReplySuccess, false for wasmvmtypes.ReplyError - replyOnSuccess bool - msg wasmvmtypes.CosmosMsg - // true if the call should return an error (it wasn't handled) - expectError bool - // true if the reflect contract wrote the response (success or error) - it was captured - writeResult bool - }{ - "all good, reply success": { - replyOnSuccess: true, - msg: goodSend, - expectError: false, - writeResult: true, - }, - "all good, reply error": { - replyOnSuccess: false, - msg: goodSend, - expectError: false, - writeResult: false, - }, - "bad msg, reply success": { - replyOnSuccess: true, - msg: failSend, - expectError: true, - writeResult: false, - }, - "bad msg, reply error": { - replyOnSuccess: false, - msg: failSend, - expectError: false, - writeResult: true, - }, - } - - var id uint64 - for name, tc := range cases { - id++ - t.Run(name, func(t *testing.T) { - subMsg := wasmvmtypes.SubMsg{ - ID: id, - Msg: tc.msg, - ReplyOn: wasmvmtypes.ReplySuccess, - } - if !tc.replyOnSuccess { - subMsg.ReplyOn = wasmvmtypes.ReplyError - } - - reflectSend := testdata.ReflectHandleMsg{ - ReflectSubMsg: &testdata.ReflectSubPayload{ - Msgs: []wasmvmtypes.SubMsg{subMsg}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - require.NoError(t, err) - _, err = keepers.ContractKeeper.Execute(ctx, contractAddr, creator, reflectSendBz, nil) - - if tc.expectError { - require.Error(t, err) - } else { - require.NoError(t, err) - } - - // query the reflect state to check if the result was stored - query := testdata.ReflectQueryMsg{ - SubMsgResult: &testdata.SubCall{ID: id}, - } - queryBz, err := json.Marshal(query) - require.NoError(t, err) - queryRes, err := keeper.QuerySmart(ctx, contractAddr, queryBz) - if tc.writeResult { - // we got some data for this call - require.NoError(t, err) - var res wasmvmtypes.Reply - err = json.Unmarshal(queryRes, &res) - require.NoError(t, err) - require.Equal(t, id, res.ID) - } else { - // nothing should be there -> error - require.Error(t, err) - } - }) - } -} diff --git a/x/wasm/keeper/test_common.go b/x/wasm/keeper/test_common.go deleted file mode 100644 index 7b7f9c7..0000000 --- a/x/wasm/keeper/test_common.go +++ /dev/null @@ -1,816 +0,0 @@ -package keeper - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "fmt" - "os" - "testing" - "time" - - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - - icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" - icahosttypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/types" - - errorsmod "cosmossdk.io/errors" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/crypto" - "github.com/cometbft/cometbft/crypto/ed25519" - "github.com/cometbft/cometbft/libs/log" - "github.com/cometbft/cometbft/libs/rand" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/std" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/auth/vesting" - authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper" - "github.com/cosmos/cosmos-sdk/x/bank" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/capability" - capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - "github.com/cosmos/cosmos-sdk/x/crisis" - crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" - "github.com/cosmos/cosmos-sdk/x/distribution" - distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/evidence" - evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types" - "github.com/cosmos/cosmos-sdk/x/feegrant" - "github.com/cosmos/cosmos-sdk/x/gov" - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - govv1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1" - govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/cosmos/cosmos-sdk/x/mint" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - "github.com/cosmos/cosmos-sdk/x/params" - paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" - paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" - paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" - "github.com/cosmos/cosmos-sdk/x/slashing" - slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/cosmos/cosmos-sdk/x/upgrade" - upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" - upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - "github.com/cosmos/ibc-go/v7/modules/apps/transfer" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - ibc "github.com/cosmos/ibc-go/v7/modules/core" - ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" - ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" - "github.com/stretchr/testify/require" - - wasmappparams "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var moduleBasics = module.NewBasicManager( - auth.AppModuleBasic{}, - bank.AppModuleBasic{}, - capability.AppModuleBasic{}, - staking.AppModuleBasic{}, - mint.AppModuleBasic{}, - distribution.AppModuleBasic{}, - gov.NewAppModuleBasic([]govclient.ProposalHandler{ - paramsclient.ProposalHandler, - upgradeclient.LegacyProposalHandler, - upgradeclient.LegacyCancelProposalHandler, - }), - params.AppModuleBasic{}, - crisis.AppModuleBasic{}, - slashing.AppModuleBasic{}, - ibc.AppModuleBasic{}, - upgrade.AppModuleBasic{}, - evidence.AppModuleBasic{}, - transfer.AppModuleBasic{}, - vesting.AppModuleBasic{}, -) - -func MakeTestCodec(t testing.TB) codec.Codec { - return MakeEncodingConfig(t).Marshaler -} - -func MakeEncodingConfig(_ testing.TB) wasmappparams.EncodingConfig { - encodingConfig := wasmappparams.MakeEncodingConfig() - amino := encodingConfig.Amino - interfaceRegistry := encodingConfig.InterfaceRegistry - - std.RegisterInterfaces(interfaceRegistry) - std.RegisterLegacyAminoCodec(amino) - - moduleBasics.RegisterLegacyAminoCodec(amino) - moduleBasics.RegisterInterfaces(interfaceRegistry) - // add wasmd types - types.RegisterInterfaces(interfaceRegistry) - types.RegisterLegacyAminoCodec(amino) - - return encodingConfig -} - -var TestingStakeParams = stakingtypes.Params{ - UnbondingTime: 100, - MaxValidators: 10, - MaxEntries: 10, - HistoricalEntries: 10, - BondDenom: "stake", - MinCommissionRate: stakingtypes.DefaultMinCommissionRate, -} - -type TestFaucet struct { - t testing.TB - bankKeeper bankkeeper.Keeper - sender sdk.AccAddress - balance sdk.Coins - minterModuleName string -} - -func NewTestFaucet(t testing.TB, ctx sdk.Context, bankKeeper bankkeeper.Keeper, minterModuleName string, initialAmount ...sdk.Coin) *TestFaucet { - require.NotEmpty(t, initialAmount) - r := &TestFaucet{t: t, bankKeeper: bankKeeper, minterModuleName: minterModuleName} - _, addr := keyPubAddr() - r.sender = addr - r.Mint(ctx, addr, initialAmount...) - r.balance = initialAmount - return r -} - -func (f *TestFaucet) Mint(parentCtx sdk.Context, addr sdk.AccAddress, amounts ...sdk.Coin) { - require.NotEmpty(f.t, amounts) - ctx := parentCtx.WithEventManager(sdk.NewEventManager()) // discard all faucet related events - err := f.bankKeeper.MintCoins(ctx, f.minterModuleName, amounts) - require.NoError(f.t, err) - err = f.bankKeeper.SendCoinsFromModuleToAccount(ctx, f.minterModuleName, addr, amounts) - require.NoError(f.t, err) - f.balance = f.balance.Add(amounts...) -} - -func (f *TestFaucet) Fund(parentCtx sdk.Context, receiver sdk.AccAddress, amounts ...sdk.Coin) { - require.NotEmpty(f.t, amounts) - // ensure faucet is always filled - if !f.balance.IsAllGTE(amounts) { - f.Mint(parentCtx, f.sender, amounts...) - } - ctx := parentCtx.WithEventManager(sdk.NewEventManager()) // discard all faucet related events - err := f.bankKeeper.SendCoins(ctx, f.sender, receiver, amounts) - require.NoError(f.t, err) - f.balance = f.balance.Sub(amounts...) -} - -func (f *TestFaucet) NewFundedRandomAccount(ctx sdk.Context, amounts ...sdk.Coin) sdk.AccAddress { - _, addr := keyPubAddr() - f.Fund(ctx, addr, amounts...) - return addr -} - -type TestKeepers struct { - AccountKeeper authkeeper.AccountKeeper - StakingKeeper *stakingkeeper.Keeper - DistKeeper distributionkeeper.Keeper - BankKeeper bankkeeper.Keeper - GovKeeper *govkeeper.Keeper - ContractKeeper types.ContractOpsKeeper - WasmKeeper *Keeper - IBCKeeper *ibckeeper.Keeper - Router MessageRouter - EncodingConfig wasmappparams.EncodingConfig - Faucet *TestFaucet - MultiStore sdk.CommitMultiStore - ScopedWasmKeeper capabilitykeeper.ScopedKeeper - WasmStoreKey *storetypes.KVStoreKey -} - -// CreateDefaultTestInput common settings for CreateTestInput -func CreateDefaultTestInput(t testing.TB) (sdk.Context, TestKeepers) { - return CreateTestInput(t, false, "staking") -} - -// CreateTestInput encoders can be nil to accept the defaults, or set it to override some of the message handlers (like default) -func CreateTestInput(t testing.TB, isCheckTx bool, availableCapabilities string, opts ...Option) (sdk.Context, TestKeepers) { - // Load default wasm config - return createTestInput(t, isCheckTx, availableCapabilities, types.DefaultWasmConfig(), dbm.NewMemDB(), opts...) -} - -// encoders can be nil to accept the defaults, or set it to override some of the message handlers (like default) -func createTestInput( - t testing.TB, - isCheckTx bool, - availableCapabilities string, - wasmConfig types.WasmConfig, - db dbm.DB, - opts ...Option, -) (sdk.Context, TestKeepers) { - tempDir := t.TempDir() - - keys := sdk.NewKVStoreKeys( - authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, - minttypes.StoreKey, distributiontypes.StoreKey, slashingtypes.StoreKey, - govtypes.StoreKey, paramstypes.StoreKey, ibcexported.StoreKey, upgradetypes.StoreKey, - evidencetypes.StoreKey, ibctransfertypes.StoreKey, - capabilitytypes.StoreKey, feegrant.StoreKey, authzkeeper.StoreKey, - types.StoreKey, - ) - ms := store.NewCommitMultiStore(db) - for _, v := range keys { - ms.MountStoreWithDB(v, storetypes.StoreTypeIAVL, db) - } - tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) - for _, v := range tkeys { - ms.MountStoreWithDB(v, storetypes.StoreTypeTransient, db) - } - - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) - for _, v := range memKeys { - ms.MountStoreWithDB(v, storetypes.StoreTypeMemory, db) - } - - require.NoError(t, ms.LoadLatestVersion()) - - ctx := sdk.NewContext(ms, tmproto.Header{ - Height: 1234567, - Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC), - }, isCheckTx, log.NewNopLogger()) - ctx = types.WithTXCounter(ctx, 0) - - encodingConfig := MakeEncodingConfig(t) - appCodec, legacyAmino := encodingConfig.Marshaler, encodingConfig.Amino - - paramsKeeper := paramskeeper.NewKeeper( - appCodec, - legacyAmino, - keys[paramstypes.StoreKey], - tkeys[paramstypes.TStoreKey], - ) - for _, m := range []string{ - authtypes.ModuleName, - banktypes.ModuleName, - stakingtypes.ModuleName, - minttypes.ModuleName, - distributiontypes.ModuleName, - slashingtypes.ModuleName, - crisistypes.ModuleName, - ibctransfertypes.ModuleName, - capabilitytypes.ModuleName, - ibcexported.ModuleName, - govtypes.ModuleName, - types.ModuleName, - } { - paramsKeeper.Subspace(m) - } - subspace := func(m string) paramstypes.Subspace { - r, ok := paramsKeeper.GetSubspace(m) - require.True(t, ok) - - var keyTable paramstypes.KeyTable - switch r.Name() { - case authtypes.ModuleName: - keyTable = authtypes.ParamKeyTable() //nolint:staticcheck - case banktypes.ModuleName: - keyTable = banktypes.ParamKeyTable() //nolint:staticcheck - case stakingtypes.ModuleName: - keyTable = stakingtypes.ParamKeyTable() - case minttypes.ModuleName: - keyTable = minttypes.ParamKeyTable() //nolint:staticcheck - case distributiontypes.ModuleName: - keyTable = distributiontypes.ParamKeyTable() //nolint:staticcheck - case slashingtypes.ModuleName: - keyTable = slashingtypes.ParamKeyTable() //nolint:staticcheck - case govtypes.ModuleName: - keyTable = govv1.ParamKeyTable() //nolint:staticcheck - case crisistypes.ModuleName: - keyTable = crisistypes.ParamKeyTable() //nolint:staticcheck - // ibc types - case ibctransfertypes.ModuleName: - keyTable = ibctransfertypes.ParamKeyTable() - case icahosttypes.SubModuleName: - keyTable = icahosttypes.ParamKeyTable() - case icacontrollertypes.SubModuleName: - keyTable = icacontrollertypes.ParamKeyTable() - // wasm - case types.ModuleName: - keyTable = types.ParamKeyTable() //nolint:staticcheck - default: - return r - } - - if !r.HasKeyTable() { - r = r.WithKeyTable(keyTable) - } - return r - } - maccPerms := map[string][]string{ // module account permissions - authtypes.FeeCollectorName: nil, - distributiontypes.ModuleName: nil, - minttypes.ModuleName: {authtypes.Minter}, - stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, - stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, - govtypes.ModuleName: {authtypes.Burner}, - ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, - types.ModuleName: {authtypes.Burner}, - } - accountKeeper := authkeeper.NewAccountKeeper( - appCodec, - keys[authtypes.StoreKey], // target store - authtypes.ProtoBaseAccount, // prototype - maccPerms, - sdk.Bech32MainPrefix, - authtypes.NewModuleAddress(authtypes.ModuleName).String(), - ) - blockedAddrs := make(map[string]bool) - for acc := range maccPerms { - blockedAddrs[authtypes.NewModuleAddress(acc).String()] = true - } - - require.NoError(t, accountKeeper.SetParams(ctx, authtypes.DefaultParams())) - - bankKeeper := bankkeeper.NewBaseKeeper( - appCodec, - keys[banktypes.StoreKey], - accountKeeper, - blockedAddrs, - authtypes.NewModuleAddress(banktypes.ModuleName).String(), - ) - require.NoError(t, bankKeeper.SetParams(ctx, banktypes.DefaultParams())) - - stakingKeeper := stakingkeeper.NewKeeper( - appCodec, - keys[stakingtypes.StoreKey], - accountKeeper, - bankKeeper, - authtypes.NewModuleAddress(stakingtypes.ModuleName).String(), - ) - stakingtypes.DefaultParams() - require.NoError(t, stakingKeeper.SetParams(ctx, TestingStakeParams)) - - distKeeper := distributionkeeper.NewKeeper( - appCodec, - keys[distributiontypes.StoreKey], - accountKeeper, - bankKeeper, - stakingKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(distributiontypes.ModuleName).String(), - ) - require.NoError(t, distKeeper.SetParams(ctx, distributiontypes.DefaultParams())) - stakingKeeper.SetHooks(distKeeper.Hooks()) - - // set genesis items required for distribution - distKeeper.SetFeePool(ctx, distributiontypes.InitialFeePool()) - - upgradeKeeper := upgradekeeper.NewKeeper( - map[int64]bool{}, - keys[upgradetypes.StoreKey], - appCodec, - tempDir, - nil, - authtypes.NewModuleAddress(upgradetypes.ModuleName).String(), - ) - - faucet := NewTestFaucet(t, ctx, bankKeeper, minttypes.ModuleName, sdk.NewCoin("stake", sdk.NewInt(100_000_000_000))) - - // set some funds ot pay out validatores, based on code from: - // https://github.com/cosmos/cosmos-sdk/blob/fea231556aee4d549d7551a6190389c4328194eb/x/distribution/keeper/keeper_test.go#L50-L57 - distrAcc := distKeeper.GetDistributionAccount(ctx) - faucet.Fund(ctx, distrAcc.GetAddress(), sdk.NewCoin("stake", sdk.NewInt(2000000))) - accountKeeper.SetModuleAccount(ctx, distrAcc) - - capabilityKeeper := capabilitykeeper.NewKeeper( - appCodec, - keys[capabilitytypes.StoreKey], - memKeys[capabilitytypes.MemStoreKey], - ) - scopedIBCKeeper := capabilityKeeper.ScopeToModule(ibcexported.ModuleName) - scopedWasmKeeper := capabilityKeeper.ScopeToModule(types.ModuleName) - - ibcKeeper := ibckeeper.NewKeeper( - appCodec, - keys[ibcexported.StoreKey], - subspace(ibcexported.ModuleName), - stakingKeeper, - upgradeKeeper, - scopedIBCKeeper, - ) - - querier := baseapp.NewGRPCQueryRouter() - querier.SetInterfaceRegistry(encodingConfig.InterfaceRegistry) - msgRouter := baseapp.NewMsgServiceRouter() - msgRouter.SetInterfaceRegistry(encodingConfig.InterfaceRegistry) - - cfg := sdk.GetConfig() - cfg.SetAddressVerifier(types.VerifyAddressLen()) - - keeper := NewKeeper( - appCodec, - keys[types.StoreKey], - accountKeeper, - bankKeeper, - stakingKeeper, - distributionkeeper.NewQuerier(distKeeper), - ibcKeeper.ChannelKeeper, - &ibcKeeper.PortKeeper, - scopedWasmKeeper, - wasmtesting.MockIBCTransferKeeper{}, - msgRouter, - querier, - tempDir, - wasmConfig, - availableCapabilities, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - opts..., - ) - require.NoError(t, keeper.SetParams(ctx, types.DefaultParams())) - - // add wasm handler so we can loop-back (contracts calling contracts) - contractKeeper := NewDefaultPermissionKeeper(&keeper) - - govRouter := govv1beta1.NewRouter(). - AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)). - AddRoute(types.RouterKey, NewWasmProposalHandler(&keeper, types.EnableAllProposals)) - - govKeeper := govkeeper.NewKeeper( - appCodec, - keys[govtypes.StoreKey], - accountKeeper, - bankKeeper, - stakingKeeper, - msgRouter, - govtypes.DefaultConfig(), - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) - require.NoError(t, govKeeper.SetParams(ctx, govv1.DefaultParams())) - govKeeper.SetLegacyRouter(govRouter) - govKeeper.SetProposalID(ctx, 1) - - am := module.NewManager( // minimal module set that we use for message/ query tests - bank.NewAppModule(appCodec, bankKeeper, accountKeeper, subspace(banktypes.ModuleName)), - staking.NewAppModule(appCodec, stakingKeeper, accountKeeper, bankKeeper, subspace(stakingtypes.ModuleName)), - distribution.NewAppModule(appCodec, distKeeper, accountKeeper, bankKeeper, stakingKeeper, subspace(distributiontypes.ModuleName)), - gov.NewAppModule(appCodec, govKeeper, accountKeeper, bankKeeper, subspace(govtypes.ModuleName)), - ) - am.RegisterServices(module.NewConfigurator(appCodec, msgRouter, querier)) - types.RegisterMsgServer(msgRouter, NewMsgServerImpl(&keeper)) - types.RegisterQueryServer(querier, NewGrpcQuerier(appCodec, keys[types.ModuleName], keeper, keeper.queryGasLimit)) - - keepers := TestKeepers{ - AccountKeeper: accountKeeper, - StakingKeeper: stakingKeeper, - DistKeeper: distKeeper, - ContractKeeper: contractKeeper, - WasmKeeper: &keeper, - BankKeeper: bankKeeper, - GovKeeper: govKeeper, - IBCKeeper: ibcKeeper, - Router: msgRouter, - EncodingConfig: encodingConfig, - Faucet: faucet, - MultiStore: ms, - ScopedWasmKeeper: scopedWasmKeeper, - WasmStoreKey: keys[types.StoreKey], - } - return ctx, keepers -} - -// TestHandler returns a wasm handler for tests (to avoid circular imports) -func TestHandler(k types.ContractOpsKeeper) MessageRouter { - return MessageRouterFunc(func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - switch msg := msg.(type) { - case *types.MsgStoreCode: - return handleStoreCode(ctx, k, msg) - case *types.MsgInstantiateContract: - return handleInstantiate(ctx, k, msg) - case *types.MsgExecuteContract: - return handleExecute(ctx, k, msg) - default: - errMsg := fmt.Sprintf("unrecognized wasm message type: %T", msg) - return nil, errorsmod.Wrap(sdkerrors.ErrUnknownRequest, errMsg) - } - }) -} - -var _ MessageRouter = MessageRouterFunc(nil) - -type MessageRouterFunc func(ctx sdk.Context, req sdk.Msg) (*sdk.Result, error) - -func (m MessageRouterFunc) Handler(msg sdk.Msg) baseapp.MsgServiceHandler { - return m -} - -func handleStoreCode(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgStoreCode) (*sdk.Result, error) { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - codeID, _, err := k.Create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission) - if err != nil { - return nil, err - } - - return &sdk.Result{ - Data: []byte(fmt.Sprintf("%d", codeID)), - Events: ctx.EventManager().ABCIEvents(), - }, nil -} - -func handleInstantiate(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgInstantiateContract) (*sdk.Result, error) { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - var adminAddr sdk.AccAddress - if msg.Admin != "" { - if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - } - - contractAddr, _, err := k.Instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds) - if err != nil { - return nil, err - } - - return &sdk.Result{ - Data: contractAddr, - Events: ctx.EventManager().Events().ToABCIEvents(), - }, nil -} - -func handleExecute(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgExecuteContract) (*sdk.Result, error) { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { - return nil, errorsmod.Wrap(err, "sender") - } - contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) - if err != nil { - return nil, errorsmod.Wrap(err, "admin") - } - data, err := k.Execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) - if err != nil { - return nil, err - } - - return &sdk.Result{ - Data: data, - Events: ctx.EventManager().Events().ToABCIEvents(), - }, nil -} - -func RandomAccountAddress(_ testing.TB) sdk.AccAddress { - _, addr := keyPubAddr() - return addr -} - -// DeterministicAccountAddress creates a test address with v repeated to valid address size -func DeterministicAccountAddress(_ testing.TB, v byte) sdk.AccAddress { - return bytes.Repeat([]byte{v}, address.Len) -} - -func RandomBech32AccountAddress(t testing.TB) string { - return RandomAccountAddress(t).String() -} - -type ExampleContract struct { - InitialAmount sdk.Coins - Creator crypto.PrivKey - CreatorAddr sdk.AccAddress - CodeID uint64 - Checksum []byte -} - -func StoreHackatomExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContractWasm(t, ctx, keepers, testdata.HackatomContractWasm()) -} - -func StoreBurnerExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContractWasm(t, ctx, keepers, testdata.BurnerContractWasm()) -} - -func StoreIBCReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContractWasm(t, ctx, keepers, testdata.IBCReflectContractWasm()) -} - -func StoreReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContractWasm(t, ctx, keepers, testdata.ReflectContractWasm()) -} - -func StoreExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers, wasmFile string) ExampleContract { - wasmCode, err := os.ReadFile(wasmFile) - require.NoError(t, err) - return StoreExampleContractWasm(t, ctx, keepers, wasmCode) -} - -func StoreExampleContractWasm(t testing.TB, ctx sdk.Context, keepers TestKeepers, wasmCode []byte) ExampleContract { - anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000)) - creator, creatorAddr := keyPubAddr() - fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount) - - codeID, _, err := keepers.ContractKeeper.Create(ctx, creatorAddr, wasmCode, nil) - require.NoError(t, err) - hash := keepers.WasmKeeper.GetCodeInfo(ctx, codeID).CodeHash - return ExampleContract{anyAmount, creator, creatorAddr, codeID, hash} -} - -var wasmIdent = []byte("\x00\x61\x73\x6D") - -type ExampleContractInstance struct { - ExampleContract - Contract sdk.AccAddress -} - -// SeedNewContractInstance sets the mock wasmerEngine in keeper and calls store + instantiate to init the contract's metadata -func SeedNewContractInstance(t testing.TB, ctx sdk.Context, keepers TestKeepers, mock types.WasmerEngine) ExampleContractInstance { - t.Helper() - exampleContract := StoreRandomContract(t, ctx, keepers, mock) - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, exampleContract.CodeID, exampleContract.CreatorAddr, exampleContract.CreatorAddr, []byte(`{}`), "", nil) - require.NoError(t, err) - return ExampleContractInstance{ - ExampleContract: exampleContract, - Contract: contractAddr, - } -} - -// StoreRandomContract sets the mock wasmerEngine in keeper and calls store -func StoreRandomContract(t testing.TB, ctx sdk.Context, keepers TestKeepers, mock types.WasmerEngine) ExampleContract { - return StoreRandomContractWithAccessConfig(t, ctx, keepers, mock, nil) -} - -func StoreRandomContractWithAccessConfig( - t testing.TB, ctx sdk.Context, - keepers TestKeepers, - mock types.WasmerEngine, - cfg *types.AccessConfig, -) ExampleContract { - t.Helper() - anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000)) - creator, creatorAddr := keyPubAddr() - fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount) - keepers.WasmKeeper.wasmVM = mock - wasmCode := append(wasmIdent, rand.Bytes(10)...) //nolint:gocritic - codeID, checksum, err := keepers.ContractKeeper.Create(ctx, creatorAddr, wasmCode, cfg) - require.NoError(t, err) - exampleContract := ExampleContract{InitialAmount: anyAmount, Creator: creator, CreatorAddr: creatorAddr, CodeID: codeID, Checksum: checksum} - return exampleContract -} - -type HackatomExampleInstance struct { - ExampleContract - Contract sdk.AccAddress - Verifier crypto.PrivKey - VerifierAddr sdk.AccAddress - Beneficiary crypto.PrivKey - BeneficiaryAddr sdk.AccAddress - Label string - Deposit sdk.Coins -} - -// InstantiateHackatomExampleContract load and instantiate the "./testdata/hackatom.wasm" contract -func InstantiateHackatomExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) HackatomExampleInstance { - contract := StoreHackatomExampleContract(t, ctx, keepers) - - verifier, verifierAddr := keyPubAddr() - fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, verifierAddr, contract.InitialAmount) - - beneficiary, beneficiaryAddr := keyPubAddr() - initMsgBz := HackatomExampleInitMsg{ - Verifier: verifierAddr, - Beneficiary: beneficiaryAddr, - }.GetBytes(t) - initialAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - - adminAddr := contract.CreatorAddr - label := "demo contract to query" - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, contract.CodeID, contract.CreatorAddr, adminAddr, initMsgBz, label, initialAmount) - require.NoError(t, err) - return HackatomExampleInstance{ - ExampleContract: contract, - Contract: contractAddr, - Verifier: verifier, - VerifierAddr: verifierAddr, - Beneficiary: beneficiary, - BeneficiaryAddr: beneficiaryAddr, - Label: label, - Deposit: initialAmount, - } -} - -type ExampleInstance struct { - ExampleContract - Contract sdk.AccAddress - Label string - Deposit sdk.Coins -} - -// InstantiateReflectExampleContract load and instantiate the "./testdata/reflect.wasm" contract -func InstantiateReflectExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleInstance { - example := StoreReflectContract(t, ctx, keepers) - initialAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - label := "demo contract to query" - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, example.CreatorAddr, []byte("{}"), label, initialAmount) - - require.NoError(t, err) - return ExampleInstance{ - ExampleContract: example, - Contract: contractAddr, - Label: label, - Deposit: initialAmount, - } -} - -type HackatomExampleInitMsg struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` -} - -func (m HackatomExampleInitMsg) GetBytes(t testing.TB) []byte { - initMsgBz, err := json.Marshal(m) - require.NoError(t, err) - return initMsgBz -} - -type IBCReflectExampleInstance struct { - Contract sdk.AccAddress - Admin sdk.AccAddress - CodeID uint64 - ReflectCodeID uint64 -} - -// InstantiateIBCReflectContract load and instantiate the "./testdata/ibc_reflect.wasm" contract -func InstantiateIBCReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) IBCReflectExampleInstance { - reflectID := StoreReflectContract(t, ctx, keepers).CodeID - ibcReflectID := StoreIBCReflectContract(t, ctx, keepers).CodeID - - initMsgBz := IBCReflectInitMsg{ - ReflectCodeID: reflectID, - }.GetBytes(t) - adminAddr := RandomAccountAddress(t) - - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, ibcReflectID, adminAddr, adminAddr, initMsgBz, "ibc-reflect-factory", nil) - require.NoError(t, err) - return IBCReflectExampleInstance{ - Admin: adminAddr, - Contract: contractAddr, - CodeID: ibcReflectID, - ReflectCodeID: reflectID, - } -} - -type IBCReflectInitMsg struct { - ReflectCodeID uint64 `json:"reflect_code_id"` -} - -func (m IBCReflectInitMsg) GetBytes(t testing.TB) []byte { - initMsgBz, err := json.Marshal(m) - require.NoError(t, err) - return initMsgBz -} - -type BurnerExampleInitMsg struct { - Payout sdk.AccAddress `json:"payout"` -} - -func (m BurnerExampleInitMsg) GetBytes(t testing.TB) []byte { - initMsgBz, err := json.Marshal(m) - require.NoError(t, err) - return initMsgBz -} - -func fundAccounts(t testing.TB, ctx sdk.Context, am authkeeper.AccountKeeper, bank bankkeeper.Keeper, addr sdk.AccAddress, coins sdk.Coins) { - acc := am.NewAccountWithAddress(ctx, addr) - am.SetAccount(ctx, acc) - NewTestFaucet(t, ctx, bank, minttypes.ModuleName, coins...).Fund(ctx, addr, coins...) -} - -var keyCounter uint64 - -// we need to make this deterministic (same every test run), as encoded address size and thus gas cost, -// depends on the actual bytes (due to ugly CanonicalAddress encoding) -func keyPubAddr() (crypto.PrivKey, sdk.AccAddress) { - keyCounter++ - seed := make([]byte, 8) - binary.BigEndian.PutUint64(seed, keyCounter) - - key := ed25519.GenPrivKeyFromSecret(seed) - pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) - return key, addr -} diff --git a/x/wasm/keeper/test_fuzz.go b/x/wasm/keeper/test_fuzz.go deleted file mode 100644 index d6acf7b..0000000 --- a/x/wasm/keeper/test_fuzz.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper - -import ( - "encoding/json" - - tmBytes "github.com/cometbft/cometbft/libs/bytes" - sdk "github.com/cosmos/cosmos-sdk/types" - fuzz "github.com/google/gofuzz" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var ModelFuzzers = []interface{}{FuzzAddr, FuzzAddrString, FuzzAbsoluteTxPosition, FuzzContractInfo, FuzzStateModel, FuzzAccessType, FuzzAccessConfig, FuzzContractCodeHistory} - -func FuzzAddr(m *sdk.AccAddress, c fuzz.Continue) { - *m = make([]byte, 20) - c.Read(*m) -} - -func FuzzAddrString(m *string, c fuzz.Continue) { - var x sdk.AccAddress - FuzzAddr(&x, c) - *m = x.String() -} - -func FuzzAbsoluteTxPosition(m *types.AbsoluteTxPosition, c fuzz.Continue) { - m.BlockHeight = c.RandUint64() - m.TxIndex = c.RandUint64() -} - -func FuzzContractInfo(m *types.ContractInfo, c fuzz.Continue) { - m.CodeID = c.RandUint64() - FuzzAddrString(&m.Creator, c) - FuzzAddrString(&m.Admin, c) - m.Label = c.RandString() - c.Fuzz(&m.Created) -} - -func FuzzContractCodeHistory(m *types.ContractCodeHistoryEntry, c fuzz.Continue) { - const maxMsgSize = 128 - m.CodeID = c.RandUint64() - msg := make([]byte, c.RandUint64()%maxMsgSize) - c.Read(msg) - var err error - if m.Msg, err = json.Marshal(msg); err != nil { - panic(err) - } - c.Fuzz(&m.Updated) - m.Operation = types.AllCodeHistoryTypes[c.Int()%len(types.AllCodeHistoryTypes)] -} - -func FuzzStateModel(m *types.Model, c fuzz.Continue) { - m.Key = tmBytes.HexBytes(c.RandString()) - if len(m.Key) != 0 { - c.Fuzz(&m.Value) - return - } - // try again, keys must not be empty - FuzzStateModel(m, c) -} - -func FuzzAccessType(m *types.AccessType, c fuzz.Continue) { - pos := c.Int() % len(types.AllAccessTypes) - for _, v := range types.AllAccessTypes { - if pos == 0 { - *m = v - return - } - pos-- - } -} - -func FuzzAccessConfig(m *types.AccessConfig, c fuzz.Continue) { - FuzzAccessType(&m.Permission, c) - var add sdk.AccAddress - FuzzAddr(&add, c) - *m = m.Permission.With(add) -} diff --git a/x/wasm/keeper/testdata/broken_crc.gzip b/x/wasm/keeper/testdata/broken_crc.gzip deleted file mode 100644 index 378713e..0000000 Binary files a/x/wasm/keeper/testdata/broken_crc.gzip and /dev/null differ diff --git a/x/wasm/keeper/testdata/burner.wasm b/x/wasm/keeper/testdata/burner.wasm deleted file mode 100644 index 6639075..0000000 Binary files a/x/wasm/keeper/testdata/burner.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/contracts.go b/x/wasm/keeper/testdata/contracts.go deleted file mode 100644 index 6073e4d..0000000 --- a/x/wasm/keeper/testdata/contracts.go +++ /dev/null @@ -1,94 +0,0 @@ -package testdata - -import ( - _ "embed" - - typwasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/types" -) - -var ( - //go:embed reflect.wasm - reflectContract []byte - //go:embed reflect_1_1.wasm - migrateReflectContract []byte - //go:embed cyberpunk.wasm - cyberpunkContract []byte - //go:embed ibc_reflect.wasm - ibcReflectContract []byte - //go:embed burner.wasm - burnerContract []byte - //go:embed hackatom.wasm - hackatomContract []byte -) - -func ReflectContractWasm() []byte { - return reflectContract -} - -func MigrateReflectContractWasm() []byte { - return migrateReflectContract -} - -func CyberpunkContractWasm() []byte { - return cyberpunkContract -} - -func IBCReflectContractWasm() []byte { - return ibcReflectContract -} - -func BurnerContractWasm() []byte { - return burnerContract -} - -func HackatomContractWasm() []byte { - return hackatomContract -} - -// ReflectHandleMsg is used to encode handle messages -type ReflectHandleMsg struct { - Reflect *ReflectPayload `json:"reflect_msg,omitempty"` - ReflectSubMsg *ReflectSubPayload `json:"reflect_sub_msg,omitempty"` - ChangeOwner *OwnerPayload `json:"change_owner,omitempty"` -} - -type OwnerPayload struct { - Owner types.Address `json:"owner"` -} - -type ReflectPayload struct { - Msgs []typwasmvmtypes.CosmosMsg `json:"msgs"` -} - -type ReflectSubPayload struct { - Msgs []typwasmvmtypes.SubMsg `json:"msgs"` -} - -// ReflectQueryMsg is used to encode query messages -type ReflectQueryMsg struct { - Owner *struct{} `json:"owner,omitempty"` - Capitalized *Text `json:"capitalized,omitempty"` - Chain *ChainQuery `json:"chain,omitempty"` - SubMsgResult *SubCall `json:"sub_msg_result,omitempty"` -} - -type ChainQuery struct { - Request *typwasmvmtypes.QueryRequest `json:"request,omitempty"` -} - -type Text struct { - Text string `json:"text"` -} - -type SubCall struct { - ID uint64 `json:"id"` -} - -type OwnerResponse struct { - Owner string `json:"owner,omitempty"` -} - -type ChainResponse struct { - Data []byte `json:"data,omitempty"` -} diff --git a/x/wasm/keeper/testdata/cyberpunk.wasm b/x/wasm/keeper/testdata/cyberpunk.wasm deleted file mode 100644 index 355804a..0000000 Binary files a/x/wasm/keeper/testdata/cyberpunk.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/download_releases.sh b/x/wasm/keeper/testdata/download_releases.sh deleted file mode 100755 index 544cdd2..0000000 --- a/x/wasm/keeper/testdata/download_releases.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail -command -v shellcheck > /dev/null && shellcheck "$0" - -if [ $# -ne 1 ]; then - echo "Usage: ./download_releases.sh RELEASE_TAG" - exit 1 -fi - -tag="$1" - -for contract in burner hackatom ibc_reflect ibc_reflect_send reflect staking cyberpunk; do - url="https://github.com/CosmWasm/cosmwasm/releases/download/$tag/${contract}.wasm" - echo "Downloading $url ..." - wget -O "${contract}.wasm" "$url" -done - -# create the zip variant -gzip -k hackatom.wasm -mv hackatom.wasm.gz hackatom.wasm.gzip - -rm -f version.txt -echo "$tag" >version.txt \ No newline at end of file diff --git a/x/wasm/keeper/testdata/genesis.json b/x/wasm/keeper/testdata/genesis.json deleted file mode 100644 index 08969c7..0000000 --- a/x/wasm/keeper/testdata/genesis.json +++ /dev/null @@ -1,219 +0,0 @@ -{ - "genesis_time": "2020-07-13T07:49:08.2945876Z", - "chain_id": "testing", - "consensus_params": { - "block": { - "max_bytes": "22020096", - "max_gas": "-1", - "time_iota_ms": "1000" - }, - "evidence": { - "max_age_num_blocks": "100000", - "max_age_duration": "172800000000000" - }, - "validator": { - "pub_key_types": [ - "ed25519" - ] - } - }, - "app_hash": "", - "app_state": { - "upgrade": {}, - "evidence": { - "params": { - "max_evidence_age": "120000000000" - }, - "evidence": [] - }, - "supply": { - "supply": [] - }, - "mint": { - "minter": { - "inflation": "0.130000000000000000", - "annual_provisions": "0.000000000000000000" - }, - "params": { - "mint_denom": "ustake", - "inflation_rate_change": "0.130000000000000000", - "inflation_max": "0.200000000000000000", - "inflation_min": "0.070000000000000000", - "goal_bonded": "0.670000000000000000", - "blocks_per_year": "6311520" - } - }, - "gov": { - "starting_proposal_id": "1", - "deposits": null, - "votes": null, - "proposals": null, - "deposit_params": { - "min_deposit": [ - { - "denom": "ustake", - "amount": "1" - } - ], - "max_deposit_period": "172800000000000" - }, - "voting_params": { - "voting_period": "60000000000", - "voting_period_desc": "1minute" - }, - "tally_params": { - "quorum": "0.000000000000000001", - "threshold": "0.000000000000000001", - "veto": "0.334000000000000000" - } - }, - "slashing": { - "params": { - "signed_blocks_window": "100", - "min_signed_per_window": "0.500000000000000000", - "downtime_jail_duration": "600000000000", - "slash_fraction_double_sign": "0.050000000000000000", - "slash_fraction_downtime": "0.010000000000000000" - }, - "signing_infos": {}, - "missed_blocks": {} - }, - "wasm": { - "params": { - "upload_access": { - "type": 3, - "address": "" - }, - "instantiate_default_permission": 3 - }, - "codes": null, - "contracts": null, - "sequences": null - }, - "bank": { - "send_enabled": true - }, - "distribution": { - "params": { - "community_tax": "0.020000000000000000", - "base_proposer_reward": "0.010000000000000000", - "bonus_proposer_reward": "0.040000000000000000", - "withdraw_addr_enabled": true - }, - "fee_pool": { - "community_pool": [] - }, - "delegator_withdraw_infos": [], - "previous_proposer": "", - "outstanding_rewards": [], - "validator_accumulated_commissions": [], - "validator_historical_rewards": [], - "validator_current_rewards": [], - "delegator_starting_infos": [], - "validator_slash_events": [] - }, - "crisis": { - "constant_fee": { - "denom": "ustake", - "amount": "1000" - } - }, - "genutil": { - "gentxs": [ - { - "type": "cosmos-sdk/StdTx", - "value": { - "msg": [ - { - "type": "cosmos-sdk/MsgCreateValidator", - "value": { - "description": { - "moniker": "testing", - "identity": "", - "website": "", - "security_contact": "", - "details": "" - }, - "commission": { - "rate": "0.100000000000000000", - "max_rate": "0.200000000000000000", - "max_change_rate": "0.010000000000000000" - }, - "min_self_delegation": "1", - "delegator_address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "validator_address": "cosmosvaloper1ve557a5g9yw2g2z57js3pdmcvd5my6g88d76lj", - "pubkey": "cosmosvalconspub1zcjduepqddfln4tujr2p8actpgqz4h2xnls9y7tu9c9tu5lqkdglmdjalzuqah4neg", - "value": { - "denom": "ustake", - "amount": "250000000" - } - } - } - ], - "fee": { - "amount": [], - "gas": "200000" - }, - "signatures": [ - { - "pub_key": { - "type": "tendermint/PubKeySecp256k1", - "value": "A//cqZxkpH1re0VrHBtH308nb5t8K+Y/hF0GeRdRBmaJ" - }, - "signature": "5QEEIuUVQTEBMuAtOOHnnKo6rPsIbmfzUxUqRnDFERVqwVr1Kg+ex4f/UGIK0yrOAvOG8zDADwFP4yF8lw+o5g==" - } - ], - "memo": "836fc54e9cad58f4ed6420223ec6290f75342afa@172.17.0.2:26656" - } - } - ] - }, - "auth": { - "params": { - "max_memo_characters": "256", - "tx_sig_limit": "7", - "tx_size_cost_per_byte": "10", - "sig_verify_cost_ed25519": "590", - "sig_verify_cost_secp256k1": "1000" - }, - "accounts": [ - { - "type": "cosmos-sdk/Account", - "value": { - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "coins": [ - { - "denom": "ucosm", - "amount": "1000000000" - }, - { - "denom": "ustake", - "amount": "1000000000" - } - ], - "public_key": "", - "account_number": 0, - "sequence": 0 - } - } - ] - }, - "params": null, - "staking": { - "params": { - "unbonding_time": "1814400000000000", - "max_validators": 100, - "max_entries": 7, - "historical_entries": 0, - "bond_denom": "ustake" - }, - "last_total_power": "0", - "last_validator_powers": null, - "validators": null, - "delegations": null, - "unbonding_delegations": null, - "redelegations": null, - "exported": false - } - } -} \ No newline at end of file diff --git a/x/wasm/keeper/testdata/hackatom.wasm b/x/wasm/keeper/testdata/hackatom.wasm deleted file mode 100644 index baa03a8..0000000 Binary files a/x/wasm/keeper/testdata/hackatom.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/hackatom.wasm.gzip b/x/wasm/keeper/testdata/hackatom.wasm.gzip deleted file mode 100644 index 3c95e9b..0000000 Binary files a/x/wasm/keeper/testdata/hackatom.wasm.gzip and /dev/null differ diff --git a/x/wasm/keeper/testdata/ibc_reflect.wasm b/x/wasm/keeper/testdata/ibc_reflect.wasm deleted file mode 100644 index ec73710..0000000 Binary files a/x/wasm/keeper/testdata/ibc_reflect.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/ibc_reflect_send.wasm b/x/wasm/keeper/testdata/ibc_reflect_send.wasm deleted file mode 100644 index 0f7d7e4..0000000 Binary files a/x/wasm/keeper/testdata/ibc_reflect_send.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/reflect.wasm b/x/wasm/keeper/testdata/reflect.wasm deleted file mode 100644 index 3173564..0000000 Binary files a/x/wasm/keeper/testdata/reflect.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/reflect.wasm.v1_0 b/x/wasm/keeper/testdata/reflect.wasm.v1_0 deleted file mode 100644 index 312f457..0000000 Binary files a/x/wasm/keeper/testdata/reflect.wasm.v1_0 and /dev/null differ diff --git a/x/wasm/keeper/testdata/reflect_1_1.wasm b/x/wasm/keeper/testdata/reflect_1_1.wasm deleted file mode 100644 index 7383a6d..0000000 Binary files a/x/wasm/keeper/testdata/reflect_1_1.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/staking.wasm b/x/wasm/keeper/testdata/staking.wasm deleted file mode 100644 index 015ae00..0000000 Binary files a/x/wasm/keeper/testdata/staking.wasm and /dev/null differ diff --git a/x/wasm/keeper/testdata/version.txt b/x/wasm/keeper/testdata/version.txt deleted file mode 100644 index 79127d8..0000000 --- a/x/wasm/keeper/testdata/version.txt +++ /dev/null @@ -1 +0,0 @@ -v1.2.0 diff --git a/x/wasm/keeper/wasmtesting/extension_mocks.go b/x/wasm/keeper/wasmtesting/extension_mocks.go deleted file mode 100644 index 562d9e7..0000000 --- a/x/wasm/keeper/wasmtesting/extension_mocks.go +++ /dev/null @@ -1,28 +0,0 @@ -package wasmtesting - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -type MockCoinTransferrer struct { - TransferCoinsFn func(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error -} - -func (m *MockCoinTransferrer) TransferCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error { - if m.TransferCoinsFn == nil { - panic("not expected to be called") - } - return m.TransferCoinsFn(ctx, fromAddr, toAddr, amt) -} - -type AccountPrunerMock struct { - CleanupExistingAccountFn func(ctx sdk.Context, existingAccount authtypes.AccountI) (handled bool, err error) -} - -func (m AccountPrunerMock) CleanupExistingAccount(ctx sdk.Context, existingAccount authtypes.AccountI) (handled bool, err error) { - if m.CleanupExistingAccountFn == nil { - panic("not expected to be called") - } - return m.CleanupExistingAccountFn(ctx, existingAccount) -} diff --git a/x/wasm/keeper/wasmtesting/gas_register.go b/x/wasm/keeper/wasmtesting/gas_register.go deleted file mode 100644 index 516cd5f..0000000 --- a/x/wasm/keeper/wasmtesting/gas_register.go +++ /dev/null @@ -1,74 +0,0 @@ -package wasmtesting - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MockGasRegister mock that implements keeper.GasRegister -type MockGasRegister struct { - CompileCostFn func(byteLength int) sdk.Gas - NewContractInstanceCostFn func(pinned bool, msgLen int) sdk.Gas - InstantiateContractCostFn func(pinned bool, msgLen int) sdk.Gas - ReplyCostFn func(pinned bool, reply wasmvmtypes.Reply) sdk.Gas - EventCostsFn func(evts []wasmvmtypes.EventAttribute) sdk.Gas - ToWasmVMGasFn func(source sdk.Gas) uint64 - FromWasmVMGasFn func(source uint64) sdk.Gas - UncompressCostsFn func(byteLength int) sdk.Gas -} - -func (m MockGasRegister) NewContractInstanceCosts(pinned bool, msgLen int) sdk.Gas { - if m.NewContractInstanceCostFn == nil { - panic("not expected to be called") - } - return m.NewContractInstanceCostFn(pinned, msgLen) -} - -func (m MockGasRegister) CompileCosts(byteLength int) sdk.Gas { - if m.CompileCostFn == nil { - panic("not expected to be called") - } - return m.CompileCostFn(byteLength) -} - -func (m MockGasRegister) UncompressCosts(byteLength int) sdk.Gas { - if m.UncompressCostsFn == nil { - panic("not expected to be called") - } - return m.UncompressCostsFn(byteLength) -} - -func (m MockGasRegister) InstantiateContractCosts(pinned bool, msgLen int) sdk.Gas { - if m.InstantiateContractCostFn == nil { - panic("not expected to be called") - } - return m.InstantiateContractCostFn(pinned, msgLen) -} - -func (m MockGasRegister) ReplyCosts(pinned bool, reply wasmvmtypes.Reply) sdk.Gas { - if m.ReplyCostFn == nil { - panic("not expected to be called") - } - return m.ReplyCostFn(pinned, reply) -} - -func (m MockGasRegister) EventCosts(evts []wasmvmtypes.EventAttribute, _ wasmvmtypes.Events) sdk.Gas { - if m.EventCostsFn == nil { - panic("not expected to be called") - } - return m.EventCostsFn(evts) -} - -func (m MockGasRegister) ToWasmVMGas(source sdk.Gas) uint64 { - if m.ToWasmVMGasFn == nil { - panic("not expected to be called") - } - return m.ToWasmVMGasFn(source) -} - -func (m MockGasRegister) FromWasmVMGas(source uint64) sdk.Gas { - if m.FromWasmVMGasFn == nil { - panic("not expected to be called") - } - return m.FromWasmVMGasFn(source) -} diff --git a/x/wasm/keeper/wasmtesting/message_router.go b/x/wasm/keeper/wasmtesting/message_router.go deleted file mode 100644 index 712e012..0000000 --- a/x/wasm/keeper/wasmtesting/message_router.go +++ /dev/null @@ -1,27 +0,0 @@ -package wasmtesting - -import ( - "github.com/cosmos/cosmos-sdk/baseapp" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MockMessageRouter mock for testing -type MockMessageRouter struct { - HandlerFn func(msg sdk.Msg) baseapp.MsgServiceHandler -} - -// Handler is the entry point -func (m MockMessageRouter) Handler(msg sdk.Msg) baseapp.MsgServiceHandler { - if m.HandlerFn == nil { - panic("not expected to be called") - } - return m.HandlerFn(msg) -} - -// MessageRouterFunc convenient type to match the keeper.MessageRouter interface -type MessageRouterFunc func(msg sdk.Msg) baseapp.MsgServiceHandler - -// Handler is the entry point -func (m MessageRouterFunc) Handler(msg sdk.Msg) baseapp.MsgServiceHandler { - return m(msg) -} diff --git a/x/wasm/keeper/wasmtesting/messenger.go b/x/wasm/keeper/wasmtesting/messenger.go deleted file mode 100644 index dbafda3..0000000 --- a/x/wasm/keeper/wasmtesting/messenger.go +++ /dev/null @@ -1,38 +0,0 @@ -package wasmtesting - -import ( - "errors" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type MockMessageHandler struct { - DispatchMsgFn func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) -} - -func (m *MockMessageHandler) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - if m.DispatchMsgFn == nil { - panic("not expected to be called") - } - return m.DispatchMsgFn(ctx, contractAddr, contractIBCPortID, msg) -} - -func NewCapturingMessageHandler() (*MockMessageHandler, *[]wasmvmtypes.CosmosMsg) { - var messages []wasmvmtypes.CosmosMsg - return &MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - messages = append(messages, msg) - // return one data item so that this doesn't cause an error in submessage processing (it takes the first element from data) - return nil, [][]byte{{1}}, nil - }, - }, &messages -} - -func NewErroringMessageHandler() *MockMessageHandler { - return &MockMessageHandler{ - DispatchMsgFn: func(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { - return nil, nil, errors.New("test, ignore") - }, - } -} diff --git a/x/wasm/keeper/wasmtesting/mock_engine.go b/x/wasm/keeper/wasmtesting/mock_engine.go deleted file mode 100644 index 052d165..0000000 --- a/x/wasm/keeper/wasmtesting/mock_engine.go +++ /dev/null @@ -1,402 +0,0 @@ -package wasmtesting - -import ( - "bytes" - "crypto/sha256" - - errorsmod "cosmossdk.io/errors" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/rand" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var _ types.WasmerEngine = &MockWasmer{} - -// MockWasmer implements types.WasmerEngine for testing purpose. One or multiple messages can be stubbed. -// Without a stub function a panic is thrown. -type MockWasmer struct { - CreateFn func(codeID wasmvm.WasmCode) (wasmvm.Checksum, error) - AnalyzeCodeFn func(codeID wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) - InstantiateFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - ExecuteFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - QueryFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, queryMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) ([]byte, uint64, error) - MigrateFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, migrateMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - SudoFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, sudoMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - ReplyFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) - GetCodeFn func(codeID wasmvm.Checksum) (wasmvm.WasmCode, error) - CleanupFn func() - IBCChannelOpenFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) - IBCChannelConnectFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCChannelCloseFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCPacketReceiveFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) - IBCPacketAckFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCPacketTimeoutFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - PinFn func(checksum wasmvm.Checksum) error - UnpinFn func(checksum wasmvm.Checksum) error - GetMetricsFn func() (*wasmvmtypes.Metrics, error) -} - -func (m *MockWasmer) IBCChannelOpen(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - if m.IBCChannelOpenFn == nil { - panic("not supposed to be called!") - } - return m.IBCChannelOpenFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCChannelConnect(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCChannelConnectFn == nil { - panic("not supposed to be called!") - } - return m.IBCChannelConnectFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCChannelClose(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCChannelCloseFn == nil { - panic("not supposed to be called!") - } - return m.IBCChannelCloseFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCPacketReceive(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - if m.IBCPacketReceiveFn == nil { - panic("not supposed to be called!") - } - return m.IBCPacketReceiveFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCPacketAck(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCPacketAckFn == nil { - panic("not supposed to be called!") - } - return m.IBCPacketAckFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) IBCPacketTimeout(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCPacketTimeoutFn == nil { - panic("not supposed to be called!") - } - return m.IBCPacketTimeoutFn(codeID, env, msg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Create(codeID wasmvm.WasmCode) (wasmvm.Checksum, error) { - if m.CreateFn == nil { - panic("not supposed to be called!") - } - return m.CreateFn(codeID) -} - -func (m *MockWasmer) AnalyzeCode(codeID wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) { - if m.AnalyzeCodeFn == nil { - panic("not supposed to be called!") - } - return m.AnalyzeCodeFn(codeID) -} - -func (m *MockWasmer) Instantiate(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.InstantiateFn == nil { - panic("not supposed to be called!") - } - return m.InstantiateFn(codeID, env, info, initMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Execute(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.ExecuteFn == nil { - panic("not supposed to be called!") - } - return m.ExecuteFn(codeID, env, info, executeMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Query(codeID wasmvm.Checksum, env wasmvmtypes.Env, queryMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) ([]byte, uint64, error) { - if m.QueryFn == nil { - panic("not supposed to be called!") - } - return m.QueryFn(codeID, env, queryMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Migrate(codeID wasmvm.Checksum, env wasmvmtypes.Env, migrateMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.MigrateFn == nil { - panic("not supposed to be called!") - } - return m.MigrateFn(codeID, env, migrateMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Sudo(codeID wasmvm.Checksum, env wasmvmtypes.Env, sudoMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.SudoFn == nil { - panic("not supposed to be called!") - } - return m.SudoFn(codeID, env, sudoMsg, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) Reply(codeID wasmvm.Checksum, env wasmvmtypes.Env, reply wasmvmtypes.Reply, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - if m.ReplyFn == nil { - panic("not supposed to be called!") - } - return m.ReplyFn(codeID, env, reply, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m *MockWasmer) GetCode(codeID wasmvm.Checksum) (wasmvm.WasmCode, error) { - if m.GetCodeFn == nil { - panic("not supposed to be called!") - } - return m.GetCodeFn(codeID) -} - -func (m *MockWasmer) Cleanup() { - if m.CleanupFn == nil { - panic("not supposed to be called!") - } - m.CleanupFn() -} - -func (m *MockWasmer) Pin(checksum wasmvm.Checksum) error { - if m.PinFn == nil { - panic("not supposed to be called!") - } - return m.PinFn(checksum) -} - -func (m *MockWasmer) Unpin(checksum wasmvm.Checksum) error { - if m.UnpinFn == nil { - panic("not supposed to be called!") - } - return m.UnpinFn(checksum) -} - -func (m *MockWasmer) GetMetrics() (*wasmvmtypes.Metrics, error) { - if m.GetMetricsFn == nil { - panic("not expected to be called") - } - return m.GetMetricsFn() -} - -var AlwaysPanicMockWasmer = &MockWasmer{} - -// SelfCallingInstMockWasmer prepares a Wasmer mock that calls itself on instantiation. -func SelfCallingInstMockWasmer(executeCalled *bool) *MockWasmer { - return &MockWasmer{ - CreateFn: func(code wasmvm.WasmCode) (wasmvm.Checksum, error) { - anyCodeID := bytes.Repeat([]byte{0x1}, 32) - return anyCodeID, nil - }, - InstantiateFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{ - Messages: []wasmvmtypes.SubMsg{ - {Msg: wasmvmtypes.CosmosMsg{ - Wasm: &wasmvmtypes.WasmMsg{Execute: &wasmvmtypes.ExecuteMsg{ContractAddr: env.Contract.Address, Msg: []byte(`{}`)}}, - }}, - }, - }, 1, nil - }, - AnalyzeCodeFn: WithoutIBCAnalyzeFn, - ExecuteFn: func(codeID wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - *executeCalled = true - return &wasmvmtypes.Response{}, 1, nil - }, - } -} - -// IBCContractCallbacks defines the methods from wasmvm to interact with the wasm contract. -// A mock contract would implement the interface to fully simulate a wasm contract's behaviour. -type IBCContractCallbacks interface { - IBCChannelOpen( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelOpenMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) - - IBCChannelConnect( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelConnectMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - IBCChannelClose( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelCloseMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - IBCPacketReceive( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - packet wasmvmtypes.IBCPacketReceiveMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCReceiveResult, uint64, error) - - IBCPacketAck( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - ack wasmvmtypes.IBCPacketAckMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - IBCPacketTimeout( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - packet wasmvmtypes.IBCPacketTimeoutMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) -} - -type contractExecutable interface { - Execute( - codeID wasmvm.Checksum, - env wasmvmtypes.Env, - info wasmvmtypes.MessageInfo, - executeMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) -} - -// MakeInstantiable adds some noop functions to not fail when contract is used for instantiation -func MakeInstantiable(m *MockWasmer) { - m.CreateFn = HashOnlyCreateFn - m.InstantiateFn = NoOpInstantiateFn - m.AnalyzeCodeFn = WithoutIBCAnalyzeFn -} - -// MakeIBCInstantiable adds some noop functions to not fail when contract is used for instantiation -func MakeIBCInstantiable(m *MockWasmer) { - MakeInstantiable(m) - m.AnalyzeCodeFn = HasIBCAnalyzeFn -} - -// NewIBCContractMockWasmer prepares a mocked wasm_engine for testing with an IBC contract test type. -// It is safe to use the mock with store code and instantiate functions in keeper as is also prepared -// with stubs. Execute is optional. When implemented by the Go test contract then it can be used with -// the mock. -func NewIBCContractMockWasmer(c IBCContractCallbacks) *MockWasmer { - m := &MockWasmer{ - IBCChannelOpenFn: c.IBCChannelOpen, - IBCChannelConnectFn: c.IBCChannelConnect, - IBCChannelCloseFn: c.IBCChannelClose, - IBCPacketReceiveFn: c.IBCPacketReceive, - IBCPacketAckFn: c.IBCPacketAck, - IBCPacketTimeoutFn: c.IBCPacketTimeout, - } - MakeIBCInstantiable(m) - if e, ok := c.(contractExecutable); ok { // optional function - m.ExecuteFn = e.Execute - } - return m -} - -func HashOnlyCreateFn(code wasmvm.WasmCode) (wasmvm.Checksum, error) { - if code == nil { - return nil, errorsmod.Wrap(types.ErrInvalid, "wasm code must not be nil") - } - hash := sha256.Sum256(code) - return hash[:], nil -} - -func NoOpInstantiateFn(wasmvm.Checksum, wasmvmtypes.Env, wasmvmtypes.MessageInfo, []byte, wasmvm.KVStore, wasmvm.GoAPI, wasmvm.Querier, wasmvm.GasMeter, uint64, wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - return &wasmvmtypes.Response{}, 0, nil -} - -func NoOpCreateFn(_ wasmvm.WasmCode) (wasmvm.Checksum, error) { - return rand.Bytes(32), nil -} - -func HasIBCAnalyzeFn(wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) { - return &wasmvmtypes.AnalysisReport{ - HasIBCEntryPoints: true, - }, nil -} - -func WithoutIBCAnalyzeFn(wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) { - return &wasmvmtypes.AnalysisReport{}, nil -} - -var _ IBCContractCallbacks = &MockIBCContractCallbacks{} - -type MockIBCContractCallbacks struct { - IBCChannelOpenFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) - IBCChannelConnectFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCChannelCloseFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCPacketReceiveFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) - IBCPacketAckFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) - IBCPacketTimeoutFn func(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) -} - -func (m MockIBCContractCallbacks) IBCChannelOpen(codeID wasmvm.Checksum, env wasmvmtypes.Env, channel wasmvmtypes.IBCChannelOpenMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - if m.IBCChannelOpenFn == nil { - panic("not expected to be called") - } - return m.IBCChannelOpenFn(codeID, env, channel, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCChannelConnect(codeID wasmvm.Checksum, env wasmvmtypes.Env, channel wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCChannelConnectFn == nil { - panic("not expected to be called") - } - return m.IBCChannelConnectFn(codeID, env, channel, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCChannelClose(codeID wasmvm.Checksum, env wasmvmtypes.Env, channel wasmvmtypes.IBCChannelCloseMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCChannelCloseFn == nil { - panic("not expected to be called") - } - return m.IBCChannelCloseFn(codeID, env, channel, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCPacketReceive(codeID wasmvm.Checksum, env wasmvmtypes.Env, packet wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - if m.IBCPacketReceiveFn == nil { - panic("not expected to be called") - } - return m.IBCPacketReceiveFn(codeID, env, packet, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCPacketAck(codeID wasmvm.Checksum, env wasmvmtypes.Env, ack wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCPacketAckFn == nil { - panic("not expected to be called") - } - return m.IBCPacketAckFn(codeID, env, ack, store, goapi, querier, gasMeter, gasLimit, deserCost) -} - -func (m MockIBCContractCallbacks) IBCPacketTimeout(codeID wasmvm.Checksum, env wasmvmtypes.Env, packet wasmvmtypes.IBCPacketTimeoutMsg, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - if m.IBCPacketTimeoutFn == nil { - panic("not expected to be called") - } - return m.IBCPacketTimeoutFn(codeID, env, packet, store, goapi, querier, gasMeter, gasLimit, deserCost) -} diff --git a/x/wasm/keeper/wasmtesting/mock_keepers.go b/x/wasm/keeper/wasmtesting/mock_keepers.go deleted file mode 100644 index 021a29f..0000000 --- a/x/wasm/keeper/wasmtesting/mock_keepers.go +++ /dev/null @@ -1,112 +0,0 @@ -package wasmtesting - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type MockChannelKeeper struct { - GetChannelFn func(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) - SendPacketFn func(ctx sdk.Context, channelCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte) (uint64, error) - ChanCloseInitFn func(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error - GetAllChannelsFn func(ctx sdk.Context) []channeltypes.IdentifiedChannel - IterateChannelsFn func(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) - SetChannelFn func(ctx sdk.Context, portID, channelID string, channel channeltypes.Channel) -} - -func (m *MockChannelKeeper) GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) { - if m.GetChannelFn == nil { - panic("not supposed to be called!") - } - return m.GetChannelFn(ctx, srcPort, srcChan) -} - -func (m *MockChannelKeeper) GetAllChannels(ctx sdk.Context) []channeltypes.IdentifiedChannel { - if m.GetAllChannelsFn == nil { - panic("not supposed to be called!") - } - return m.GetAllChannelsFn(ctx) -} - -func (m *MockChannelKeeper) SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, sourcePort string, sourceChannel string, timeoutHeight clienttypes.Height, timeoutTimestamp uint64, data []byte) (uint64, error) { - if m.SendPacketFn == nil { - panic("not supposed to be called!") - } - return m.SendPacketFn(ctx, channelCap, sourcePort, sourceChannel, timeoutHeight, timeoutTimestamp, data) -} - -func (m *MockChannelKeeper) ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error { - if m.ChanCloseInitFn == nil { - panic("not supposed to be called!") - } - return m.ChanCloseInitFn(ctx, portID, channelID, chanCap) -} - -func (m *MockChannelKeeper) IterateChannels(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) { - if m.IterateChannelsFn == nil { - panic("not expected to be called") - } - m.IterateChannelsFn(ctx, cb) -} - -func (m *MockChannelKeeper) SetChannel(ctx sdk.Context, portID, channelID string, channel channeltypes.Channel) { - if m.GetChannelFn == nil { - panic("not supposed to be called!") - } - m.SetChannelFn(ctx, portID, channelID, channel) -} - -func MockChannelKeeperIterator(s []channeltypes.IdentifiedChannel) func(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) { - return func(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) { - for _, channel := range s { - stop := cb(channel) - if stop { - break - } - } - } -} - -type MockCapabilityKeeper struct { - GetCapabilityFn func(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) - ClaimCapabilityFn func(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error - AuthenticateCapabilityFn func(ctx sdk.Context, capability *capabilitytypes.Capability, name string) bool -} - -func (m MockCapabilityKeeper) GetCapability(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) { - if m.GetCapabilityFn == nil { - panic("not supposed to be called!") - } - return m.GetCapabilityFn(ctx, name) -} - -func (m MockCapabilityKeeper) ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error { - if m.ClaimCapabilityFn == nil { - panic("not supposed to be called!") - } - return m.ClaimCapabilityFn(ctx, cap, name) -} - -func (m MockCapabilityKeeper) AuthenticateCapability(ctx sdk.Context, capability *capabilitytypes.Capability, name string) bool { - if m.AuthenticateCapabilityFn == nil { - panic("not supposed to be called!") - } - return m.AuthenticateCapabilityFn(ctx, capability, name) -} - -var _ types.ICS20TransferPortSource = &MockIBCTransferKeeper{} - -type MockIBCTransferKeeper struct { - GetPortFn func(ctx sdk.Context) string -} - -func (m MockIBCTransferKeeper) GetPort(ctx sdk.Context) string { - if m.GetPortFn == nil { - panic("not expected to be called") - } - return m.GetPortFn(ctx) -} diff --git a/x/wasm/keeper/wasmtesting/msg_dispatcher.go b/x/wasm/keeper/wasmtesting/msg_dispatcher.go deleted file mode 100644 index a660094..0000000 --- a/x/wasm/keeper/wasmtesting/msg_dispatcher.go +++ /dev/null @@ -1,17 +0,0 @@ -package wasmtesting - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type MockMsgDispatcher struct { - DispatchSubmessagesFn func(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) -} - -func (m MockMsgDispatcher) DispatchSubmessages(ctx sdk.Context, contractAddr sdk.AccAddress, ibcPort string, msgs []wasmvmtypes.SubMsg) ([]byte, error) { - if m.DispatchSubmessagesFn == nil { - panic("not expected to be called") - } - return m.DispatchSubmessagesFn(ctx, contractAddr, ibcPort, msgs) -} diff --git a/x/wasm/keeper/wasmtesting/query_handler.go b/x/wasm/keeper/wasmtesting/query_handler.go deleted file mode 100644 index 52cf97d..0000000 --- a/x/wasm/keeper/wasmtesting/query_handler.go +++ /dev/null @@ -1,17 +0,0 @@ -package wasmtesting - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type MockQueryHandler struct { - HandleQueryFn func(ctx sdk.Context, request wasmvmtypes.QueryRequest, caller sdk.AccAddress) ([]byte, error) -} - -func (m *MockQueryHandler) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { - if m.HandleQueryFn == nil { - panic("not expected to be called") - } - return m.HandleQueryFn(ctx, request, caller) -} diff --git a/x/wasm/keeper/wasmtesting/store.go b/x/wasm/keeper/wasmtesting/store.go deleted file mode 100644 index 6548c8b..0000000 --- a/x/wasm/keeper/wasmtesting/store.go +++ /dev/null @@ -1,26 +0,0 @@ -package wasmtesting - -import ( - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// MockCommitMultiStore mock with a CacheMultiStore to capture commits -type MockCommitMultiStore struct { - sdk.CommitMultiStore - Committed []bool -} - -func (m *MockCommitMultiStore) CacheMultiStore() storetypes.CacheMultiStore { - m.Committed = append(m.Committed, false) - return &mockCMS{m, &m.Committed[len(m.Committed)-1]} -} - -type mockCMS struct { - sdk.CommitMultiStore - committed *bool -} - -func (m *mockCMS) Write() { - *m.committed = true -} diff --git a/x/wasm/migrations/v1/store.go b/x/wasm/migrations/v1/store.go deleted file mode 100644 index f2c6dbb..0000000 --- a/x/wasm/migrations/v1/store.go +++ /dev/null @@ -1,36 +0,0 @@ -package v1 - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// AddToSecondIndexFn creates a secondary index entry for the creator fo the contract -type AddToSecondIndexFn func(ctx sdk.Context, creatorAddress sdk.AccAddress, position *types.AbsoluteTxPosition, contractAddress sdk.AccAddress) - -// Keeper abstract keeper -type wasmKeeper interface { - IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, types.ContractInfo) bool) -} - -// Migrator is a struct for handling in-place store migrations. -type Migrator struct { - keeper wasmKeeper - addToSecondIndexFn AddToSecondIndexFn -} - -// NewMigrator returns a new Migrator. -func NewMigrator(k wasmKeeper, fn AddToSecondIndexFn) Migrator { - return Migrator{keeper: k, addToSecondIndexFn: fn} -} - -// Migrate1to2 migrates from version 1 to 2. -func (m Migrator) Migrate1to2(ctx sdk.Context) error { - m.keeper.IterateContractInfo(ctx, func(contractAddr sdk.AccAddress, contractInfo types.ContractInfo) bool { - creator := sdk.MustAccAddressFromBech32(contractInfo.Creator) - m.addToSecondIndexFn(ctx, creator, contractInfo.Created, contractAddr) - return false - }) - return nil -} diff --git a/x/wasm/migrations/v1/store_test.go b/x/wasm/migrations/v1/store_test.go deleted file mode 100644 index 990baac..0000000 --- a/x/wasm/migrations/v1/store_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package v1_test - -import ( - "bytes" - "encoding/json" - "testing" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestMigrate1To2(t *testing.T) { - const AvailableCapabilities = "iterator,staking,stargate,cosmwasm_1_1" - ctx, keepers := keeper.CreateTestInput(t, false, AvailableCapabilities) - wasmKeeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - keepers.Faucet.Fund(ctx, creator, deposit...) - example := keeper.StoreHackatomExampleContract(t, ctx, keepers) - - initMsg := keeper.HackatomExampleInitMsg{ - Verifier: keeper.RandomAccountAddress(t), - Beneficiary: keeper.RandomAccountAddress(t), - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - em := sdk.NewEventManager() - - // create with no balance is also legal - gotContractAddr1, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil) - require.NoError(t, err) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // create with no balance is also legal - gotContractAddr2, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil) - require.NoError(t, err) - ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) - - // create with no balance is also legal - gotContractAddr3, _, err := keepers.ContractKeeper.Instantiate(ctx.WithEventManager(em), example.CodeID, creator, nil, initMsgBz, "demo contract 1", nil) - require.NoError(t, err) - - info1 := wasmKeeper.GetContractInfo(ctx, gotContractAddr1) - info2 := wasmKeeper.GetContractInfo(ctx, gotContractAddr2) - info3 := wasmKeeper.GetContractInfo(ctx, gotContractAddr3) - - // remove key - ctx.KVStore(keepers.WasmStoreKey).Delete(types.GetContractByCreatorSecondaryIndexKey(creator, info1.Created.Bytes(), gotContractAddr1)) - ctx.KVStore(keepers.WasmStoreKey).Delete(types.GetContractByCreatorSecondaryIndexKey(creator, info2.Created.Bytes(), gotContractAddr2)) - ctx.KVStore(keepers.WasmStoreKey).Delete(types.GetContractByCreatorSecondaryIndexKey(creator, info3.Created.Bytes(), gotContractAddr3)) - - // migrator - err = keeper.NewMigrator(*wasmKeeper, nil).Migrate1to2(ctx) - require.NoError(t, err) - - // check new store - var allContract []string - wasmKeeper.IterateContractsByCreator(ctx, creator, func(addr sdk.AccAddress) bool { - allContract = append(allContract, addr.String()) - return false - }) - - require.Equal(t, []string{gotContractAddr1.String(), gotContractAddr2.String(), gotContractAddr3.String()}, allContract) -} diff --git a/x/wasm/migrations/v2/store.go b/x/wasm/migrations/v2/store.go deleted file mode 100644 index f6318c0..0000000 --- a/x/wasm/migrations/v2/store.go +++ /dev/null @@ -1,33 +0,0 @@ -package v2 - -import ( - "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/wasm/exported" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// MigrateStore migrates the x/wasm module state from the consensus version 2 to -// version 3. Specifically, it takes the parameters that are currently stored -// and managed by the x/params module and stores them directly into the x/wasm -// module state. -func MigrateStore(ctx sdk.Context, storeKey storetypes.StoreKey, legacySubspace exported.Subspace, cdc codec.BinaryCodec) error { - store := ctx.KVStore(storeKey) - var currParams types.Params - legacySubspace.GetParamSet(ctx, &currParams) - - if err := currParams.ValidateBasic(); err != nil { - return err - } - - bz, err := cdc.Marshal(&currParams) - if err != nil { - return err - } - - store.Set(types.ParamsKey, bz) - - return nil -} diff --git a/x/wasm/module.go b/x/wasm/module.go deleted file mode 100644 index 371e804..0000000 --- a/x/wasm/module.go +++ /dev/null @@ -1,314 +0,0 @@ -package wasm - -import ( - "context" - "encoding/json" - "fmt" - "runtime/debug" - "strings" - - "cosmossdk.io/core/appmodule" - - "github.com/cosmos/cosmos-sdk/baseapp" - - wasmvm "github.com/CosmWasm/wasmvm" - 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" - "github.com/cosmos/cosmos-sdk/server" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cast" - "github.com/spf13/cobra" - - "github.com/terpnetwork/terp-core/x/wasm/client/cli" - "github.com/terpnetwork/terp-core/x/wasm/exported" - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/simulation" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -var ( - _ module.AppModuleBasic = AppModuleBasic{} - _ module.AppModuleSimulation = AppModule{} -) - -// Module init related flags -const ( - flagWasmMemoryCacheSize = "wasm.memory_cache_size" - flagWasmQueryGasLimit = "wasm.query_gas_limit" - flagWasmSimulationGasLimit = "wasm.simulation_gas_limit" -) - -// AppModuleBasic defines the basic application module used by the wasm module. -type AppModuleBasic struct{} - -func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { - RegisterCodec(amino) -} - -func (b AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, serveMux *runtime.ServeMux) { - err := types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(clientCtx)) - if err != nil { - panic(err) - } -} - -// Name returns the wasm module's name. -func (AppModuleBasic) Name() string { - return ModuleName -} - -// DefaultGenesis returns default genesis state as raw bytes for the wasm -// module. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(&GenesisState{ - Params: DefaultParams(), - }) -} - -// ValidateGenesis performs genesis state validation for the wasm module. -func (b AppModuleBasic) ValidateGenesis(marshaler codec.JSONCodec, _ client.TxEncodingConfig, message json.RawMessage) error { - var data GenesisState - err := marshaler.UnmarshalJSON(message, &data) - if err != nil { - return err - } - return ValidateGenesis(data) -} - -// GetTxCmd returns the root tx command for the wasm module. -func (b AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns no root query command for the wasm module. -func (b AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd() -} - -// RegisterInterfaces implements InterfaceModule -func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - types.RegisterInterfaces(registry) -} - -// ____________________________________________________________________________ -var _ appmodule.AppModule = AppModule{} - -// AppModule implements an application module for the wasm module. -type AppModule struct { - AppModuleBasic - cdc codec.Codec - keeper *Keeper - validatorSetSource keeper.ValidatorSetSource - accountKeeper types.AccountKeeper // for simulation - bankKeeper simulation.BankKeeper - router keeper.MessageRouter - // legacySubspace is used solely for migration of x/params managed parameters - legacySubspace exported.Subspace -} - -// NewAppModule creates a new AppModule object -func NewAppModule( - cdc codec.Codec, - keeper *Keeper, - validatorSetSource keeper.ValidatorSetSource, - ak types.AccountKeeper, - bk simulation.BankKeeper, - router *baseapp.MsgServiceRouter, - ss exported.Subspace, -) AppModule { - return AppModule{ - AppModuleBasic: AppModuleBasic{}, - cdc: cdc, - keeper: keeper, - validatorSetSource: validatorSetSource, - accountKeeper: ak, - bankKeeper: bk, - router: router, - legacySubspace: ss, - } -} - -// IsOnePerModuleType implements the depinject.OnePerModuleType interface. -func (am AppModule) IsOnePerModuleType() { // marker -} - -// IsAppModule implements the appmodule.AppModule interface. -func (am AppModule) IsAppModule() { // marker -} - -// 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 3 } - -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) - types.RegisterQueryServer(cfg.QueryServer(), NewQuerier(am.keeper)) - - m := keeper.NewMigrator(*am.keeper, am.legacySubspace) - err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2) - if err != nil { - panic(err) - } - err = cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3) - if err != nil { - panic(err) - } -} - -// RegisterInvariants registers the wasm module invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// QuerierRoute returns the wasm module's querier route name. -func (AppModule) QuerierRoute() string { - return QuerierRoute -} - -// InitGenesis performs genesis initialization for the wasm module. It returns -// no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { - var genesisState GenesisState - cdc.MustUnmarshalJSON(data, &genesisState) - validators, err := InitGenesis(ctx, am.keeper, genesisState) - if err != nil { - panic(err) - } - return validators -} - -// ExportGenesis returns the exported genesis state as raw bytes for the wasm -// module. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - gs := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(gs) -} - -// BeginBlock returns the begin blocker for the wasm module. -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock returns the end blocker for the wasm module. It returns no validator -// updates. -func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} - -// ____________________________________________________________________________ - -// AppModuleSimulation functions - -// GenerateGenesisState creates a randomized GenState of the bank module. -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - simulation.RandomizedGenState(simState) -} - -// ProposalMsgs returns msgs used for governance proposals for simulations. -func (am AppModule) ProposalMsgs(simState module.SimulationState) []simtypes.WeightedProposalMsg { - return simulation.ProposalMsgs(am.bankKeeper, am.keeper) -} - -// RegisterStoreDecoder registers a decoder for supply module's types -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) { -} - -// WeightedOperations returns the all the gov module operations with their respective weights. -func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { - return simulation.WeightedOperations(&simState, am.accountKeeper, am.bankKeeper, am.keeper) -} - -// ____________________________________________________________________________ - -// AddModuleInitFlags implements servertypes.ModuleInitFlags interface. -func AddModuleInitFlags(startCmd *cobra.Command) { - defaults := DefaultWasmConfig() - startCmd.Flags().Uint32(flagWasmMemoryCacheSize, defaults.MemoryCacheSize, "Sets the size in MiB (NOT bytes) of an in-memory cache for Wasm modules. Set to 0 to disable.") - startCmd.Flags().Uint64(flagWasmQueryGasLimit, defaults.SmartQueryGasLimit, "Set the max gas that can be spent on executing a query with a Wasm contract") - startCmd.Flags().String(flagWasmSimulationGasLimit, "", "Set the max gas that can be spent when executing a simulation TX") - - startCmd.PreRunE = chainPreRuns(checkLibwasmVersion, startCmd.PreRunE) -} - -// ReadWasmConfig reads the wasm specifig configuration -func ReadWasmConfig(opts servertypes.AppOptions) (types.WasmConfig, error) { - cfg := types.DefaultWasmConfig() - var err error - if v := opts.Get(flagWasmMemoryCacheSize); v != nil { - if cfg.MemoryCacheSize, err = cast.ToUint32E(v); err != nil { - return cfg, err - } - } - if v := opts.Get(flagWasmQueryGasLimit); v != nil { - if cfg.SmartQueryGasLimit, err = cast.ToUint64E(v); err != nil { - return cfg, err - } - } - if v := opts.Get(flagWasmSimulationGasLimit); v != nil { - if raw, ok := v.(string); !ok || raw != "" { - limit, err := cast.ToUint64E(v) // non empty string set - if err != nil { - return cfg, err - } - cfg.SimulationGasLimit = &limit - } - } - // attach contract debugging to global "trace" flag - if v := opts.Get(server.FlagTrace); v != nil { - if cfg.ContractDebugMode, err = cast.ToBoolE(v); err != nil { - return cfg, err - } - } - return cfg, nil -} - -func getExpectedLibwasmVersion() string { - buildInfo, ok := debug.ReadBuildInfo() - if !ok { - panic("can't read build info") - } - for _, d := range buildInfo.Deps { - if d.Path != "github.com/CosmWasm/wasmvm" { - continue - } - if d.Replace != nil { - return d.Replace.Version - } - return d.Version - } - return "" -} - -func checkLibwasmVersion(_ *cobra.Command, _ []string) error { - wasmVersion, err := wasmvm.LibwasmvmVersion() - if err != nil { - return fmt.Errorf("unable to retrieve libwasmversion %w", err) - } - wasmExpectedVersion := getExpectedLibwasmVersion() - if wasmExpectedVersion == "" { - return fmt.Errorf("wasmvm module not exist") - } - if !strings.Contains(wasmExpectedVersion, wasmVersion) { - return fmt.Errorf("libwasmversion mismatch. got: %s; expected: %s", wasmVersion, wasmExpectedVersion) - } - return nil -} - -type preRunFn func(cmd *cobra.Command, args []string) error - -func chainPreRuns(pfns ...preRunFn) preRunFn { - return func(cmd *cobra.Command, args []string) error { - for _, pfn := range pfns { - if pfn != nil { - if err := pfn(cmd, args); err != nil { - return err - } - } - } - return nil - } -} diff --git a/x/wasm/module_test.go b/x/wasm/module_test.go deleted file mode 100644 index 04fcbb8..0000000 --- a/x/wasm/module_test.go +++ /dev/null @@ -1,651 +0,0 @@ -package wasm - -import ( - "bytes" - "encoding/json" - "os" - "strings" - "testing" - - servertypes "github.com/cosmos/cosmos-sdk/server/types" - "github.com/spf13/viper" - - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/crypto/ed25519" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" - "github.com/cosmos/cosmos-sdk/types/module" - authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/wasm/exported" - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type mockSubspace struct { - ps types.Params -} - -func newMockSubspace(ps types.Params) mockSubspace { - return mockSubspace{ps: ps} -} - -func (ms mockSubspace) GetParamSet(ctx sdk.Context, ps exported.ParamSet) { - *ps.(*types.Params) = ms.ps -} - -type testData struct { - module AppModule - ctx sdk.Context - acctKeeper authkeeper.AccountKeeper - keeper Keeper - bankKeeper bankkeeper.Keeper - stakingKeeper *stakingkeeper.Keeper - faucet *keeper.TestFaucet - grpcQueryRouter *baseapp.GRPCQueryRouter - msgServiceRouter *baseapp.MsgServiceRouter - encConf params.EncodingConfig -} - -func setupTest(t *testing.T) testData { - ctx, keepers := CreateTestInput(t, false, "iterator,staking,stargate,cosmwasm_1_1") - encConf := keeper.MakeEncodingConfig(t) - queryRouter := baseapp.NewGRPCQueryRouter() - serviceRouter := baseapp.NewMsgServiceRouter() - queryRouter.SetInterfaceRegistry(encConf.InterfaceRegistry) - serviceRouter.SetInterfaceRegistry(encConf.InterfaceRegistry) - data := testData{ - module: NewAppModule(encConf.Marshaler, keepers.WasmKeeper, keepers.StakingKeeper, keepers.AccountKeeper, keepers.BankKeeper, nil, newMockSubspace(types.DefaultParams())), - ctx: ctx, - acctKeeper: keepers.AccountKeeper, - keeper: *keepers.WasmKeeper, - bankKeeper: keepers.BankKeeper, - stakingKeeper: keepers.StakingKeeper, - faucet: keepers.Faucet, - grpcQueryRouter: queryRouter, - msgServiceRouter: serviceRouter, - encConf: encConf, - } - data.module.RegisterServices(module.NewConfigurator(encConf.Marshaler, serviceRouter, queryRouter)) - return data -} - -func keyPubAddr() sdk.AccAddress { - key := ed25519.GenPrivKey() - pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) - return addr -} - -func mustLoad(path string) []byte { - bz, err := os.ReadFile(path) - if err != nil { - panic(err) - } - return bz -} - -var ( - addrAcc1 = keyPubAddr() - addr1 = addrAcc1.String() - testContract = mustLoad("./keeper/testdata/hackatom.wasm") - maskContract = testdata.ReflectContractWasm() - oldContract = mustLoad("./testdata/escrow_0.7.wasm") -) - -func TestHandleCreate(t *testing.T) { - cases := map[string]struct { - msg sdk.Msg - isValid bool - }{ - "empty": { - msg: &MsgStoreCode{}, - isValid: false, - }, - "invalid wasm": { - msg: &MsgStoreCode{ - Sender: addr1, - WASMByteCode: []byte("foobar"), - }, - isValid: false, - }, - "valid wasm": { - msg: &MsgStoreCode{ - Sender: addr1, - WASMByteCode: testContract, - }, - isValid: true, - }, - "other valid wasm": { - msg: &MsgStoreCode{ - Sender: addr1, - WASMByteCode: maskContract, - }, - isValid: true, - }, - "old wasm (0.7)": { - msg: &MsgStoreCode{ - Sender: addr1, - WASMByteCode: oldContract, - }, - isValid: false, - }, - } - - for name, tc := range cases { - tc := tc - t.Run(name, func(t *testing.T) { - data := setupTest(t) - - h := data.msgServiceRouter.Handler(tc.msg) - // q := data.grpcQueryRouter.Route(sdk.MsgTypeURL(tc.msg)) - q := data.grpcQueryRouter - - res, err := h(data.ctx, tc.msg) - if !tc.isValid { - require.Error(t, err, "%#v", res) - assertCodeList(t, q, data.ctx, 0, data.encConf.Marshaler) - assertCodeBytes(t, q, data.ctx, 1, nil, data.encConf.Marshaler) - return - } - require.NoError(t, err) - assertCodeList(t, q, data.ctx, 1, data.encConf.Marshaler) - }) - } -} - -type initMsg struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` -} - -type state struct { - Verifier string `json:"verifier"` - Beneficiary string `json:"beneficiary"` - Funder string `json:"funder"` -} - -func TestHandleInstantiate(t *testing.T) { - data := setupTest(t) - creator := data.faucet.NewFundedRandomAccount(data.ctx, sdk.NewInt64Coin("denom", 100000)) - - msg := &MsgStoreCode{ - Sender: creator.String(), - WASMByteCode: testContract, - } - - h := data.msgServiceRouter.Handler(msg) - q := data.grpcQueryRouter - - res, err := h(data.ctx, msg) - require.NoError(t, err) - assertStoreCodeResponse(t, res.Data, 1) - - bob := keyPubAddr() - fred := keyPubAddr() - - initPayload := initMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initPayload) - require.NoError(t, err) - - // create with no balance is also legal - initMsg := &MsgInstantiateContract{ - Sender: creator.String(), - CodeID: firstCodeID, - Msg: initMsgBz, - Funds: nil, - Label: "testing", - } - h = data.msgServiceRouter.Handler(initMsg) - res, err = h(data.ctx, initMsg) - require.NoError(t, err) - contractBech32Addr := parseInitResponse(t, res.Data) - - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", contractBech32Addr) - // this should be standard x/wasm init event, nothing from contract - require.Equal(t, 2, len(res.Events), prettyEvents(res.Events)) - require.Equal(t, "instantiate", res.Events[0].Type) - require.Equal(t, "wasm", res.Events[1].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[1].Attributes[0]) - - assertCodeList(t, q, data.ctx, 1, data.encConf.Marshaler) - assertCodeBytes(t, q, data.ctx, 1, testContract, data.encConf.Marshaler) - - assertContractList(t, q, data.ctx, 1, []string{contractBech32Addr}, data.encConf.Marshaler) - assertContractInfo(t, q, data.ctx, contractBech32Addr, 1, creator, data.encConf.Marshaler) - assertContractState(t, q, data.ctx, contractBech32Addr, state{ - Verifier: fred.String(), - Beneficiary: bob.String(), - Funder: creator.String(), - }, data.encConf.Marshaler) -} - -func TestHandleExecute(t *testing.T) { - data := setupTest(t) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - - creator := data.faucet.NewFundedRandomAccount(data.ctx, deposit.Add(deposit...)...) - fred := data.faucet.NewFundedRandomAccount(data.ctx, topUp...) - - msg := &MsgStoreCode{ - Sender: creator.String(), - WASMByteCode: testContract, - } - h := data.msgServiceRouter.Handler(msg) - q := data.grpcQueryRouter - res, err := h(data.ctx, msg) - require.NoError(t, err) - assertStoreCodeResponse(t, res.Data, 1) - - bob := keyPubAddr() - initMsg := initMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - initCmd := &MsgInstantiateContract{ - Sender: creator.String(), - CodeID: firstCodeID, - Msg: initMsgBz, - Funds: deposit, - Label: "testing", - } - h = data.msgServiceRouter.Handler(initCmd) - res, err = h(data.ctx, initCmd) - require.NoError(t, err) - contractBech32Addr := parseInitResponse(t, res.Data) - - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", contractBech32Addr) - // this should be standard x/wasm message event, init event, plus a bank send event (2), with no custom contract events - require.Equal(t, 5, len(res.Events), prettyEvents(res.Events)) - require.Equal(t, "coin_spent", res.Events[0].Type) - require.Equal(t, "coin_received", res.Events[1].Type) - require.Equal(t, "transfer", res.Events[2].Type) - require.Equal(t, "instantiate", res.Events[3].Type) - require.Equal(t, "wasm", res.Events[4].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[4].Attributes[0]) - - // ensure bob doesn't exist - bobAcct := data.acctKeeper.GetAccount(data.ctx, bob) - require.Nil(t, bobAcct) - - // ensure funder has reduced balance - creatorAcct := data.acctKeeper.GetAccount(data.ctx, creator) - require.NotNil(t, creatorAcct) - // we started at 2*deposit, should have spent one above - assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, creatorAcct.GetAddress())) - - // ensure contract has updated balance - contractAddr, _ := sdk.AccAddressFromBech32(contractBech32Addr) - contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) - require.NotNil(t, contractAcct) - assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) - - execCmd := &MsgExecuteContract{ - Sender: fred.String(), - Contract: contractBech32Addr, - Msg: []byte(`{"release":{}}`), - Funds: topUp, - } - h = data.msgServiceRouter.Handler(execCmd) - res, err = h(data.ctx, execCmd) - require.NoError(t, err) - // from https://github.com/CosmWasm/cosmwasm/blob/master/contracts/hackatom/src/contract.rs#L167 - assertExecuteResponse(t, res.Data, []byte{0xf0, 0x0b, 0xaa}) - - // this should be standard message event, plus x/wasm init event, plus 2 bank send event, plus a special event from the contract - require.Equal(t, 9, len(res.Events), prettyEvents(res.Events)) - - assert.Equal(t, "coin_spent", res.Events[0].Type) - assert.Equal(t, "coin_received", res.Events[1].Type) - - require.Equal(t, "transfer", res.Events[2].Type) - require.Len(t, res.Events[2].Attributes, 3) - assertAttribute(t, "recipient", contractBech32Addr, res.Events[2].Attributes[0]) - assertAttribute(t, "sender", fred.String(), res.Events[2].Attributes[1]) - assertAttribute(t, "amount", "5000denom", res.Events[2].Attributes[2]) - - assert.Equal(t, "execute", res.Events[3].Type) - - // custom contract event attribute - assert.Equal(t, "wasm", res.Events[4].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[4].Attributes[0]) - assertAttribute(t, "action", "release", res.Events[4].Attributes[1]) - // custom contract event - assert.Equal(t, "wasm-hackatom", res.Events[5].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[5].Attributes[0]) - assertAttribute(t, "action", "release", res.Events[5].Attributes[1]) - // second transfer (this without conflicting message) - assert.Equal(t, "coin_spent", res.Events[6].Type) - assert.Equal(t, "coin_received", res.Events[7].Type) - - assert.Equal(t, "transfer", res.Events[8].Type) - assertAttribute(t, "recipient", bob.String(), res.Events[8].Attributes[0]) - assertAttribute(t, "sender", contractBech32Addr, res.Events[8].Attributes[1]) - assertAttribute(t, "amount", "105000denom", res.Events[8].Attributes[2]) - // finally, standard x/wasm tag - - // ensure bob now exists and got both payments released - bobAcct = data.acctKeeper.GetAccount(data.ctx, bob) - require.NotNil(t, bobAcct) - balance := data.bankKeeper.GetAllBalances(data.ctx, bobAcct.GetAddress()) - assert.Equal(t, deposit.Add(topUp...), balance) - - // ensure contract has updated balance - contractAcct = data.acctKeeper.GetAccount(data.ctx, contractAddr) - require.NotNil(t, contractAcct) - assert.Equal(t, sdk.Coins{}, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) - - // ensure all contract state is as after init - assertCodeList(t, q, data.ctx, 1, data.encConf.Marshaler) - assertCodeBytes(t, q, data.ctx, 1, testContract, data.encConf.Marshaler) - - assertContractList(t, q, data.ctx, 1, []string{contractBech32Addr}, data.encConf.Marshaler) - assertContractInfo(t, q, data.ctx, contractBech32Addr, 1, creator, data.encConf.Marshaler) - assertContractState(t, q, data.ctx, contractBech32Addr, state{ - Verifier: fred.String(), - Beneficiary: bob.String(), - Funder: creator.String(), - }, data.encConf.Marshaler) -} - -func TestHandleExecuteEscrow(t *testing.T) { - data := setupTest(t) - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := sdk.AccAddress(bytes.Repeat([]byte{1}, address.Len)) - data.faucet.Fund(data.ctx, creator, sdk.NewInt64Coin("denom", 100000)) - fred := data.faucet.NewFundedRandomAccount(data.ctx, topUp...) - - msg := &MsgStoreCode{ - Sender: creator.String(), - WASMByteCode: testContract, - } - - h := data.msgServiceRouter.Handler(msg) - _, err := h(data.ctx, msg) - require.NoError(t, err) - - bob := keyPubAddr() - initMsg := map[string]interface{}{ - "verifier": fred.String(), - "beneficiary": bob.String(), - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - initCmd := MsgInstantiateContract{ - Sender: creator.String(), - CodeID: firstCodeID, - Msg: initMsgBz, - Funds: deposit, - Label: "testing", - } - h = data.msgServiceRouter.Handler(&initCmd) - res, err := h(data.ctx, &initCmd) - require.NoError(t, err) - contractBech32Addr := parseInitResponse(t, res.Data) - require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", contractBech32Addr) - - handleMsg := map[string]interface{}{ - "release": map[string]interface{}{}, - } - handleMsgBz, err := json.Marshal(handleMsg) - require.NoError(t, err) - - execCmd := MsgExecuteContract{ - Sender: fred.String(), - Contract: contractBech32Addr, - Msg: handleMsgBz, - Funds: topUp, - } - h = data.msgServiceRouter.Handler(&execCmd) - res, err = h(data.ctx, &execCmd) - require.NoError(t, err) - // from https://github.com/CosmWasm/cosmwasm/blob/master/contracts/hackatom/src/contract.rs#L167 - assertExecuteResponse(t, res.Data, []byte{0xf0, 0x0b, 0xaa}) - - // ensure bob now exists and got both payments released - bobAcct := data.acctKeeper.GetAccount(data.ctx, bob) - require.NotNil(t, bobAcct) - balance := data.bankKeeper.GetAllBalances(data.ctx, bobAcct.GetAddress()) - assert.Equal(t, deposit.Add(topUp...), balance) - - // ensure contract has updated balance - contractAddr, _ := sdk.AccAddressFromBech32(contractBech32Addr) - contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) - require.NotNil(t, contractAcct) - assert.Equal(t, sdk.Coins{}, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) -} - -func TestReadWasmConfig(t *testing.T) { - withViper := func(s string) *viper.Viper { - v := viper.New() - v.SetConfigType("toml") - require.NoError(t, v.ReadConfig(strings.NewReader(s))) - return v - } - var one uint64 = 1 - defaults := DefaultWasmConfig() - - specs := map[string]struct { - src servertypes.AppOptions - exp types.WasmConfig - }{ - "set query gas limit via opts": { - src: AppOptionsMock{ - "wasm.query_gas_limit": 1, - }, - exp: types.WasmConfig{ - SmartQueryGasLimit: 1, - MemoryCacheSize: defaults.MemoryCacheSize, - }, - }, - "set cache via opts": { - src: AppOptionsMock{ - "wasm.memory_cache_size": 2, - }, - exp: types.WasmConfig{ - MemoryCacheSize: 2, - SmartQueryGasLimit: defaults.SmartQueryGasLimit, - }, - }, - "set debug via opts": { - src: AppOptionsMock{ - "trace": true, - }, - exp: types.WasmConfig{ - SmartQueryGasLimit: defaults.SmartQueryGasLimit, - MemoryCacheSize: defaults.MemoryCacheSize, - ContractDebugMode: true, - }, - }, - "all defaults when no options set": { - src: AppOptionsMock{}, - exp: defaults, - }, - "default config template values": { - src: withViper(types.DefaultConfigTemplate()), - exp: defaults, - }, - "custom config template values": { - src: withViper(types.ConfigTemplate(types.WasmConfig{ - SimulationGasLimit: &one, - SmartQueryGasLimit: 2, - MemoryCacheSize: 3, - })), - exp: types.WasmConfig{ - SimulationGasLimit: &one, - SmartQueryGasLimit: 2, - MemoryCacheSize: 3, - ContractDebugMode: false, - }, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := ReadWasmConfig(spec.src) - require.NoError(t, err) - assert.Equal(t, spec.exp, got) - }) - } -} - -type AppOptionsMock map[string]interface{} - -func (a AppOptionsMock) Get(s string) interface{} { - return a[s] -} - -type prettyEvent struct { - Type string - Attr []sdk.Attribute -} - -func prettyEvents(evts []abci.Event) string { - res := make([]prettyEvent, len(evts)) - for i, e := range evts { - res[i] = prettyEvent{ - Type: e.Type, - Attr: prettyAttrs(e.Attributes), - } - } - bz, err := json.MarshalIndent(res, "", " ") - if err != nil { - panic(err) - } - return string(bz) -} - -func prettyAttrs(attrs []abci.EventAttribute) []sdk.Attribute { - pretty := make([]sdk.Attribute, len(attrs)) - for i, a := range attrs { - pretty[i] = prettyAttr(a) - } - return pretty -} - -func prettyAttr(attr abci.EventAttribute) sdk.Attribute { - return sdk.NewAttribute(attr.Key, attr.Value) -} - -func assertAttribute(t *testing.T, key string, value string, attr abci.EventAttribute) { - t.Helper() - assert.Equal(t, key, attr.Key, prettyAttr(attr)) - assert.Equal(t, value, attr.Value, prettyAttr(attr)) -} - -func assertCodeList(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, expectedNum int, marshaler codec.Codec) { - t.Helper() - path := "/cosmwasm.wasm.v1.Query/Codes" - resp, sdkerr := q.Route(path)(ctx, abci.RequestQuery{Path: path}) - require.NoError(t, sdkerr) - require.True(t, resp.IsOK()) - - bz := resp.Value - if len(bz) == 0 { - require.Equal(t, expectedNum, 0) - return - } - - var res types.QueryCodesResponse - require.NoError(t, marshaler.Unmarshal(bz, &res)) - assert.Equal(t, expectedNum, len(res.CodeInfos)) -} - -func assertCodeBytes(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, codeID uint64, expectedBytes []byte, marshaler codec.Codec) { //nolint:unparam - t.Helper() - bz, err := marshaler.Marshal(&types.QueryCodeRequest{CodeId: codeID}) - require.NoError(t, err) - - path := "/cosmwasm.wasm.v1.Query/Code" - resp, err := q.Route(path)(ctx, abci.RequestQuery{Path: path, Data: bz}) - if len(expectedBytes) == 0 { - assert.ErrorIs(t, err, types.ErrNotFound) - return - } - require.NoError(t, err) - require.True(t, resp.IsOK()) - bz = resp.Value - - var rsp types.QueryCodeResponse - require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - assert.Equal(t, expectedBytes, rsp.Data) -} - -func assertContractList(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, codeID uint64, expContractAddrs []string, marshaler codec.Codec) { //nolint:unparam - t.Helper() - bz, err := marshaler.Marshal(&types.QueryContractsByCodeRequest{CodeId: codeID}) - require.NoError(t, err) - - path := "/cosmwasm.wasm.v1.Query/ContractsByCode" - resp, sdkerr := q.Route(path)(ctx, abci.RequestQuery{Path: path, Data: bz}) - if len(expContractAddrs) == 0 { - assert.ErrorIs(t, err, types.ErrNotFound) - return - } - require.NoError(t, sdkerr) - require.True(t, resp.IsOK()) - bz = resp.Value - - var rsp types.QueryContractsByCodeResponse - require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - - hasAddrs := make([]string, len(rsp.Contracts)) - for i, r := range rsp.Contracts { //nolint:gosimple - hasAddrs[i] = r - } - assert.Equal(t, expContractAddrs, hasAddrs) -} - -func assertContractState(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, contractBech32Addr string, expected state, marshaler codec.Codec) { - t.Helper() - bz, err := marshaler.Marshal(&types.QueryRawContractStateRequest{Address: contractBech32Addr, QueryData: []byte("config")}) - require.NoError(t, err) - - path := "/cosmwasm.wasm.v1.Query/RawContractState" - resp, sdkerr := q.Route(path)(ctx, abci.RequestQuery{Path: path, Data: bz}) - require.NoError(t, sdkerr) - require.True(t, resp.IsOK()) - bz = resp.Value - - var rsp types.QueryRawContractStateResponse - require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - expectedBz, err := json.Marshal(expected) - require.NoError(t, err) - assert.Equal(t, expectedBz, rsp.Data) -} - -func assertContractInfo(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, contractBech32Addr string, codeID uint64, creator sdk.AccAddress, marshaler codec.Codec) { //nolint:unparam - t.Helper() - bz, err := marshaler.Marshal(&types.QueryContractInfoRequest{Address: contractBech32Addr}) - require.NoError(t, err) - - path := "/cosmwasm.wasm.v1.Query/ContractInfo" - resp, sdkerr := q.Route(path)(ctx, abci.RequestQuery{Path: path, Data: bz}) - require.NoError(t, sdkerr) - require.True(t, resp.IsOK()) - bz = resp.Value - - var rsp types.QueryContractInfoResponse - require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - - assert.Equal(t, codeID, rsp.CodeID) - assert.Equal(t, creator.String(), rsp.Creator) -} diff --git a/x/wasm/relay_pingpong_test.go b/x/wasm/relay_pingpong_test.go deleted file mode 100644 index 932bebb..0000000 --- a/x/wasm/relay_pingpong_test.go +++ /dev/null @@ -1,381 +0,0 @@ -package wasm_test - -import ( - "encoding/json" - "fmt" - "testing" - - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - ping = "ping" - pong = "pong" -) - -var doNotTimeout = clienttypes.NewHeight(1, 1111111) - -func TestPinPong(t *testing.T) { - // custom IBC protocol example - // scenario: given two chains, - // with a contract on chain A and chain B - // when a ibc packet comes in, the contract responds with a new packet containing - // either ping or pong - - pingContract := &player{t: t, actor: ping} - pongContract := &player{t: t, actor: pong} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(pingContract)), - } - chainBOpts = []wasmkeeper.Option{wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(pongContract), - )} - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts, chainBOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - _ = chainB.SeedNewContractInstance() // skip 1 instance so that addresses are not the same - var ( - pingContractAddr = chainA.SeedNewContractInstance() - pongContractAddr = chainB.SeedNewContractInstance() - ) - require.NotEqual(t, pingContractAddr, pongContractAddr) - coordinator.CommitBlock(chainA, chainB) - - pingContract.chain = chainA - pingContract.contractAddr = pingContractAddr - - pongContract.chain = chainB - pongContract.contractAddr = pongContractAddr - - var ( - sourcePortID = wasmkeeper.PortIDForContract(pingContractAddr) - counterpartyPortID = wasmkeeper.PortIDForContract(pongContractAddr) - ) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: sourcePortID, - Version: ibctransfertypes.Version, - Order: channeltypes.ORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: counterpartyPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.ORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // trigger start game via execute - const startValue uint64 = 100 - const rounds = 3 - s := startGame{ - ChannelID: path.EndpointA.ChannelID, - Value: startValue, - } - startMsg := &wasmtypes.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: pingContractAddr.String(), - Msg: s.GetBytes(), - } - // on chain A - _, err := path.EndpointA.Chain.SendMsgs(startMsg) - require.NoError(t, err) - - // when some rounds are played - for i := 1; i <= rounds; i++ { - t.Logf("++ round: %d\n", i) - - require.Len(t, chainA.PendingSendPackets, 1) - err := coordinator.RelayAndAckPendingPackets(path) - require.NoError(t, err) - } - - // then receive/response state is as expected - assert.Equal(t, startValue+rounds, pingContract.QueryState(lastBallSentKey)) - assert.Equal(t, uint64(rounds), pingContract.QueryState(lastBallReceivedKey)) - assert.Equal(t, uint64(rounds+1), pingContract.QueryState(sentBallsCountKey)) - assert.Equal(t, uint64(rounds), pingContract.QueryState(receivedBallsCountKey)) - assert.Equal(t, uint64(rounds), pingContract.QueryState(confirmedBallsCountKey)) - - assert.Equal(t, uint64(rounds), pongContract.QueryState(lastBallSentKey)) - assert.Equal(t, startValue+rounds-1, pongContract.QueryState(lastBallReceivedKey)) - assert.Equal(t, uint64(rounds), pongContract.QueryState(sentBallsCountKey)) - assert.Equal(t, uint64(rounds), pongContract.QueryState(receivedBallsCountKey)) - assert.Equal(t, uint64(rounds), pongContract.QueryState(confirmedBallsCountKey)) -} - -var _ wasmtesting.IBCContractCallbacks = &player{} - -// player is a (mock) contract that sends and receives ibc packages -type player struct { - t *testing.T - chain *wasmibctesting.TestChain - contractAddr sdk.AccAddress - actor string // either ping or pong - execCalls int // number of calls to Execute method (checkTx + deliverTx) -} - -// Execute starts the ping pong game -// Contracts finds all connected channels and broadcasts a ping message -func (p *player) Execute(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.MessageInfo, executeMsg []byte, store wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - p.execCalls++ - // start game - var start startGame - if err := json.Unmarshal(executeMsg, &start); err != nil { - return nil, 0, err - } - - if start.MaxValue != 0 { - store.Set(maxValueKey, sdk.Uint64ToBigEndian(start.MaxValue)) - } - service := NewHit(p.actor, start.Value) - p.t.Logf("[%s] starting game with: %d: %v\n", p.actor, start.Value, service) - - p.incrementCounter(sentBallsCountKey, store) - store.Set(lastBallSentKey, sdk.Uint64ToBigEndian(start.Value)) - return &wasmvmtypes.Response{ - Messages: []wasmvmtypes.SubMsg{ - { - Msg: wasmvmtypes.CosmosMsg{ - IBC: &wasmvmtypes.IBCMsg{ - SendPacket: &wasmvmtypes.SendPacketMsg{ - ChannelID: start.ChannelID, - Data: service.GetBytes(), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{ - Revision: doNotTimeout.RevisionNumber, - Height: doNotTimeout.RevisionHeight, - }}, - }, - }, - }, - ReplyOn: wasmvmtypes.ReplyNever, - }, - }, - }, 0, nil -} - -// OnIBCChannelOpen ensures to accept only configured version -func (p player) IBCChannelOpen(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCChannelOpenMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - if msg.GetChannel().Version != p.actor { - return &wasmvmtypes.IBC3ChannelOpenResponse{}, 0, nil - } - return &wasmvmtypes.IBC3ChannelOpenResponse{}, 0, nil -} - -// OnIBCChannelConnect persists connection endpoints -func (p player) IBCChannelConnect(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCChannelConnectMsg, store wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - p.storeEndpoint(store, msg.GetChannel()) - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -// connectedChannelsModel is a simple persistence model to store endpoint addresses within the contract's store -type connectedChannelsModel struct { - Our wasmvmtypes.IBCEndpoint - Their wasmvmtypes.IBCEndpoint -} - -var ( // store keys - ibcEndpointsKey = []byte("ibc-endpoints") - maxValueKey = []byte("max-value") -) - -func (p player) storeEndpoint(store wasmvm.KVStore, channel wasmvmtypes.IBCChannel) { - var counterparties []connectedChannelsModel - if b := store.Get(ibcEndpointsKey); b != nil { - require.NoError(p.t, json.Unmarshal(b, &counterparties)) - } - counterparties = append(counterparties, connectedChannelsModel{Our: channel.Endpoint, Their: channel.CounterpartyEndpoint}) - bz, err := json.Marshal(&counterparties) - require.NoError(p.t, err) - store.Set(ibcEndpointsKey, bz) -} - -func (p player) IBCChannelClose(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelCloseMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - panic("implement me") -} - -var ( // store keys - lastBallSentKey = []byte("lastBallSent") - lastBallReceivedKey = []byte("lastBallReceived") - sentBallsCountKey = []byte("sentBalls") - receivedBallsCountKey = []byte("recvBalls") - confirmedBallsCountKey = []byte("confBalls") -) - -// IBCPacketReceive receives the hit and serves a response hit via `wasmvmtypes.IBCPacket` -func (p player) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, store wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - // parse received data and store - packet := msg.Packet - var receivedBall hit - if err := json.Unmarshal(packet.Data, &receivedBall); err != nil { - return &wasmvmtypes.IBCReceiveResult{ - Ok: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: hitAcknowledgement{Error: err.Error()}.GetBytes(), - }, - // no hit msg, we stop the game - }, 0, nil - } - p.incrementCounter(receivedBallsCountKey, store) - - otherCount := receivedBall[counterParty(p.actor)] - store.Set(lastBallReceivedKey, sdk.Uint64ToBigEndian(otherCount)) - - if maxVal := store.Get(maxValueKey); maxVal != nil && otherCount > sdk.BigEndianToUint64(maxVal) { - errMsg := fmt.Sprintf("max value exceeded: %d got %d", sdk.BigEndianToUint64(maxVal), otherCount) - return &wasmvmtypes.IBCReceiveResult{Ok: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: receivedBall.BuildError(errMsg).GetBytes(), - }}, 0, nil - } - - nextValue := p.incrementCounter(lastBallSentKey, store) - newHit := NewHit(p.actor, nextValue) - respHit := &wasmvmtypes.IBCMsg{SendPacket: &wasmvmtypes.SendPacketMsg{ - ChannelID: packet.Src.ChannelID, - Data: newHit.GetBytes(), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{ - Revision: doNotTimeout.RevisionNumber, - Height: doNotTimeout.RevisionHeight, - }}, - }} - p.incrementCounter(sentBallsCountKey, store) - p.t.Logf("[%s] received %d, returning %d: %v\n", p.actor, otherCount, nextValue, newHit) - - return &wasmvmtypes.IBCReceiveResult{ - Ok: &wasmvmtypes.IBCReceiveResponse{ - Acknowledgement: receivedBall.BuildAck().GetBytes(), - Messages: []wasmvmtypes.SubMsg{{Msg: wasmvmtypes.CosmosMsg{IBC: respHit}, ReplyOn: wasmvmtypes.ReplyNever}}, - }, - }, 0, nil -} - -// OnIBCPacketAcknowledgement handles the packet acknowledgment frame. Stops the game on an any error -func (p player) IBCPacketAck(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, store wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - // parse received data and store - var sentBall hit - if err := json.Unmarshal(msg.OriginalPacket.Data, &sentBall); err != nil { - return nil, 0, err - } - - var ack hitAcknowledgement - if err := json.Unmarshal(msg.Acknowledgement.Data, &ack); err != nil { - return nil, 0, err - } - if ack.Success != nil { - confirmedCount := sentBall[p.actor] - p.t.Logf("[%s] acknowledged %d: %v\n", p.actor, confirmedCount, sentBall) - } else { - p.t.Logf("[%s] received app layer error: %s\n", p.actor, ack.Error) - } - - p.incrementCounter(confirmedBallsCountKey, store) - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -func (p player) IBCPacketTimeout(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCPacketTimeoutMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - panic("implement me") -} - -func (p player) incrementCounter(key []byte, store wasmvm.KVStore) uint64 { - var count uint64 - bz := store.Get(key) - if bz != nil { - count = sdk.BigEndianToUint64(bz) - } - count++ - store.Set(key, sdk.Uint64ToBigEndian(count)) - return count -} - -func (p player) QueryState(key []byte) uint64 { - raw := p.chain.App.WasmKeeper.QueryRaw(p.chain.GetContext(), p.contractAddr, key) - return sdk.BigEndianToUint64(raw) -} - -func counterParty(s string) string { - switch s { - case ping: - return pong - case pong: - return ping - default: - panic(fmt.Sprintf("unsupported: %q", s)) - } -} - -// hit is ibc packet payload -type hit map[string]uint64 - -func NewHit(player string, count uint64) hit { - return map[string]uint64{ - player: count, - } -} - -func (h hit) GetBytes() []byte { - b, err := json.Marshal(h) - if err != nil { - panic(err) - } - return b -} - -func (h hit) String() string { - return fmt.Sprintf("Ball %s", string(h.GetBytes())) -} - -func (h hit) BuildAck() hitAcknowledgement { - return hitAcknowledgement{Success: &h} -} - -func (h hit) BuildError(errMsg string) hitAcknowledgement { - return hitAcknowledgement{Error: errMsg} -} - -// hitAcknowledgement is ibc acknowledgment payload -type hitAcknowledgement struct { - Error string `json:"error,omitempty"` - Success *hit `json:"success,omitempty"` -} - -func (a hitAcknowledgement) GetBytes() []byte { - b, err := json.Marshal(a) - if err != nil { - panic(err) - } - return b -} - -// startGame is an execute message payload -type startGame struct { - ChannelID string - Value uint64 - // limit above the game is aborted - MaxValue uint64 `json:"max_value,omitempty"` -} - -func (g startGame) GetBytes() wasmtypes.RawContractMessage { - b, err := json.Marshal(g) - if err != nil { - panic(err) - } - return b -} diff --git a/x/wasm/relay_test.go b/x/wasm/relay_test.go deleted file mode 100644 index 583f506..0000000 --- a/x/wasm/relay_test.go +++ /dev/null @@ -1,824 +0,0 @@ -package wasm_test - -import ( - "encoding/json" - "errors" - "testing" - "time" - - errorsmod "cosmossdk.io/errors" - "cosmossdk.io/math" - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v7/testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - wasmibctesting "github.com/terpnetwork/terp-core/x/wasm/ibctesting" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - wasmtesting "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestFromIBCTransferToContract(t *testing.T) { - // scenario: given two chains, - // with a contract on chain B - // then the contract can handle the receiving side of an ics20 transfer - // that was started on chain A via ibc transfer module - - transferAmount := sdk.NewInt(1) - specs := map[string]struct { - contract wasmtesting.IBCContractCallbacks - setupContract func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) - expChainAPendingSendPackets int - expChainBPendingSendPackets int - expChainABalanceDiff math.Int - expChainBBalanceDiff math.Int - expErr bool - }{ - "ack": { - contract: &ackReceiverContract{}, - setupContract: func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) { - c := contract.(*ackReceiverContract) - c.t = t - c.chain = chain - }, - expChainAPendingSendPackets: 0, - expChainBPendingSendPackets: 0, - expChainABalanceDiff: transferAmount.Neg(), - expChainBBalanceDiff: transferAmount, - }, - "nack": { - contract: &nackReceiverContract{}, - setupContract: func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) { - c := contract.(*nackReceiverContract) - c.t = t - }, - expChainAPendingSendPackets: 0, - expChainBPendingSendPackets: 0, - expChainABalanceDiff: sdk.ZeroInt(), - expChainBBalanceDiff: sdk.ZeroInt(), - }, - "error": { - contract: &errorReceiverContract{}, - setupContract: func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) { - c := contract.(*errorReceiverContract) - c.t = t - }, - expChainAPendingSendPackets: 1, - expChainBPendingSendPackets: 0, - expChainABalanceDiff: transferAmount.Neg(), - expChainBBalanceDiff: sdk.ZeroInt(), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var ( - chainAOpts = []wasmkeeper.Option{wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(spec.contract), - )} - coordinator = wasmibctesting.NewCoordinator(t, 2, []wasmkeeper.Option{}, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - coordinator.CommitBlock(chainA, chainB) - myContractAddr := chainB.SeedNewContractInstance() - contractBPortID := chainB.ContractInfo(myContractAddr).IBCPortID - - spec.setupContract(t, spec.contract, chainB) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: "transfer", - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: contractBPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - originalChainABalance := chainA.Balance(chainA.SenderAccount.GetAddress(), sdk.DefaultBondDenom) - // when transfer via sdk transfer from A (module) -> B (contract) - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, transferAmount) - timeoutHeight := clienttypes.NewHeight(1, 110) - - msg := ibctransfertypes.NewMsgTransfer(path.EndpointA.ChannelConfig.PortID, path.EndpointA.ChannelID, coinToSendToB, chainA.SenderAccount.GetAddress().String(), chainB.SenderAccount.GetAddress().String(), timeoutHeight, 0, "") - _, err := chainA.SendMsgs(msg) - require.NoError(t, err) - require.NoError(t, path.EndpointB.UpdateClient()) - - // then - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and when relay to chain B and handle Ack on chain A - err = coordinator.RelayAndAckPendingPackets(path) - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - - // then - require.Equal(t, spec.expChainAPendingSendPackets, len(chainA.PendingSendPackets)) - require.Equal(t, spec.expChainBPendingSendPackets, len(chainB.PendingSendPackets)) - - // and source chain balance was decreased - newChainABalance := chainA.Balance(chainA.SenderAccount.GetAddress(), sdk.DefaultBondDenom) - assert.Equal(t, originalChainABalance.Amount.Add(spec.expChainABalanceDiff), newChainABalance.Amount) - - // and dest chain balance contains voucher - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, coinToSendToB.Denom, spec.expChainBBalanceDiff) - gotBalance := chainB.Balance(chainB.SenderAccount.GetAddress(), expBalance.Denom) - assert.Equal(t, expBalance, gotBalance, "got total balance: %s", chainB.AllBalances(chainB.SenderAccount.GetAddress())) - }) - } -} - -func TestContractCanInitiateIBCTransferMsg(t *testing.T) { - // scenario: given two chains, - // with a contract on chain A - // then the contract can start an ibc transfer via ibctransfertypes.NewMsgTransfer - // that is handled on chain A by the ibc transfer module and - // received on chain B via ibc transfer module as well - - myContract := &sendViaIBCTransferContract{t: t} - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - myContractAddr := chainA.SeedNewContractInstance() - coordinator.CommitBlock(chainA, chainB) - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // when contract is triggered to send IBCTransferMsg - receiverAddress := chainB.SenderAccount.GetAddress() - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - - // start transfer from chainA to chainB - startMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddr.String(), - Msg: startTransfer{ - ChannelID: path.EndpointA.ChannelID, - CoinsToSend: coinToSendToB, - ReceiverAddr: receiverAddress.String(), - }.GetBytes(), - } - // trigger contract to start the transfer - _, err := chainA.SendMsgs(startMsg) - require.NoError(t, err) - - // then - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and when relay to chain B and handle Ack on chain A - err = coordinator.RelayAndAckPendingPackets(path) - require.NoError(t, err) - - // then - require.Equal(t, 0, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and dest chain balance contains voucher - bankKeeperB := chainB.App.BankKeeper - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, coinToSendToB.Denom, coinToSendToB.Amount) - gotBalance := chainB.Balance(chainB.SenderAccount.GetAddress(), expBalance.Denom) - assert.Equal(t, expBalance, gotBalance, "got total balance: %s", bankKeeperB.GetAllBalances(chainB.GetContext(), chainB.SenderAccount.GetAddress())) -} - -func TestContractCanEmulateIBCTransferMessage(t *testing.T) { - // scenario: given two chains, - // with a contract on chain A - // then the contract can emulate the ibc transfer module in the contract to send an ibc packet - // which is received on chain B via ibc transfer module - - myContract := &sendEmulatedIBCTransferContract{t: t} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - myContractAddr := chainA.SeedNewContractInstance() - myContract.contractAddr = myContractAddr.String() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddr).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // when contract is triggered to send the ibc package to chain B - timeout := uint64(chainB.LastHeader.Header.Time.Add(time.Hour).UnixNano()) // enough time to not timeout - receiverAddress := chainB.SenderAccount.GetAddress() - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - - // start transfer from chainA to chainB - startMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddr.String(), - Msg: startTransfer{ - ChannelID: path.EndpointA.ChannelID, - CoinsToSend: coinToSendToB, - ReceiverAddr: receiverAddress.String(), - ContractIBCPort: chainA.ContractInfo(myContractAddr).IBCPortID, - Timeout: timeout, - }.GetBytes(), - Funds: sdk.NewCoins(coinToSendToB), - } - _, err := chainA.SendMsgs(startMsg) - require.NoError(t, err) - - // then - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and when relay to chain B and handle Ack on chain A - err = coordinator.RelayAndAckPendingPackets(path) - require.NoError(t, err) - - // then - require.Equal(t, 0, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and dest chain balance contains voucher - bankKeeperB := chainB.App.BankKeeper - expBalance := ibctransfertypes.GetTransferCoin(path.EndpointB.ChannelConfig.PortID, path.EndpointB.ChannelID, coinToSendToB.Denom, coinToSendToB.Amount) - gotBalance := chainB.Balance(chainB.SenderAccount.GetAddress(), expBalance.Denom) - assert.Equal(t, expBalance, gotBalance, "got total balance: %s", bankKeeperB.GetAllBalances(chainB.GetContext(), chainB.SenderAccount.GetAddress())) -} - -func TestContractCanEmulateIBCTransferMessageWithTimeout(t *testing.T) { - // scenario: given two chains, - // with a contract on chain A - // then the contract can emulate the ibc transfer module in the contract to send an ibc packet - // which is not received on chain B and times out - - myContract := &sendEmulatedIBCTransferContract{t: t} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContract)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - coordinator.CommitBlock(chainA, chainB) - myContractAddr := chainA.SeedNewContractInstance() - myContract.contractAddr = myContractAddr.String() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddr).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - coordinator.UpdateTime() - - // when contract is triggered to send the ibc package to chain B - timeout := uint64(chainB.LastHeader.Header.Time.Add(time.Nanosecond).UnixNano()) // will timeout - receiverAddress := chainB.SenderAccount.GetAddress() - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - initialContractBalance := chainA.Balance(myContractAddr, sdk.DefaultBondDenom) - initialSenderBalance := chainA.Balance(chainA.SenderAccount.GetAddress(), sdk.DefaultBondDenom) - - // custom payload data to be transferred into a proper ICS20 ibc packet - startMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddr.String(), - Msg: startTransfer{ - ChannelID: path.EndpointA.ChannelID, - CoinsToSend: coinToSendToB, - ReceiverAddr: receiverAddress.String(), - ContractIBCPort: chainA.ContractInfo(myContractAddr).IBCPortID, - Timeout: timeout, - }.GetBytes(), - Funds: sdk.NewCoins(coinToSendToB), - } - _, err := chainA.SendMsgs(startMsg) - require.NoError(t, err) - coordinator.CommitBlock(chainA, chainB) - // then - require.Equal(t, 1, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - newContractBalance := chainA.Balance(myContractAddr, sdk.DefaultBondDenom) - assert.Equal(t, initialContractBalance.Add(coinToSendToB), newContractBalance) // hold in escrow - - // when timeout packet send (by the relayer) - err = coordinator.TimeoutPendingPackets(path) - require.NoError(t, err) - coordinator.CommitBlock(chainA) - - // then - require.Equal(t, 0, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) - - // and then verify account balances restored - newContractBalance = chainA.Balance(myContractAddr, sdk.DefaultBondDenom) - assert.Equal(t, initialContractBalance.String(), newContractBalance.String()) - newSenderBalance := chainA.Balance(chainA.SenderAccount.GetAddress(), sdk.DefaultBondDenom) - assert.Equal(t, initialSenderBalance.String(), newSenderBalance.String()) -} - -func TestContractEmulateIBCTransferMessageOnDiffContractIBCChannel(t *testing.T) { - // scenario: given two chains, A and B - // with 2 contract A1 and A2 on chain A - // then the contract A2 try to send an ibc packet via IBC Channel that create by A1 and B - myContractA1 := &sendEmulatedIBCTransferContract{} - myContractA2 := &sendEmulatedIBCTransferContract{} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA1), - ), - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA2), - ), - } - - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - - coordinator.CommitBlock(chainA, chainB) - myContractAddr1 := chainA.SeedNewContractInstance() - myContractA1.contractAddr = myContractAddr1.String() - myContractAddr2 := chainA.SeedNewContractInstance() - myContractA2.contractAddr = myContractAddr2.String() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddr1).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: ibctransfertypes.PortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - // when contract is triggered to send the ibc package to chain B - timeout := uint64(chainB.LastHeader.Header.Time.Add(time.Hour).UnixNano()) // enough time to not timeout - receiverAddress := chainB.SenderAccount.GetAddress() - coinToSendToB := sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100)) - - // start transfer from chainA - A2 to chainB via IBC channel - startMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddr2.String(), - Msg: startTransfer{ - ChannelID: path.EndpointA.ChannelID, - CoinsToSend: coinToSendToB, - ReceiverAddr: receiverAddress.String(), - Timeout: timeout, - }.GetBytes(), - Funds: sdk.NewCoins(coinToSendToB), - } - _, err := chainA.SendMsgs(startMsg) - require.Error(t, err) -} - -func TestContractHandlesChannelClose(t *testing.T) { - // scenario: a contract is the sending side of an ics20 transfer but the packet was not received - // on the destination chain within the timeout boundaries - myContractA := &captureCloseContract{} - myContractB := &captureCloseContract{} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA)), - } - chainBOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractB)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts, chainBOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - - coordinator.CommitBlock(chainA, chainB) - myContractAddrA := chainA.SeedNewContractInstance() - _ = chainB.SeedNewContractInstance() // skip one instance - myContractAddrB := chainB.SeedNewContractInstance() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddrA).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainB.ContractInfo(myContractAddrB).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - coordinator.CloseChannel(path) - assert.True(t, myContractB.closeCalled) -} - -func TestContractHandlesChannelCloseNotOwned(t *testing.T) { - // scenario: given two chains, - // with a contract A1, A2 on chain A, contract B on chain B - // contract A2 try to close ibc channel that create between A1 and B - - myContractA1 := &closeChannelContract{} - myContractA2 := &closeChannelContract{} - myContractB := &closeChannelContract{} - - var ( - chainAOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA1)), - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractA2)), - } - chainBOpts = []wasmkeeper.Option{ - wasmkeeper.WithWasmEngine( - wasmtesting.NewIBCContractMockWasmer(myContractB)), - } - coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts, chainBOpts) - - chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) - ) - - coordinator.CommitBlock(chainA, chainB) - myContractAddrA1 := chainA.SeedNewContractInstance() - myContractAddrA2 := chainA.SeedNewContractInstance() - _ = chainB.SeedNewContractInstance() // skip one instance - _ = chainB.SeedNewContractInstance() // skip one instance - myContractAddrB := chainB.SeedNewContractInstance() - - path := wasmibctesting.NewPath(chainA, chainB) - path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainA.ContractInfo(myContractAddrA1).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: chainB.ContractInfo(myContractAddrB).IBCPortID, - Version: ibctransfertypes.Version, - Order: channeltypes.UNORDERED, - } - coordinator.SetupConnections(path) - coordinator.CreateChannels(path) - - closeIBCChannelMsg := &types.MsgExecuteContract{ - Sender: chainA.SenderAccount.GetAddress().String(), - Contract: myContractAddrA2.String(), - Msg: closeIBCChannel{ - ChannelID: path.EndpointA.ChannelID, - }.GetBytes(), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))), - } - - _, err := chainA.SendMsgs(closeIBCChannelMsg) - require.Error(t, err) -} - -var _ wasmtesting.IBCContractCallbacks = &captureCloseContract{} - -// contract that sets a flag on IBC channel close only. -type captureCloseContract struct { - contractStub - closeCalled bool -} - -func (c *captureCloseContract) IBCChannelClose(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelCloseMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - c.closeCalled = true - return &wasmvmtypes.IBCBasicResponse{}, 1, nil -} - -var _ wasmtesting.IBCContractCallbacks = &sendViaIBCTransferContract{} - -// contract that initiates an ics-20 transfer on execute via sdk message -type sendViaIBCTransferContract struct { - contractStub - t *testing.T -} - -func (s *sendViaIBCTransferContract) Execute(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.MessageInfo, executeMsg []byte, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - var in startTransfer - if err := json.Unmarshal(executeMsg, &in); err != nil { - return nil, 0, err - } - ibcMsg := &wasmvmtypes.IBCMsg{ - Transfer: &wasmvmtypes.TransferMsg{ - ToAddress: in.ReceiverAddr, - Amount: wasmvmtypes.NewCoin(in.CoinsToSend.Amount.Uint64(), in.CoinsToSend.Denom), - ChannelID: in.ChannelID, - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{ - Revision: 1, - Height: 110, - }}, - }, - } - - return &wasmvmtypes.Response{Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{IBC: ibcMsg}}}}, 0, nil -} - -var _ wasmtesting.IBCContractCallbacks = &sendEmulatedIBCTransferContract{} - -// contract that interacts as an ics20 sending side via IBC packets -// It can also handle the timeout. -type sendEmulatedIBCTransferContract struct { - contractStub - t *testing.T - contractAddr string -} - -func (s *sendEmulatedIBCTransferContract) Execute(_ wasmvm.Checksum, _ wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - var in startTransfer - if err := json.Unmarshal(executeMsg, &in); err != nil { - return nil, 0, err - } - require.Len(s.t, info.Funds, 1) - require.Equal(s.t, in.CoinsToSend.Amount.String(), info.Funds[0].Amount) - require.Equal(s.t, in.CoinsToSend.Denom, info.Funds[0].Denom) - dataPacket := ibctransfertypes.NewFungibleTokenPacketData( - in.CoinsToSend.Denom, in.CoinsToSend.Amount.String(), info.Sender, in.ReceiverAddr, "memo", - ) - if err := dataPacket.ValidateBasic(); err != nil { - return nil, 0, err - } - - ibcMsg := &wasmvmtypes.IBCMsg{ - SendPacket: &wasmvmtypes.SendPacketMsg{ - ChannelID: in.ChannelID, - Data: dataPacket.GetBytes(), - Timeout: wasmvmtypes.IBCTimeout{Timestamp: in.Timeout}, - }, - } - return &wasmvmtypes.Response{Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{IBC: ibcMsg}}}}, 0, nil -} - -func (s *sendEmulatedIBCTransferContract) IBCPacketTimeout(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketTimeoutMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - packet := msg.Packet - - var data ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(packet.Data, &data); err != nil { - return nil, 0, err - } - if err := data.ValidateBasic(); err != nil { - return nil, 0, err - } - amount, _ := sdk.NewIntFromString(data.Amount) - - returnTokens := &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: data.Sender, - Amount: wasmvmtypes.Coins{wasmvmtypes.NewCoin(amount.Uint64(), data.Denom)}, - }, - } - - return &wasmvmtypes.IBCBasicResponse{Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{Bank: returnTokens}}}}, 0, nil -} - -var _ wasmtesting.IBCContractCallbacks = &closeChannelContract{} - -type closeChannelContract struct { - contractStub -} - -func (c *closeChannelContract) IBCChannelClose(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelCloseMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - return &wasmvmtypes.IBCBasicResponse{}, 1, nil -} - -func (c *closeChannelContract) Execute(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.MessageInfo, executeMsg []byte, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) { - var in closeIBCChannel - if err := json.Unmarshal(executeMsg, &in); err != nil { - return nil, 0, err - } - ibcMsg := &wasmvmtypes.IBCMsg{ - CloseChannel: &wasmvmtypes.CloseChannelMsg{ - ChannelID: in.ChannelID, - }, - } - - return &wasmvmtypes.Response{Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{IBC: ibcMsg}}}}, 0, nil -} - -type closeIBCChannel struct { - ChannelID string -} - -func (g closeIBCChannel) GetBytes() types.RawContractMessage { - b, err := json.Marshal(g) - if err != nil { - panic(err) - } - return b -} - -// custom contract execute payload -type startTransfer struct { - ChannelID string - CoinsToSend sdk.Coin - ReceiverAddr string - ContractIBCPort string - Timeout uint64 -} - -func (g startTransfer) GetBytes() types.RawContractMessage { - b, err := json.Marshal(g) - if err != nil { - panic(err) - } - return b -} - -var _ wasmtesting.IBCContractCallbacks = &ackReceiverContract{} - -// contract that acts as the receiving side for an ics-20 transfer. -type ackReceiverContract struct { - contractStub - t *testing.T - chain *wasmibctesting.TestChain -} - -func (c *ackReceiverContract) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - packet := msg.Packet - - var src ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(packet.Data, &src); err != nil { - return nil, 0, err - } - require.NoError(c.t, src.ValidateBasic()) - - // call original ibctransfer keeper to not copy all code into this - ibcPacket := toIBCPacket(packet) - ctx := c.chain.GetContext() // HACK: please note that this is not reverted after checkTX - err := c.chain.App.TransferKeeper.OnRecvPacket(ctx, ibcPacket, src) - if err != nil { - return nil, 0, errorsmod.Wrap(err, "within our smart contract") - } - - var log []wasmvmtypes.EventAttribute // note: all events are under `wasm` event type - ack := channeltypes.NewResultAcknowledgement([]byte{byte(1)}).Acknowledgement() - return &wasmvmtypes.IBCReceiveResult{Ok: &wasmvmtypes.IBCReceiveResponse{Acknowledgement: ack, Attributes: log}}, 0, nil -} - -func (c *ackReceiverContract) IBCPacketAck(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketAckMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - var data ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(msg.OriginalPacket.Data, &data); err != nil { - return nil, 0, err - } - // call original ibctransfer keeper to not copy all code into this - - var ack channeltypes.Acknowledgement - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(msg.Acknowledgement.Data, &ack); err != nil { - return nil, 0, err - } - - // call original ibctransfer keeper to not copy all code into this - ctx := c.chain.GetContext() // HACK: please note that this is not reverted after checkTX - ibcPacket := toIBCPacket(msg.OriginalPacket) - err := c.chain.App.TransferKeeper.OnAcknowledgementPacket(ctx, ibcPacket, data, ack) - if err != nil { - return nil, 0, errorsmod.Wrap(err, "within our smart contract") - } - - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -// contract that acts as the receiving side for an ics-20 transfer and always returns a nack. -type nackReceiverContract struct { - contractStub - t *testing.T -} - -func (c *nackReceiverContract) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - packet := msg.Packet - - var src ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(packet.Data, &src); err != nil { - return nil, 0, err - } - require.NoError(c.t, src.ValidateBasic()) - return &wasmvmtypes.IBCReceiveResult{Err: "nack-testing"}, 0, nil -} - -// contract that acts as the receiving side for an ics-20 transfer and always returns an error. -type errorReceiverContract struct { - contractStub - t *testing.T -} - -func (c *errorReceiverContract) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, msg wasmvmtypes.IBCPacketReceiveMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - packet := msg.Packet - - var src ibctransfertypes.FungibleTokenPacketData - if err := ibctransfertypes.ModuleCdc.UnmarshalJSON(packet.Data, &src); err != nil { - return nil, 0, err - } - require.NoError(c.t, src.ValidateBasic()) - return nil, 0, errors.New("error-testing") -} - -// simple helper struct that implements connection setup methods. -type contractStub struct{} - -func (s *contractStub) IBCChannelOpen(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelOpenMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) { - return &wasmvmtypes.IBC3ChannelOpenResponse{}, 0, nil -} - -func (s *contractStub) IBCChannelConnect(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelConnectMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -func (s *contractStub) IBCChannelClose(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCChannelCloseMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - panic("implement me") -} - -func (s *contractStub) IBCPacketReceive(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCPacketReceiveMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCReceiveResult, uint64, error) { - panic("implement me") -} - -func (s *contractStub) IBCPacketAck(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCPacketAckMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - return &wasmvmtypes.IBCBasicResponse{}, 0, nil -} - -func (s *contractStub) IBCPacketTimeout(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ wasmvmtypes.IBCPacketTimeoutMsg, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.IBCBasicResponse, uint64, error) { - panic("implement me") -} - -func toIBCPacket(p wasmvmtypes.IBCPacket) channeltypes.Packet { - var height clienttypes.Height - if p.Timeout.Block != nil { - height = clienttypes.NewHeight(p.Timeout.Block.Revision, p.Timeout.Block.Height) - } - return channeltypes.Packet{ - Sequence: p.Sequence, - SourcePort: p.Src.PortID, - SourceChannel: p.Src.ChannelID, - DestinationPort: p.Dest.PortID, - DestinationChannel: p.Dest.ChannelID, - Data: p.Data, - TimeoutHeight: height, - TimeoutTimestamp: p.Timeout.Timestamp, - } -} diff --git a/x/wasm/simulation/genesis.go b/x/wasm/simulation/genesis.go deleted file mode 100644 index 47a18ca..0000000 --- a/x/wasm/simulation/genesis.go +++ /dev/null @@ -1,27 +0,0 @@ -package simulation - -import ( - "github.com/cosmos/cosmos-sdk/types/module" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// RandomizeGenState generates a random GenesisState for wasm -func RandomizedGenState(simstate *module.SimulationState) { - params := types.DefaultParams() - wasmGenesis := types.GenesisState{ - Params: params, - Codes: nil, - Contracts: nil, - Sequences: []types.Sequence{ - {IDKey: types.KeyLastCodeID, Value: simstate.Rand.Uint64()}, - }, - } - - _, err := simstate.Cdc.MarshalJSON(&wasmGenesis) - if err != nil { - panic(err) - } - - simstate.GenState[types.ModuleName] = simstate.Cdc.MustMarshalJSON(&wasmGenesis) -} diff --git a/x/wasm/simulation/operations.go b/x/wasm/simulation/operations.go deleted file mode 100644 index 5ff14e4..0000000 --- a/x/wasm/simulation/operations.go +++ /dev/null @@ -1,566 +0,0 @@ -package simulation - -import ( - "encoding/json" - "math/rand" - "os" - - errorsmod "cosmossdk.io/errors" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/auth/tx" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/terpnetwork/terp-core/app/params" - wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -// Simulation operation weights constants -// -//nolint:gosec -const ( - OpWeightMsgStoreCode = "op_weight_msg_store_code" - OpWeightMsgInstantiateContract = "op_weight_msg_instantiate_contract" - OpWeightMsgExecuteContract = "op_weight_msg_execute_contract" - OpWeightMsgUpdateAdmin = "op_weight_msg_update_admin" - OpWeightMsgClearAdmin = "op_weight_msg_clear_admin" - OpWeightMsgMigrateContract = "op_weight_msg_migrate_contract" - OpReflectContractPath = "op_reflect_contract_path" -) - -// WasmKeeper is a subset of the wasm keeper used by simulations -type WasmKeeper interface { - GetAuthority() string - GetParams(ctx sdk.Context) types.Params - IterateCodeInfos(ctx sdk.Context, cb func(uint64, types.CodeInfo) bool) - IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, types.ContractInfo) bool) - QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) - PeekAutoIncrementID(ctx sdk.Context, lastIDKey []byte) uint64 -} -type BankKeeper interface { - simulation.BankKeeper - IsSendEnabledCoin(ctx sdk.Context, coin sdk.Coin) bool -} - -// WeightedOperations returns all the operations from the module with their respective weights -func WeightedOperations( - simstate *module.SimulationState, - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, -) simulation.WeightedOperations { - var ( - weightMsgStoreCode int - weightMsgInstantiateContract int - weightMsgExecuteContract int - weightMsgUpdateAdmin int - weightMsgClearAdmin int - weightMsgMigrateContract int - wasmContractPath string - ) - - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgStoreCode, &weightMsgStoreCode, nil, - func(_ *rand.Rand) { - weightMsgStoreCode = params.DefaultWeightMsgStoreCode - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgInstantiateContract, &weightMsgInstantiateContract, nil, - func(_ *rand.Rand) { - weightMsgInstantiateContract = params.DefaultWeightMsgInstantiateContract - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgExecuteContract, &weightMsgInstantiateContract, nil, - func(_ *rand.Rand) { - weightMsgExecuteContract = params.DefaultWeightMsgExecuteContract - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgUpdateAdmin, &weightMsgUpdateAdmin, nil, - func(_ *rand.Rand) { - weightMsgUpdateAdmin = params.DefaultWeightMsgUpdateAdmin - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgClearAdmin, &weightMsgClearAdmin, nil, - func(_ *rand.Rand) { - weightMsgClearAdmin = params.DefaultWeightMsgClearAdmin - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgMigrateContract, &weightMsgMigrateContract, nil, - func(_ *rand.Rand) { - weightMsgMigrateContract = params.DefaultWeightMsgMigrateContract - }, - ) - simstate.AppParams.GetOrGenerate(simstate.Cdc, OpReflectContractPath, &wasmContractPath, nil, - func(_ *rand.Rand) { - wasmContractPath = "" - }, - ) - - var wasmBz []byte - if wasmContractPath == "" { - wasmBz = testdata.MigrateReflectContractWasm() - } else { - var err error - wasmBz, err = os.ReadFile(wasmContractPath) - if err != nil { - panic(err) - } - } - return simulation.WeightedOperations{ - simulation.NewWeightedOperation( - weightMsgStoreCode, - SimulateMsgStoreCode(ak, bk, wasmKeeper, wasmBz), - ), - simulation.NewWeightedOperation( - weightMsgInstantiateContract, - SimulateMsgInstantiateContract(ak, bk, wasmKeeper, DefaultSimulationCodeIDSelector), - ), - simulation.NewWeightedOperation( - weightMsgExecuteContract, - SimulateMsgExecuteContract( - ak, - bk, - wasmKeeper, - DefaultSimulationExecuteContractSelector, - DefaultSimulationExecuteSenderSelector, - DefaultSimulationExecutePayloader, - ), - ), - simulation.NewWeightedOperation( - weightMsgUpdateAdmin, - SimulateMsgUpdateAmin( - ak, - bk, - wasmKeeper, - DefaultSimulationUpdateAdminContractSelector, - ), - ), - simulation.NewWeightedOperation( - weightMsgClearAdmin, - SimulateMsgClearAdmin( - ak, - bk, - wasmKeeper, - DefaultSimulationClearAdminContractSelector, - ), - ), - simulation.NewWeightedOperation( - weightMsgMigrateContract, - SimulateMsgMigrateContract( - ak, - bk, - wasmKeeper, - DefaultSimulationMigrateContractSelector, - DefaultSimulationMigrateCodeIDSelector, - ), - ), - } -} - -type ( - MsgMigrateContractSelector func(sdk.Context, WasmKeeper, string) (sdk.AccAddress, types.ContractInfo) - MsgMigrateCodeIDSelector func(sdk.Context, WasmKeeper, uint64) uint64 -) - -func DefaultSimulationMigrateContractSelector(ctx sdk.Context, wasmKeeper WasmKeeper, adminAddress string) (sdk.AccAddress, types.ContractInfo) { - var contractAddress sdk.AccAddress - var contractInfo types.ContractInfo - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - if info.Admin != adminAddress { - return false - } - contractAddress = address - contractInfo = info - return true - }) - return contractAddress, contractInfo -} - -func DefaultSimulationMigrateCodeIDSelector(ctx sdk.Context, wasmKeeper WasmKeeper, currentCodeID uint64) uint64 { - var codeID uint64 - wasmKeeper.IterateCodeInfos(ctx, func(u uint64, info types.CodeInfo) bool { - if (info.InstantiateConfig.Permission != types.AccessTypeEverybody) || (u == currentCodeID) { - return false - } - codeID = u - return true - }) - return codeID -} - -func SimulateMsgMigrateContract( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgMigrateContractSelector, - codeIDSelector MsgMigrateCodeIDSelector, -) 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) - ctAddress, info := contractSelector(ctx, wasmKeeper, simAccount.Address.String()) - if ctAddress == nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgMigrateContract{}.Type(), "no contract instance available"), nil, nil - } - - codeID := codeIDSelector(ctx, wasmKeeper, info.CodeID) - if codeID == 0 { - return simtypes.NoOpMsg(types.ModuleName, types.MsgMigrateContract{}.Type(), "no target contract available"), nil, nil - } - migrateMsg := types.MsgMigrateContract{ - Sender: simAccount.Address.String(), - Contract: ctAddress.String(), - CodeID: codeID, - Msg: []byte(`{}`), - } - - txCtx := BuildOperationInput(r, app, ctx, &migrateMsg, simAccount, ak, bk, nil) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -type MsgClearAdminContractSelector func(sdk.Context, WasmKeeper, string) sdk.AccAddress - -func DefaultSimulationClearAdminContractSelector(ctx sdk.Context, wasmKeeper WasmKeeper, adminAddress string) sdk.AccAddress { - var ctAddress sdk.AccAddress - wasmKeeper.IterateContractInfo(ctx, func(addr sdk.AccAddress, info types.ContractInfo) bool { - if info.Admin != adminAddress { - return false - } - ctAddress = addr - return true - }) - return ctAddress -} - -func SimulateMsgClearAdmin( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgClearAdminContractSelector, -) simtypes.Operation { - return func( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - accounts []simtypes.Account, - chainID string, - ) (OperationMsg simtypes.OperationMsg, futureOps []simtypes.FutureOperation, err error) { - simAccount, _ := simtypes.RandomAcc(r, accounts) - ctAddress := contractSelector(ctx, wasmKeeper, simAccount.Address.String()) - if ctAddress == nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgClearAdmin{}.Type(), "no contract instance available"), nil, nil - } - - msg := types.MsgClearAdmin{ - Sender: simAccount.Address.String(), - Contract: ctAddress.String(), - } - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, nil) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -type MsgUpdateAdminContractSelector func(sdk.Context, WasmKeeper, string) (sdk.AccAddress, types.ContractInfo) - -// DefaultSimulationUpdateAdminContractSelector picks the first contract which Admin != "" -func DefaultSimulationUpdateAdminContractSelector(ctx sdk.Context, wasmKeeper WasmKeeper, adminAddress string) (sdk.AccAddress, types.ContractInfo) { - var contractAddress sdk.AccAddress - var contractInfo types.ContractInfo - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - if info.Admin != adminAddress { - return false - } - contractAddress = address - contractInfo = info - return true - }) - return contractAddress, contractInfo -} - -func SimulateMsgUpdateAmin( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgUpdateAdminContractSelector, -) 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) - ctAddress, _ := contractSelector(ctx, wasmKeeper, simAccount.Address.String()) - if ctAddress == nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgUpdateAdmin{}.Type(), "no contract instance available"), nil, nil - } - - newAdmin, _ := simtypes.RandomAcc(r, accs) - if newAdmin.Address.String() == simAccount.Address.String() { - return simtypes.NoOpMsg(types.ModuleName, types.MsgUpdateAdmin{}.Type(), "new admin cannot be the same as current admin"), nil, nil - } - - msg := types.MsgUpdateAdmin{ - Sender: simAccount.Address.String(), - NewAdmin: newAdmin.Address.String(), - Contract: ctAddress.String(), - } - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, nil) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -// SimulateMsgStoreCode generates a MsgStoreCode with random values -func SimulateMsgStoreCode( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - wasmBz []byte, -) simtypes.Operation { - return func( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - accs []simtypes.Account, - chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - if wasmKeeper.GetParams(ctx).CodeUploadAccess.Permission != types.AccessTypeEverybody { - return simtypes.NoOpMsg(types.ModuleName, types.MsgStoreCode{}.Type(), "no chain permission"), nil, nil - } - - simAccount, _ := simtypes.RandomAcc(r, accs) - - permission := wasmKeeper.GetParams(ctx).InstantiateDefaultPermission - config := permission.With(simAccount.Address) - - msg := types.MsgStoreCode{ - Sender: simAccount.Address.String(), - WASMByteCode: wasmBz, - InstantiatePermission: &config, - } - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, nil) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -// CodeIDSelector returns code id to be used in simulations -type CodeIDSelector = func(ctx sdk.Context, wasmKeeper WasmKeeper) uint64 - -// DefaultSimulationCodeIDSelector picks the first code id -func DefaultSimulationCodeIDSelector(ctx sdk.Context, wasmKeeper WasmKeeper) uint64 { - var codeID uint64 - wasmKeeper.IterateCodeInfos(ctx, func(u uint64, info types.CodeInfo) bool { - if info.InstantiateConfig.Permission != types.AccessTypeEverybody { - return false - } - codeID = u - return true - }) - return codeID -} - -// SimulateMsgInstantiateContract generates a MsgInstantiateContract with random values -func SimulateMsgInstantiateContract( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - codeSelector CodeIDSelector, -) 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) - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return simtypes.NoOpMsg(types.ModuleName, types.MsgInstantiateContract{}.Type(), "no codes with permission available"), nil, nil - } - deposit := sdk.Coins{} - spendableCoins := bk.SpendableCoins(ctx, simAccount.Address) - for _, v := range spendableCoins { - if bk.IsSendEnabledCoin(ctx, v) { - deposit = deposit.Add(simtypes.RandSubsetCoins(r, sdk.NewCoins(v))...) - } - } - - adminAccount, _ := simtypes.RandomAcc(r, accs) - - msg := types.MsgInstantiateContract{ - Sender: simAccount.Address.String(), - Admin: adminAccount.Address.String(), - CodeID: codeID, - Label: simtypes.RandStringOfLength(r, 10), - Msg: []byte(`{}`), - Funds: deposit, - } - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, deposit) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -// MsgExecuteContractSelector returns contract address to be used in simulations -type MsgExecuteContractSelector = func(ctx sdk.Context, wasmKeeper WasmKeeper) sdk.AccAddress - -// MsgExecutePayloader extension point to modify msg with custom payload -type MsgExecutePayloader func(msg *types.MsgExecuteContract) error - -// MsgExecuteSenderSelector extension point that returns the sender address -type MsgExecuteSenderSelector func(wasmKeeper WasmKeeper, ctx sdk.Context, contractAddr sdk.AccAddress, accs []simtypes.Account) (simtypes.Account, error) - -// SimulateMsgExecuteContract create a execute message a reflect contract instance -func SimulateMsgExecuteContract( - ak types.AccountKeeper, - bk BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgExecuteContractSelector, - senderSelector MsgExecuteSenderSelector, - payloader MsgExecutePayloader, -) simtypes.Operation { - return func( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - accs []simtypes.Account, - chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - contractAddr := contractSelector(ctx, wasmKeeper) - if contractAddr == nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgExecuteContract{}.Type(), "no contract instance available"), nil, nil - } - simAccount, err := senderSelector(wasmKeeper, ctx, contractAddr, accs) - if err != nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgExecuteContract{}.Type(), "query contract owner"), nil, err - } - - deposit := sdk.Coins{} - spendableCoins := bk.SpendableCoins(ctx, simAccount.Address) - for _, v := range spendableCoins { - if bk.IsSendEnabledCoin(ctx, v) { - deposit = deposit.Add(simtypes.RandSubsetCoins(r, sdk.NewCoins(v))...) - } - } - if deposit.IsZero() { - return simtypes.NoOpMsg(types.ModuleName, types.MsgExecuteContract{}.Type(), "broke account"), nil, nil - } - msg := types.MsgExecuteContract{ - Sender: simAccount.Address.String(), - Contract: contractAddr.String(), - Funds: deposit, - } - if err := payloader(&msg); err != nil { - return simtypes.NoOpMsg(types.ModuleName, types.MsgExecuteContract{}.Type(), "contract execute payload"), nil, err - } - - txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, deposit) - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -// BuildOperationInput helper to build object -func BuildOperationInput( - r *rand.Rand, - app *baseapp.BaseApp, - ctx sdk.Context, - msg interface { - sdk.Msg - Type() string - }, - simAccount simtypes.Account, - ak types.AccountKeeper, - bk BankKeeper, - deposit sdk.Coins, -) simulation.OperationInput { - interfaceRegistry := codectypes.NewInterfaceRegistry() - txConfig := tx.NewTxConfig(codec.NewProtoCodec(interfaceRegistry), tx.DefaultSignModes) - return simulation.OperationInput{ - R: r, - App: app, - TxGen: txConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - AccountKeeper: ak, - Bankkeeper: bk, - ModuleName: types.ModuleName, - CoinsSpentInMsg: deposit, - } -} - -// DefaultSimulationExecuteContractSelector picks the first contract address -func DefaultSimulationExecuteContractSelector(ctx sdk.Context, wasmKeeper WasmKeeper) sdk.AccAddress { - var r sdk.AccAddress - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - r = address - return true - }) - return r -} - -// DefaultSimulationExecuteSenderSelector queries reflect contract for owner address and selects accounts -func DefaultSimulationExecuteSenderSelector(wasmKeeper WasmKeeper, ctx sdk.Context, contractAddr sdk.AccAddress, accs []simtypes.Account) (simtypes.Account, error) { - var none simtypes.Account - bz, err := json.Marshal(testdata.ReflectQueryMsg{Owner: &struct{}{}}) - if err != nil { - return none, errorsmod.Wrap(err, "build smart query") - } - got, err := wasmKeeper.QuerySmart(ctx, contractAddr, bz) - if err != nil { - return none, errorsmod.Wrap(err, "exec smart query") - } - var ownerRes testdata.OwnerResponse - if err := json.Unmarshal(got, &ownerRes); err != nil || ownerRes.Owner == "" { - return none, errorsmod.Wrap(err, "parse smart query response") - } - ownerAddr, err := sdk.AccAddressFromBech32(ownerRes.Owner) - if err != nil { - return none, errorsmod.Wrap(err, "parse contract owner address") - } - simAccount, ok := simtypes.FindAccount(accs, ownerAddr) - if !ok { - return none, errorsmod.Wrap(err, "unknown contract owner address") - } - return simAccount, nil -} - -// DefaultSimulationExecutePayloader implements a bank msg to send the -// tokens from contract account back to original sender -func DefaultSimulationExecutePayloader(msg *types.MsgExecuteContract) error { - reflectSend := testdata.ReflectHandleMsg{ - Reflect: &testdata.ReflectPayload{ - Msgs: []wasmvmtypes.CosmosMsg{{ - Bank: &wasmvmtypes.BankMsg{ - Send: &wasmvmtypes.SendMsg{ - ToAddress: msg.Sender, // - Amount: wasmkeeper.ConvertSdkCoinsToWasmCoins(msg.Funds), - }, - }, - }}, - }, - } - reflectSendBz, err := json.Marshal(reflectSend) - if err != nil { - return err - } - msg.Msg = reflectSendBz - return nil -} diff --git a/x/wasm/simulation/proposals.go b/x/wasm/simulation/proposals.go deleted file mode 100644 index 04a4c08..0000000 --- a/x/wasm/simulation/proposals.go +++ /dev/null @@ -1,369 +0,0 @@ -package simulation - -import ( - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/wasm/keeper/testdata" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - WeightStoreCodeProposal = "weight_store_code_proposal" - WeightInstantiateContractProposal = "weight_instantiate_contract_proposal" - WeightUpdateAdminProposal = "weight_update_admin_proposal" - WeightExeContractProposal = "weight_execute_contract_proposal" - WeightClearAdminProposal = "weight_clear_admin_proposal" - WeightMigrateContractProposal = "weight_migrate_contract_proposal" - WeightSudoContractProposal = "weight_sudo_contract_proposal" - WeightPinCodesProposal = "weight_pin_codes_proposal" - WeightUnpinCodesProposal = "weight_unpin_codes_proposal" - WeightUpdateInstantiateConfigProposal = "weight_update_instantiate_config_proposal" - WeightStoreAndInstantiateContractProposal = "weight_store_and_instantiate_contract_proposal" -) - -func ProposalMsgs(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedProposalMsg { - return []simtypes.WeightedProposalMsg{ - simulation.NewWeightedProposalMsg( - WeightInstantiateContractProposal, - params.DefaultWeightInstantiateContractProposal, - SimulateInstantiateContractProposal( - bk, - wasmKeeper, - DefaultSimulationCodeIDSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightUpdateAdminProposal, - params.DefaultWeightUpdateAdminProposal, - SimulateUpdateAdminProposal( - wasmKeeper, - DefaultSimulateUpdateAdminProposalContractSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightExeContractProposal, - params.DefaultWeightExecuteContractProposal, - SimulateExecuteContractProposal( - bk, - wasmKeeper, - DefaultSimulationExecuteContractSelector, - DefaultSimulationExecuteSenderSelector, - DefaultSimulationExecutePayloader, - ), - ), - simulation.NewWeightedProposalMsg( - WeightClearAdminProposal, - params.DefaultWeightClearAdminProposal, - SimulateClearAdminProposal( - wasmKeeper, - DefaultSimulateContractSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightMigrateContractProposal, - params.DefaultWeightMigrateContractProposal, - SimulateMigrateContractProposal( - wasmKeeper, - DefaultSimulateContractSelector, - DefaultSimulationCodeIDSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightPinCodesProposal, - params.DefaultWeightPinCodesProposal, - SimulatePinContractProposal( - wasmKeeper, - DefaultSimulationCodeIDSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightUnpinCodesProposal, - params.DefaultWeightUnpinCodesProposal, - SimulateUnpinContractProposal( - wasmKeeper, - DefaultSimulationCodeIDSelector, - ), - ), - simulation.NewWeightedProposalMsg( - WeightUpdateInstantiateConfigProposal, - params.DefaultWeightUpdateInstantiateConfigProposal, - SimulateUpdateInstantiateConfigProposal( - wasmKeeper, - DefaultSimulationCodeIDSelector, - ), - ), - } -} - -// simulate store code proposal (unused now) -// Current problem: out of gas (defaul gaswanted config of gov SimulateMsgSubmitProposal is 10_000_000) -// but this proposal may need more than it -func SimulateStoreCodeProposal(wasmKeeper WasmKeeper) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - simAccount, _ := simtypes.RandomAcc(r, accs) - - wasmBz := testdata.ReflectContractWasm() - - permission := wasmKeeper.GetParams(ctx).InstantiateDefaultPermission.With(simAccount.Address) - - return &types.MsgStoreCode{ - Sender: authority, - WASMByteCode: wasmBz, - InstantiatePermission: &permission, - } - } -} - -// Simulate instantiate contract proposal -func SimulateInstantiateContractProposal(bk BankKeeper, wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - // admin - adminAccount, _ := simtypes.RandomAcc(r, accs) - // get codeID - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - return &types.MsgInstantiateContract{ - Sender: authority, - Admin: adminAccount.Address.String(), - CodeID: codeID, - Label: simtypes.RandStringOfLength(r, 10), - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - } -} - -// Simulate execute contract proposal -func SimulateExecuteContractProposal( - _ BankKeeper, - wasmKeeper WasmKeeper, - contractSelector MsgExecuteContractSelector, - senderSelector MsgExecuteSenderSelector, - payloader MsgExecutePayloader, -) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - ctAddress := contractSelector(ctx, wasmKeeper) - if ctAddress == nil { - return nil - } - - msg := &types.MsgExecuteContract{ - Sender: authority, - Contract: ctAddress.String(), - Funds: sdk.Coins{}, - } - - if err := payloader(msg); err != nil { - return nil - } - - return msg - } -} - -type UpdateAdminContractSelector func(sdk.Context, WasmKeeper, string) (sdk.AccAddress, types.ContractInfo) - -func DefaultSimulateUpdateAdminProposalContractSelector( - ctx sdk.Context, - wasmKeeper WasmKeeper, - adminAddress string, -) (sdk.AccAddress, types.ContractInfo) { - var contractAddr sdk.AccAddress - var contractInfo types.ContractInfo - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - if info.Admin != adminAddress { - return false - } - contractAddr = address - contractInfo = info - return true - }) - return contractAddr, contractInfo -} - -// Simulate update admin contract proposal -func SimulateUpdateAdminProposal(wasmKeeper WasmKeeper, contractSelector UpdateAdminContractSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - simAccount, _ := simtypes.RandomAcc(r, accs) - ctAddress, _ := contractSelector(ctx, wasmKeeper, simAccount.Address.String()) - if ctAddress == nil { - return nil - } - - return &types.MsgUpdateAdmin{ - Sender: authority, - NewAdmin: simtypes.RandomAccounts(r, 1)[0].Address.String(), - Contract: ctAddress.String(), - } - } -} - -type ClearAdminContractSelector func(sdk.Context, WasmKeeper) sdk.AccAddress - -func DefaultSimulateContractSelector( - ctx sdk.Context, - wasmKeeper WasmKeeper, -) sdk.AccAddress { - var contractAddr sdk.AccAddress - wasmKeeper.IterateContractInfo(ctx, func(address sdk.AccAddress, info types.ContractInfo) bool { - contractAddr = address - return true - }) - return contractAddr -} - -// Simulate clear admin proposal -func SimulateClearAdminProposal(wasmKeeper WasmKeeper, contractSelector ClearAdminContractSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - ctAddress := contractSelector(ctx, wasmKeeper) - if ctAddress == nil { - return nil - } - return &types.MsgClearAdmin{ - Sender: authority, - Contract: ctAddress.String(), - } - } -} - -type MigrateContractProposalContractSelector func(sdk.Context, WasmKeeper) sdk.AccAddress - -// Simulate migrate contract proposal -func SimulateMigrateContractProposal(wasmKeeper WasmKeeper, contractSelector MigrateContractProposalContractSelector, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - ctAddress := contractSelector(ctx, wasmKeeper) - if ctAddress == nil { - return nil - } - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - return &types.MsgMigrateContract{ - Sender: authority, - Contract: ctAddress.String(), - CodeID: codeID, - Msg: []byte(`{}`), - } - } -} - -type SudoContractProposalContractSelector func(sdk.Context, WasmKeeper) sdk.AccAddress - -// Simulate sudo contract proposal -func SimulateSudoContractProposal(wasmKeeper WasmKeeper, contractSelector SudoContractProposalContractSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - ctAddress := contractSelector(ctx, wasmKeeper) - if ctAddress == nil { - return nil - } - - return &types.MsgSudoContract{ - Authority: authority, - Contract: ctAddress.String(), - Msg: []byte(`{}`), - } - } -} - -// Simulate pin contract proposal -func SimulatePinContractProposal(wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - return &types.MsgPinCodes{ - Authority: authority, - CodeIDs: []uint64{codeID}, - } - } -} - -// Simulate unpin contract proposal -func SimulateUnpinContractProposal(wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - return &types.MsgUnpinCodes{ - Authority: authority, - CodeIDs: []uint64{codeID}, - } - } -} - -// Simulate update instantiate config proposal -func SimulateUpdateInstantiateConfigProposal(wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - codeID := codeSelector(ctx, wasmKeeper) - if codeID == 0 { - return nil - } - - simAccount, _ := simtypes.RandomAcc(r, accs) - permission := wasmKeeper.GetParams(ctx).InstantiateDefaultPermission - config := permission.With(simAccount.Address) - - return &types.MsgUpdateInstantiateConfig{ - Sender: authority, - CodeID: codeID, - NewInstantiatePermission: &config, - } - } -} - -func SimulateStoreAndInstantiateContractProposal(wasmKeeper WasmKeeper) simtypes.MsgSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) sdk.Msg { - authority := wasmKeeper.GetAuthority() - - simAccount, _ := simtypes.RandomAcc(r, accs) - adminAccount, _ := simtypes.RandomAcc(r, accs) - - wasmBz := testdata.ReflectContractWasm() - permission := wasmKeeper.GetParams(ctx).InstantiateDefaultPermission.With(simAccount.Address) - - return &types.MsgStoreAndInstantiateContract{ - Authority: authority, - WASMByteCode: wasmBz, - InstantiatePermission: &permission, - UnpinCode: false, - Admin: adminAccount.Address.String(), - Label: simtypes.RandStringOfLength(r, 10), - Msg: []byte(`{}`), - Funds: sdk.Coins{}, - } - } -} diff --git a/x/wasm/testdata/escrow_0.7.wasm b/x/wasm/testdata/escrow_0.7.wasm deleted file mode 100644 index 668aa74..0000000 Binary files a/x/wasm/testdata/escrow_0.7.wasm and /dev/null differ diff --git a/x/wasm/types/ante.go b/x/wasm/types/ante.go deleted file mode 100644 index 4c76efd..0000000 --- a/x/wasm/types/ante.go +++ /dev/null @@ -1,24 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" -) - -type contextKey int - -const ( - // private type creates an interface key for Context that cannot be accessed by any other package - contextKeyTXCount contextKey = iota -) - -// WithTXCounter stores a transaction counter value in the context -func WithTXCounter(ctx sdk.Context, counter uint32) sdk.Context { - return ctx.WithValue(contextKeyTXCount, counter) -} - -// TXCounter returns the tx counter value and found bool from the context. -// The result will be (0, false) for external queries or simulations where no counter available. -func TXCounter(ctx sdk.Context) (uint32, bool) { - val, ok := ctx.Value(contextKeyTXCount).(uint32) - return val, ok -} diff --git a/x/wasm/types/authz.go b/x/wasm/types/authz.go deleted file mode 100644 index 9692088..0000000 --- a/x/wasm/types/authz.go +++ /dev/null @@ -1,533 +0,0 @@ -package types - -import ( - "strings" - - errorsmod "cosmossdk.io/errors" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authztypes "github.com/cosmos/cosmos-sdk/x/authz" - "github.com/cosmos/gogoproto/proto" -) - -const gasDeserializationCostPerByte = uint64(1) - -var ( - _ authztypes.Authorization = &ContractExecutionAuthorization{} - _ authztypes.Authorization = &ContractMigrationAuthorization{} - _ cdctypes.UnpackInterfacesMessage = &ContractExecutionAuthorization{} - _ cdctypes.UnpackInterfacesMessage = &ContractMigrationAuthorization{} -) - -// AuthzableWasmMsg is abstract wasm tx message that is supported in authz -type AuthzableWasmMsg interface { - GetFunds() sdk.Coins - GetMsg() RawContractMessage - GetContract() string - ValidateBasic() error -} - -// NewContractExecutionAuthorization constructor -func NewContractExecutionAuthorization(grants ...ContractGrant) *ContractExecutionAuthorization { - return &ContractExecutionAuthorization{ - Grants: grants, - } -} - -// MsgTypeURL implements Authorization.MsgTypeURL. -func (a ContractExecutionAuthorization) MsgTypeURL() string { - return sdk.MsgTypeURL(&MsgExecuteContract{}) -} - -// NewAuthz factory method to create an Authorization with updated grants -func (a ContractExecutionAuthorization) NewAuthz(g []ContractGrant) authztypes.Authorization { - return NewContractExecutionAuthorization(g...) -} - -// Accept implements Authorization.Accept. -func (a *ContractExecutionAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authztypes.AcceptResponse, error) { - return AcceptGrantedMessage[*MsgExecuteContract](ctx, a.Grants, msg, a) -} - -// ValidateBasic implements Authorization.ValidateBasic. -func (a ContractExecutionAuthorization) ValidateBasic() error { - return validateGrants(a.Grants) -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (a ContractExecutionAuthorization) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { - for _, g := range a.Grants { - if err := g.UnpackInterfaces(unpacker); err != nil { - return err - } - } - return nil -} - -// NewContractMigrationAuthorization constructor -func NewContractMigrationAuthorization(grants ...ContractGrant) *ContractMigrationAuthorization { - return &ContractMigrationAuthorization{ - Grants: grants, - } -} - -// MsgTypeURL implements Authorization.MsgTypeURL. -func (a ContractMigrationAuthorization) MsgTypeURL() string { - return sdk.MsgTypeURL(&MsgMigrateContract{}) -} - -// Accept implements Authorization.Accept. -func (a *ContractMigrationAuthorization) Accept(ctx sdk.Context, msg sdk.Msg) (authztypes.AcceptResponse, error) { - return AcceptGrantedMessage[*MsgMigrateContract](ctx, a.Grants, msg, a) -} - -// NewAuthz factory method to create an Authorization with updated grants -func (a ContractMigrationAuthorization) NewAuthz(g []ContractGrant) authztypes.Authorization { - return NewContractMigrationAuthorization(g...) -} - -// ValidateBasic implements Authorization.ValidateBasic. -func (a ContractMigrationAuthorization) ValidateBasic() error { - return validateGrants(a.Grants) -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (a ContractMigrationAuthorization) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { - for _, g := range a.Grants { - if err := g.UnpackInterfaces(unpacker); err != nil { - return err - } - } - return nil -} - -func validateGrants(g []ContractGrant) error { - if len(g) == 0 { - return ErrEmpty.Wrap("grants") - } - for i, v := range g { - if err := v.ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "position %d", i) - } - } - // allow multiple grants for a contract: - // contractA:doThis:1,doThat:* has with different counters for different methods - return nil -} - -// ContractAuthzFactory factory to create an updated Authorization object -type ContractAuthzFactory interface { - NewAuthz([]ContractGrant) authztypes.Authorization -} - -// AcceptGrantedMessage determines whether this grant permits the provided sdk.Msg to be performed, -// and if so provides an upgraded authorization instance. -func AcceptGrantedMessage[T AuthzableWasmMsg](ctx sdk.Context, grants []ContractGrant, msg sdk.Msg, factory ContractAuthzFactory) (authztypes.AcceptResponse, error) { - exec, ok := msg.(T) - if !ok { - return authztypes.AcceptResponse{}, sdkerrors.ErrInvalidType.Wrap("type mismatch") - } - if exec.GetMsg() == nil { - return authztypes.AcceptResponse{}, sdkerrors.ErrInvalidType.Wrap("empty message") - } - if err := exec.ValidateBasic(); err != nil { - return authztypes.AcceptResponse{}, err - } - - // iterate though all grants - for i, g := range grants { - if g.Contract != exec.GetContract() { - continue - } - - // first check limits - result, err := g.GetLimit().Accept(ctx, exec) - switch { - case err != nil: - return authztypes.AcceptResponse{}, errorsmod.Wrap(err, "limit") - case result == nil: // sanity check - return authztypes.AcceptResponse{}, sdkerrors.ErrInvalidType.Wrap("limit result must not be nil") - case !result.Accepted: - // not applicable, continue with next grant - continue - } - - // then check permission set - ok, err := g.GetFilter().Accept(ctx, exec.GetMsg()) - switch { - case err != nil: - return authztypes.AcceptResponse{}, errorsmod.Wrap(err, "filter") - case !ok: - // no limit update and continue with next grant - continue - } - - // finally do limit state updates in result - switch { - case result.DeleteLimit: - updatedGrants := append(grants[0:i], grants[i+1:]...) //nolint:gocritic - if len(updatedGrants) == 0 { // remove when empty - return authztypes.AcceptResponse{Accept: true, Delete: true}, nil - } - newAuthz := factory.NewAuthz(updatedGrants) - if err := newAuthz.ValidateBasic(); err != nil { // sanity check - return authztypes.AcceptResponse{}, ErrInvalid.Wrapf("new grant state: %s", err) - } - return authztypes.AcceptResponse{Accept: true, Updated: newAuthz}, nil - case result.UpdateLimit != nil: - obj, err := g.WithNewLimits(result.UpdateLimit) - if err != nil { - return authztypes.AcceptResponse{}, err - } - newAuthz := factory.NewAuthz(append(append(grants[0:i], *obj), grants[i+1:]...)) - if err := newAuthz.ValidateBasic(); err != nil { // sanity check - return authztypes.AcceptResponse{}, ErrInvalid.Wrapf("new grant state: %s", err) - } - return authztypes.AcceptResponse{Accept: true, Updated: newAuthz}, nil - default: // accepted without a limit state update - return authztypes.AcceptResponse{Accept: true}, nil - } - } - return authztypes.AcceptResponse{Accept: false}, nil -} - -// ContractAuthzLimitX define execution limits that are enforced and updated when the grant -// is applied. When the limit lapsed the grant is removed. -type ContractAuthzLimitX interface { - Accept(ctx sdk.Context, msg AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) - ValidateBasic() error -} - -// ContractAuthzLimitAcceptResult result of the ContractAuthzLimitX.Accept method -type ContractAuthzLimitAcceptResult struct { - // Accepted is true when limit applies - Accepted bool - // DeleteLimit when set it is the end of life for this limit. Grant is removed from persistent store - DeleteLimit bool - // UpdateLimit update persistent state with new value - UpdateLimit ContractAuthzLimitX -} - -// ContractAuthzFilterX define more fine-grained control on the message payload passed -// to the contract in the operation. When no filter applies on execution, the -// operation is prohibited. -type ContractAuthzFilterX interface { - // Accept returns applicable or error - Accept(ctx sdk.Context, msg RawContractMessage) (bool, error) - ValidateBasic() error -} - -var _ cdctypes.UnpackInterfacesMessage = &ContractGrant{} - -// NewContractGrant constructor -func NewContractGrant(contract sdk.AccAddress, limit ContractAuthzLimitX, filter ContractAuthzFilterX) (*ContractGrant, error) { - pFilter, ok := filter.(proto.Message) - if !ok { - return nil, sdkerrors.ErrInvalidType.Wrap("filter is not a proto type") - } - anyFilter, err := cdctypes.NewAnyWithValue(pFilter) - if err != nil { - return nil, errorsmod.Wrap(err, "filter") - } - return ContractGrant{ - Contract: contract.String(), - Filter: anyFilter, - }.WithNewLimits(limit) -} - -// WithNewLimits factory method to create a new grant with given limit -func (g ContractGrant) WithNewLimits(limit ContractAuthzLimitX) (*ContractGrant, error) { - pLimit, ok := limit.(proto.Message) - if !ok { - return nil, sdkerrors.ErrInvalidType.Wrap("limit is not a proto type") - } - anyLimit, err := cdctypes.NewAnyWithValue(pLimit) - if err != nil { - return nil, errorsmod.Wrap(err, "limit") - } - - return &ContractGrant{ - Contract: g.Contract, - Limit: anyLimit, - Filter: g.Filter, - }, nil -} - -// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces -func (g ContractGrant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { - var f ContractAuthzFilterX - if err := unpacker.UnpackAny(g.Filter, &f); err != nil { - return errorsmod.Wrap(err, "filter") - } - var l ContractAuthzLimitX - if err := unpacker.UnpackAny(g.Limit, &l); err != nil { - return errorsmod.Wrap(err, "limit") - } - return nil -} - -// GetLimit returns the cached value from the ContractGrant.Limit if present. -func (g ContractGrant) GetLimit() ContractAuthzLimitX { - if g.Limit == nil { - return &UndefinedLimit{} - } - a, ok := g.Limit.GetCachedValue().(ContractAuthzLimitX) - if !ok { - return &UndefinedLimit{} - } - return a -} - -// GetFilter returns the cached value from the ContractGrant.Filter if present. -func (g ContractGrant) GetFilter() ContractAuthzFilterX { - if g.Filter == nil { - return &UndefinedFilter{} - } - a, ok := g.Filter.GetCachedValue().(ContractAuthzFilterX) - if !ok { - return &UndefinedFilter{} - } - return a -} - -// ValidateBasic validates the grant -func (g ContractGrant) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(g.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - // execution limits - if err := g.GetLimit().ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "limit") - } - // filter - if err := g.GetFilter().ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "filter") - } - return nil -} - -// UndefinedFilter null object that is always rejected in execution -type UndefinedFilter struct{} - -// Accept always returns error -func (f *UndefinedFilter) Accept(_ sdk.Context, _ RawContractMessage) (bool, error) { - return false, sdkerrors.ErrNotFound.Wrapf("undefined filter") -} - -// ValidateBasic always returns error -func (f UndefinedFilter) ValidateBasic() error { - return sdkerrors.ErrInvalidType.Wrapf("undefined filter") -} - -// NewAllowAllMessagesFilter constructor -func NewAllowAllMessagesFilter() *AllowAllMessagesFilter { - return &AllowAllMessagesFilter{} -} - -// Accept accepts any valid json message content. -func (f *AllowAllMessagesFilter) Accept(_ sdk.Context, msg RawContractMessage) (bool, error) { - return true, msg.ValidateBasic() -} - -// ValidateBasic returns always nil -func (f AllowAllMessagesFilter) ValidateBasic() error { - return nil -} - -// NewAcceptedMessageKeysFilter constructor -func NewAcceptedMessageKeysFilter(acceptedKeys ...string) *AcceptedMessageKeysFilter { - return &AcceptedMessageKeysFilter{Keys: acceptedKeys} -} - -// Accept only payload messages which contain one of the accepted key names in the json object. -func (f *AcceptedMessageKeysFilter) Accept(ctx sdk.Context, msg RawContractMessage) (bool, error) { - gasForDeserialization := gasDeserializationCostPerByte * uint64(len(msg)) - ctx.GasMeter().ConsumeGas(gasForDeserialization, "contract authorization") - - ok, err := isJSONObjectWithTopLevelKey(msg, f.Keys) - if err != nil { - return false, sdkerrors.ErrUnauthorized.Wrapf("not an allowed msg: %s", err.Error()) - } - return ok, nil -} - -// ValidateBasic validates the filter -func (f AcceptedMessageKeysFilter) ValidateBasic() error { - if len(f.Keys) == 0 { - return ErrEmpty.Wrap("keys") - } - idx := make(map[string]struct{}, len(f.Keys)) - for _, m := range f.Keys { - if m == "" { - return ErrEmpty.Wrap("key") - } - if m != strings.TrimSpace(m) { - return ErrInvalid.Wrapf("key %q contains whitespaces", m) - } - if _, exists := idx[m]; exists { - return ErrDuplicate.Wrapf("key %q", m) - } - idx[m] = struct{}{} - } - return nil -} - -// NewAcceptedMessagesFilter constructor -func NewAcceptedMessagesFilter(msgs ...RawContractMessage) *AcceptedMessagesFilter { - return &AcceptedMessagesFilter{Messages: msgs} -} - -// Accept only payload messages which are equal to the granted one. -func (f *AcceptedMessagesFilter) Accept(_ sdk.Context, msg RawContractMessage) (bool, error) { - for _, v := range f.Messages { - if v.Equal(msg) { - return true, nil - } - } - return false, nil -} - -// ValidateBasic validates the filter -func (f AcceptedMessagesFilter) ValidateBasic() error { - if len(f.Messages) == 0 { - return ErrEmpty.Wrap("messages") - } - idx := make(map[string]struct{}, len(f.Messages)) - for _, m := range f.Messages { - if len(m) == 0 { - return ErrEmpty.Wrap("message") - } - if err := m.ValidateBasic(); err != nil { - return err - } - if _, exists := idx[string(m)]; exists { - return ErrDuplicate.Wrap("message") - } - idx[string(m)] = struct{}{} - } - return nil -} - -var ( - _ ContractAuthzLimitX = &UndefinedLimit{} - _ ContractAuthzLimitX = &MaxCallsLimit{} - _ ContractAuthzLimitX = &MaxFundsLimit{} - _ ContractAuthzLimitX = &CombinedLimit{} -) - -// UndefinedLimit null object that is always rejected in execution -type UndefinedLimit struct{} - -// ValidateBasic always returns error -func (u UndefinedLimit) ValidateBasic() error { - return sdkerrors.ErrInvalidType.Wrapf("undefined limit") -} - -// Accept always returns error -func (u UndefinedLimit) Accept(_ sdk.Context, _ AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { - return nil, sdkerrors.ErrNotFound.Wrapf("undefined filter") -} - -// NewMaxCallsLimit constructor -func NewMaxCallsLimit(number uint64) *MaxCallsLimit { - return &MaxCallsLimit{Remaining: number} -} - -// Accept only the defined number of message calls. No token transfers to the contract allowed. -func (m MaxCallsLimit) Accept(_ sdk.Context, msg AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { - if !msg.GetFunds().Empty() { - return &ContractAuthzLimitAcceptResult{Accepted: false}, nil - } - switch n := m.Remaining; n { - case 0: // sanity check - return nil, sdkerrors.ErrUnauthorized.Wrap("no calls left") - case 1: - return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil - default: - return &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: &MaxCallsLimit{Remaining: n - 1}}, nil - } -} - -// ValidateBasic validates the limit -func (m MaxCallsLimit) ValidateBasic() error { - if m.Remaining == 0 { - return ErrEmpty.Wrap("remaining calls") - } - return nil -} - -// NewMaxFundsLimit constructor -// A panic will occur if the coin set is not valid. -func NewMaxFundsLimit(max ...sdk.Coin) *MaxFundsLimit { - return &MaxFundsLimit{Amounts: sdk.NewCoins(max...)} -} - -// Accept until the defined budget for token transfers to the contract is spent -func (m MaxFundsLimit) Accept(_ sdk.Context, msg AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { - if msg.GetFunds().Empty() { // no state changes required - return &ContractAuthzLimitAcceptResult{Accepted: true}, nil - } - if !msg.GetFunds().IsAllLTE(m.Amounts) { - return &ContractAuthzLimitAcceptResult{Accepted: false}, nil - } - newAmounts := m.Amounts.Sub(msg.GetFunds()...) - if newAmounts.IsZero() { - return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil - } - return &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: &MaxFundsLimit{Amounts: newAmounts}}, nil -} - -// ValidateBasic validates the limit -func (m MaxFundsLimit) ValidateBasic() error { - if err := m.Amounts.Validate(); err != nil { - return err - } - if m.Amounts.IsZero() { - return ErrEmpty.Wrap("amounts") - } - return nil -} - -// NewCombinedLimit constructor -// A panic will occur if the coin set is not valid. -func NewCombinedLimit(maxCalls uint64, maxAmounts ...sdk.Coin) *CombinedLimit { - return &CombinedLimit{CallsRemaining: maxCalls, Amounts: sdk.NewCoins(maxAmounts...)} -} - -// Accept until the max calls is reached or the token budget is spent. -func (l CombinedLimit) Accept(_ sdk.Context, msg AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { - transferFunds := msg.GetFunds() - if !transferFunds.IsAllLTE(l.Amounts) { - return &ContractAuthzLimitAcceptResult{Accepted: false}, nil // does not apply - } - switch n := l.CallsRemaining; n { - case 0: // sanity check - return nil, sdkerrors.ErrUnauthorized.Wrap("no calls left") - case 1: - return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil - default: - remainingAmounts := l.Amounts.Sub(transferFunds...) - if remainingAmounts.IsZero() { - return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil - } - return &ContractAuthzLimitAcceptResult{ - Accepted: true, - UpdateLimit: NewCombinedLimit(n-1, remainingAmounts...), - }, nil - } -} - -// ValidateBasic validates the limit -func (l CombinedLimit) ValidateBasic() error { - if l.CallsRemaining == 0 { - return ErrEmpty.Wrap("remaining calls") - } - if l.Amounts.IsZero() { - return ErrEmpty.Wrap("amounts") - } - if err := l.Amounts.Validate(); err != nil { - return errorsmod.Wrap(err, "amounts") - } - return nil -} diff --git a/x/wasm/types/authz.pb.go b/x/wasm/types/authz.pb.go deleted file mode 100644 index 2d76723..0000000 --- a/x/wasm/types/authz.pb.go +++ /dev/null @@ -1,1870 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/authz.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types1 "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = 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 - -// ContractExecutionAuthorization defines authorization for wasm execute. -// Since: wasmd 0.30 -type ContractExecutionAuthorization struct { - // Grants for contract executions - Grants []ContractGrant `protobuf:"bytes,1,rep,name=grants,proto3" json:"grants"` -} - -func (m *ContractExecutionAuthorization) Reset() { *m = ContractExecutionAuthorization{} } -func (m *ContractExecutionAuthorization) String() string { return proto.CompactTextString(m) } -func (*ContractExecutionAuthorization) ProtoMessage() {} -func (*ContractExecutionAuthorization) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{0} -} - -func (m *ContractExecutionAuthorization) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractExecutionAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractExecutionAuthorization.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 *ContractExecutionAuthorization) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractExecutionAuthorization.Merge(m, src) -} - -func (m *ContractExecutionAuthorization) XXX_Size() int { - return m.Size() -} - -func (m *ContractExecutionAuthorization) XXX_DiscardUnknown() { - xxx_messageInfo_ContractExecutionAuthorization.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractExecutionAuthorization proto.InternalMessageInfo - -// ContractMigrationAuthorization defines authorization for wasm contract -// migration. Since: wasmd 0.30 -type ContractMigrationAuthorization struct { - // Grants for contract migrations - Grants []ContractGrant `protobuf:"bytes,1,rep,name=grants,proto3" json:"grants"` -} - -func (m *ContractMigrationAuthorization) Reset() { *m = ContractMigrationAuthorization{} } -func (m *ContractMigrationAuthorization) String() string { return proto.CompactTextString(m) } -func (*ContractMigrationAuthorization) ProtoMessage() {} -func (*ContractMigrationAuthorization) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{1} -} - -func (m *ContractMigrationAuthorization) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractMigrationAuthorization) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractMigrationAuthorization.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 *ContractMigrationAuthorization) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractMigrationAuthorization.Merge(m, src) -} - -func (m *ContractMigrationAuthorization) XXX_Size() int { - return m.Size() -} - -func (m *ContractMigrationAuthorization) XXX_DiscardUnknown() { - xxx_messageInfo_ContractMigrationAuthorization.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractMigrationAuthorization proto.InternalMessageInfo - -// ContractGrant a granted permission for a single contract -// Since: wasmd 0.30 -type ContractGrant struct { - // Contract is the bech32 address of the smart contract - Contract string `protobuf:"bytes,1,opt,name=contract,proto3" json:"contract,omitempty"` - // Limit defines execution limits that are enforced and updated when the grant - // is applied. When the limit lapsed the grant is removed. - Limit *types.Any `protobuf:"bytes,2,opt,name=limit,proto3" json:"limit,omitempty"` - // Filter define more fine-grained control on the message payload passed - // to the contract in the operation. When no filter applies on execution, the - // operation is prohibited. - Filter *types.Any `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` -} - -func (m *ContractGrant) Reset() { *m = ContractGrant{} } -func (m *ContractGrant) String() string { return proto.CompactTextString(m) } -func (*ContractGrant) ProtoMessage() {} -func (*ContractGrant) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{2} -} - -func (m *ContractGrant) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractGrant) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractGrant.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 *ContractGrant) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractGrant.Merge(m, src) -} - -func (m *ContractGrant) XXX_Size() int { - return m.Size() -} - -func (m *ContractGrant) XXX_DiscardUnknown() { - xxx_messageInfo_ContractGrant.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractGrant proto.InternalMessageInfo - -// MaxCallsLimit limited number of calls to the contract. No funds transferable. -// Since: wasmd 0.30 -type MaxCallsLimit struct { - // Remaining number that is decremented on each execution - Remaining uint64 `protobuf:"varint,1,opt,name=remaining,proto3" json:"remaining,omitempty"` -} - -func (m *MaxCallsLimit) Reset() { *m = MaxCallsLimit{} } -func (m *MaxCallsLimit) String() string { return proto.CompactTextString(m) } -func (*MaxCallsLimit) ProtoMessage() {} -func (*MaxCallsLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{3} -} - -func (m *MaxCallsLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MaxCallsLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MaxCallsLimit.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 *MaxCallsLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MaxCallsLimit.Merge(m, src) -} - -func (m *MaxCallsLimit) XXX_Size() int { - return m.Size() -} - -func (m *MaxCallsLimit) XXX_DiscardUnknown() { - xxx_messageInfo_MaxCallsLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_MaxCallsLimit proto.InternalMessageInfo - -// MaxFundsLimit defines the maximal amounts that can be sent to the contract. -// Since: wasmd 0.30 -type MaxFundsLimit struct { - // Amounts is the maximal amount of tokens transferable to the contract. - Amounts github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,1,rep,name=amounts,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amounts"` -} - -func (m *MaxFundsLimit) Reset() { *m = MaxFundsLimit{} } -func (m *MaxFundsLimit) String() string { return proto.CompactTextString(m) } -func (*MaxFundsLimit) ProtoMessage() {} -func (*MaxFundsLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{4} -} - -func (m *MaxFundsLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MaxFundsLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MaxFundsLimit.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 *MaxFundsLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_MaxFundsLimit.Merge(m, src) -} - -func (m *MaxFundsLimit) XXX_Size() int { - return m.Size() -} - -func (m *MaxFundsLimit) XXX_DiscardUnknown() { - xxx_messageInfo_MaxFundsLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_MaxFundsLimit proto.InternalMessageInfo - -// CombinedLimit defines the maximal amounts that can be sent to a contract and -// the maximal number of calls executable. Both need to remain >0 to be valid. -// Since: wasmd 0.30 -type CombinedLimit struct { - // Remaining number that is decremented on each execution - CallsRemaining uint64 `protobuf:"varint,1,opt,name=calls_remaining,json=callsRemaining,proto3" json:"calls_remaining,omitempty"` - // Amounts is the maximal amount of tokens transferable to the contract. - Amounts github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,2,rep,name=amounts,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"amounts"` -} - -func (m *CombinedLimit) Reset() { *m = CombinedLimit{} } -func (m *CombinedLimit) String() string { return proto.CompactTextString(m) } -func (*CombinedLimit) ProtoMessage() {} -func (*CombinedLimit) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{5} -} - -func (m *CombinedLimit) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *CombinedLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CombinedLimit.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 *CombinedLimit) XXX_Merge(src proto.Message) { - xxx_messageInfo_CombinedLimit.Merge(m, src) -} - -func (m *CombinedLimit) XXX_Size() int { - return m.Size() -} - -func (m *CombinedLimit) XXX_DiscardUnknown() { - xxx_messageInfo_CombinedLimit.DiscardUnknown(m) -} - -var xxx_messageInfo_CombinedLimit proto.InternalMessageInfo - -// AllowAllMessagesFilter is a wildcard to allow any type of contract payload -// message. -// Since: wasmd 0.30 -type AllowAllMessagesFilter struct{} - -func (m *AllowAllMessagesFilter) Reset() { *m = AllowAllMessagesFilter{} } -func (m *AllowAllMessagesFilter) String() string { return proto.CompactTextString(m) } -func (*AllowAllMessagesFilter) ProtoMessage() {} -func (*AllowAllMessagesFilter) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{6} -} - -func (m *AllowAllMessagesFilter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AllowAllMessagesFilter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AllowAllMessagesFilter.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 *AllowAllMessagesFilter) XXX_Merge(src proto.Message) { - xxx_messageInfo_AllowAllMessagesFilter.Merge(m, src) -} - -func (m *AllowAllMessagesFilter) XXX_Size() int { - return m.Size() -} - -func (m *AllowAllMessagesFilter) XXX_DiscardUnknown() { - xxx_messageInfo_AllowAllMessagesFilter.DiscardUnknown(m) -} - -var xxx_messageInfo_AllowAllMessagesFilter proto.InternalMessageInfo - -// AcceptedMessageKeysFilter accept only the specific contract message keys in -// the json object to be executed. -// Since: wasmd 0.30 -type AcceptedMessageKeysFilter struct { - // Messages is the list of unique keys - Keys []string `protobuf:"bytes,1,rep,name=keys,proto3" json:"keys,omitempty"` -} - -func (m *AcceptedMessageKeysFilter) Reset() { *m = AcceptedMessageKeysFilter{} } -func (m *AcceptedMessageKeysFilter) String() string { return proto.CompactTextString(m) } -func (*AcceptedMessageKeysFilter) ProtoMessage() {} -func (*AcceptedMessageKeysFilter) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{7} -} - -func (m *AcceptedMessageKeysFilter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AcceptedMessageKeysFilter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AcceptedMessageKeysFilter.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 *AcceptedMessageKeysFilter) XXX_Merge(src proto.Message) { - xxx_messageInfo_AcceptedMessageKeysFilter.Merge(m, src) -} - -func (m *AcceptedMessageKeysFilter) XXX_Size() int { - return m.Size() -} - -func (m *AcceptedMessageKeysFilter) XXX_DiscardUnknown() { - xxx_messageInfo_AcceptedMessageKeysFilter.DiscardUnknown(m) -} - -var xxx_messageInfo_AcceptedMessageKeysFilter proto.InternalMessageInfo - -// AcceptedMessagesFilter accept only the specific raw contract messages to be -// executed. -// Since: wasmd 0.30 -type AcceptedMessagesFilter struct { - // Messages is the list of raw contract messages - Messages []RawContractMessage `protobuf:"bytes,1,rep,name=messages,proto3,casttype=RawContractMessage" json:"messages,omitempty"` -} - -func (m *AcceptedMessagesFilter) Reset() { *m = AcceptedMessagesFilter{} } -func (m *AcceptedMessagesFilter) String() string { return proto.CompactTextString(m) } -func (*AcceptedMessagesFilter) ProtoMessage() {} -func (*AcceptedMessagesFilter) Descriptor() ([]byte, []int) { - return fileDescriptor_36ff3a20cf32b258, []int{8} -} - -func (m *AcceptedMessagesFilter) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AcceptedMessagesFilter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AcceptedMessagesFilter.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 *AcceptedMessagesFilter) XXX_Merge(src proto.Message) { - xxx_messageInfo_AcceptedMessagesFilter.Merge(m, src) -} - -func (m *AcceptedMessagesFilter) XXX_Size() int { - return m.Size() -} - -func (m *AcceptedMessagesFilter) XXX_DiscardUnknown() { - xxx_messageInfo_AcceptedMessagesFilter.DiscardUnknown(m) -} - -var xxx_messageInfo_AcceptedMessagesFilter proto.InternalMessageInfo - -func init() { - proto.RegisterType((*ContractExecutionAuthorization)(nil), "cosmwasm.wasm.v1.ContractExecutionAuthorization") - proto.RegisterType((*ContractMigrationAuthorization)(nil), "cosmwasm.wasm.v1.ContractMigrationAuthorization") - proto.RegisterType((*ContractGrant)(nil), "cosmwasm.wasm.v1.ContractGrant") - proto.RegisterType((*MaxCallsLimit)(nil), "cosmwasm.wasm.v1.MaxCallsLimit") - proto.RegisterType((*MaxFundsLimit)(nil), "cosmwasm.wasm.v1.MaxFundsLimit") - proto.RegisterType((*CombinedLimit)(nil), "cosmwasm.wasm.v1.CombinedLimit") - proto.RegisterType((*AllowAllMessagesFilter)(nil), "cosmwasm.wasm.v1.AllowAllMessagesFilter") - proto.RegisterType((*AcceptedMessageKeysFilter)(nil), "cosmwasm.wasm.v1.AcceptedMessageKeysFilter") - proto.RegisterType((*AcceptedMessagesFilter)(nil), "cosmwasm.wasm.v1.AcceptedMessagesFilter") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/authz.proto", fileDescriptor_36ff3a20cf32b258) } - -var fileDescriptor_36ff3a20cf32b258 = []byte{ - // 671 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x55, 0x4d, 0x4f, 0x13, 0x41, - 0x18, 0xee, 0x00, 0x22, 0x1d, 0xc4, 0x8f, 0x0d, 0x21, 0x05, 0xc9, 0x96, 0xac, 0x1a, 0x2b, 0x49, - 0x77, 0x53, 0x8c, 0x97, 0x5e, 0x4c, 0x4b, 0xc4, 0x18, 0xc0, 0xc3, 0xc6, 0x44, 0xe2, 0x85, 0xcc, - 0x6e, 0x87, 0x65, 0x64, 0x77, 0xa6, 0xd9, 0x99, 0xa5, 0x94, 0xc4, 0x3f, 0xe0, 0xc9, 0x9b, 0x7f, - 0xc1, 0x78, 0xe2, 0xd0, 0xa3, 0x3f, 0x80, 0x70, 0xe2, 0x68, 0x3c, 0xa0, 0x42, 0x0c, 0xff, 0xc1, - 0x93, 0xd9, 0x99, 0xd9, 0x42, 0x09, 0x34, 0xc8, 0x89, 0xcb, 0x74, 0xde, 0xf7, 0x9d, 0x79, 0x9e, - 0xe7, 0xfd, 0xd8, 0x29, 0x9c, 0xf6, 0x19, 0x8f, 0x5a, 0x88, 0x47, 0x8e, 0x5c, 0x36, 0x2b, 0x0e, - 0x4a, 0xc4, 0xfa, 0xb6, 0xdd, 0x8c, 0x99, 0x60, 0xc6, 0xdd, 0x2c, 0x6a, 0xcb, 0x65, 0xb3, 0x32, - 0x35, 0x1e, 0xb0, 0x80, 0xc9, 0xa0, 0x93, 0xee, 0xd4, 0xb9, 0xa9, 0xc9, 0xf4, 0x1c, 0xe3, 0xab, - 0x2a, 0xa0, 0x0c, 0x1d, 0x32, 0x95, 0xe5, 0x78, 0x88, 0x63, 0x67, 0xb3, 0xe2, 0x61, 0x81, 0x2a, - 0x8e, 0xcf, 0x08, 0xcd, 0xae, 0x06, 0x8c, 0x05, 0x21, 0x76, 0xa4, 0xe5, 0x25, 0x6b, 0x0e, 0xa2, - 0x6d, 0x1d, 0xba, 0x87, 0x22, 0x42, 0x99, 0x23, 0x57, 0xe5, 0xb2, 0x3a, 0x00, 0x9a, 0xf3, 0x8c, - 0x8a, 0x18, 0xf9, 0xe2, 0xc5, 0x16, 0xf6, 0x13, 0x41, 0x18, 0xad, 0x25, 0x62, 0x9d, 0xc5, 0x64, - 0x1b, 0xa5, 0x86, 0x51, 0x87, 0xc3, 0x41, 0x8c, 0xa8, 0xe0, 0x05, 0x30, 0x33, 0x58, 0x1a, 0x9d, - 0x2b, 0xda, 0x67, 0x93, 0xb0, 0x33, 0x84, 0x97, 0xe9, 0xb9, 0x7a, 0x7e, 0xf7, 0xa0, 0x98, 0xfb, - 0x72, 0xbc, 0x33, 0x0b, 0x5c, 0x7d, 0xb3, 0xfa, 0x7a, 0xaf, 0x53, 0xb6, 0x74, 0x1a, 0xaa, 0x1e, - 0x5a, 0xb9, 0xdd, 0xc3, 0xf5, 0xf1, 0x78, 0x67, 0xf6, 0x81, 0xac, 0x5b, 0x7f, 0x4d, 0x3d, 0xb2, - 0x97, 0x49, 0x10, 0xa3, 0x6b, 0x26, 0xfb, 0x7c, 0x4d, 0xd6, 0x0f, 0x00, 0xc7, 0x7a, 0x48, 0x8d, - 0x29, 0x38, 0xe2, 0x6b, 0x47, 0x01, 0xcc, 0x80, 0x52, 0xde, 0xed, 0xda, 0xc6, 0x1b, 0x78, 0x23, - 0x24, 0x11, 0x11, 0x85, 0x81, 0x19, 0x50, 0x1a, 0x9d, 0x1b, 0xb7, 0x55, 0x67, 0xed, 0xac, 0xb3, - 0x76, 0x8d, 0xb6, 0xeb, 0xa5, 0xbd, 0x4e, 0xf9, 0xe1, 0x85, 0x99, 0xa5, 0xf4, 0xdb, 0x4b, 0x29, - 0xc8, 0x8a, 0xab, 0xc0, 0x8c, 0xb7, 0x70, 0x78, 0x8d, 0x84, 0x02, 0xc7, 0x85, 0xc1, 0x3e, 0xb0, - 0x4f, 0xf6, 0x3a, 0xe5, 0x47, 0xfd, 0x61, 0x17, 0x24, 0xca, 0x8a, 0xab, 0xe1, 0x2c, 0x0a, 0xc7, - 0x96, 0xd1, 0xd6, 0x3c, 0x0a, 0x43, 0x2e, 0x19, 0x8d, 0x69, 0x98, 0x8f, 0x71, 0x84, 0x08, 0x25, - 0x34, 0x90, 0xc9, 0x0d, 0xb9, 0x27, 0x8e, 0xea, 0xf3, 0xcb, 0x0a, 0x4f, 0xab, 0x6b, 0xc8, 0xea, - 0xf6, 0xc0, 0x5b, 0xdf, 0x80, 0x24, 0x5c, 0x48, 0x68, 0x43, 0x13, 0xbe, 0x87, 0x37, 0x51, 0xc4, - 0x92, 0x93, 0x9e, 0x4f, 0xda, 0xba, 0x79, 0xe9, 0xc7, 0xd2, 0xed, 0xdd, 0x3c, 0x23, 0xb4, 0xfe, - 0x2c, 0xed, 0xf6, 0xd7, 0x9f, 0xc5, 0x52, 0x40, 0xc4, 0x7a, 0xe2, 0xd9, 0x3e, 0x8b, 0xf4, 0x77, - 0xa6, 0x7f, 0xca, 0xbc, 0xb1, 0xe1, 0x88, 0x76, 0x13, 0x73, 0x79, 0x81, 0xab, 0xc9, 0xc8, 0x08, - 0xae, 0x28, 0xff, 0x44, 0xac, 0xf5, 0x47, 0xce, 0x42, 0xe4, 0x11, 0x8a, 0x1b, 0x4a, 0xfe, 0x63, - 0x78, 0xc7, 0x4f, 0xd3, 0x5b, 0x3d, 0x5b, 0xb5, 0xdb, 0xd2, 0xed, 0x66, 0xde, 0xd3, 0x79, 0x0e, - 0x5c, 0xc3, 0x3c, 0x7b, 0xb2, 0xb2, 0x7c, 0x38, 0x51, 0x0b, 0x43, 0xd6, 0xaa, 0x85, 0xe1, 0x32, - 0xe6, 0x1c, 0x05, 0x98, 0xab, 0xc9, 0xa9, 0xbe, 0xba, 0xf4, 0x8c, 0xa5, 0xd8, 0xf7, 0x25, 0xf6, - 0xf9, 0x50, 0xd6, 0x07, 0x38, 0x59, 0xf3, 0x7d, 0xdc, 0x14, 0xb8, 0xa1, 0x23, 0x8b, 0xb8, 0xad, - 0x83, 0x86, 0x01, 0x87, 0x36, 0x70, 0x5b, 0xcd, 0x44, 0xde, 0x95, 0xfb, 0xea, 0xd2, 0x7f, 0x71, - 0x9b, 0x8a, 0xfb, 0x22, 0x06, 0xeb, 0x33, 0x80, 0x13, 0x67, 0xa2, 0x19, 0xf9, 0x1c, 0x1c, 0x89, - 0xb4, 0x47, 0x0a, 0xb8, 0x55, 0x9f, 0xf8, 0x7b, 0x50, 0x34, 0x5c, 0xd4, 0xea, 0xbe, 0x15, 0x2a, - 0xec, 0x76, 0xcf, 0x5d, 0xad, 0x30, 0xe7, 0xd2, 0xd7, 0x17, 0x77, 0x7f, 0x9b, 0xb9, 0xdd, 0x43, - 0x13, 0xec, 0x1f, 0x9a, 0xe0, 0xd7, 0xa1, 0x09, 0x3e, 0x1d, 0x99, 0xb9, 0xfd, 0x23, 0x33, 0xf7, - 0xfd, 0xc8, 0xcc, 0xbd, 0x2b, 0x9f, 0x1a, 0x0a, 0x81, 0xe3, 0x26, 0xc5, 0xa2, 0xc5, 0xe2, 0x0d, - 0xb9, 0x2f, 0xfb, 0x2c, 0xc6, 0xce, 0x96, 0xfa, 0x1b, 0x93, 0xf3, 0xe1, 0x0d, 0xcb, 0x27, 0xe2, - 0xe9, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x4e, 0xa7, 0xb1, 0x51, 0xe4, 0x06, 0x00, 0x00, -} - -func (m *ContractExecutionAuthorization) 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 *ContractExecutionAuthorization) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractExecutionAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Grants) > 0 { - for iNdEx := len(m.Grants) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Grants[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *ContractMigrationAuthorization) 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 *ContractMigrationAuthorization) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractMigrationAuthorization) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Grants) > 0 { - for iNdEx := len(m.Grants) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Grants[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *ContractGrant) 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 *ContractGrant) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractGrant) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Filter != nil { - { - size, err := m.Filter.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if m.Limit != nil { - { - size, err := m.Limit.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintAuthz(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MaxCallsLimit) 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 *MaxCallsLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MaxCallsLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Remaining != 0 { - i = encodeVarintAuthz(dAtA, i, uint64(m.Remaining)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MaxFundsLimit) 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 *MaxFundsLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MaxFundsLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amounts) > 0 { - for iNdEx := len(m.Amounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *CombinedLimit) 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 *CombinedLimit) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CombinedLimit) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Amounts) > 0 { - for iNdEx := len(m.Amounts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Amounts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintAuthz(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - if m.CallsRemaining != 0 { - i = encodeVarintAuthz(dAtA, i, uint64(m.CallsRemaining)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *AllowAllMessagesFilter) 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 *AllowAllMessagesFilter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AllowAllMessagesFilter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *AcceptedMessageKeysFilter) 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 *AcceptedMessageKeysFilter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AcceptedMessageKeysFilter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Keys) > 0 { - for iNdEx := len(m.Keys) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Keys[iNdEx]) - copy(dAtA[i:], m.Keys[iNdEx]) - i = encodeVarintAuthz(dAtA, i, uint64(len(m.Keys[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *AcceptedMessagesFilter) 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 *AcceptedMessagesFilter) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AcceptedMessagesFilter) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Messages) > 0 { - for iNdEx := len(m.Messages) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Messages[iNdEx]) - copy(dAtA[i:], m.Messages[iNdEx]) - i = encodeVarintAuthz(dAtA, i, uint64(len(m.Messages[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintAuthz(dAtA []byte, offset int, v uint64) int { - offset -= sovAuthz(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *ContractExecutionAuthorization) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Grants) > 0 { - for _, e := range m.Grants { - l = e.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *ContractMigrationAuthorization) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Grants) > 0 { - for _, e := range m.Grants { - l = e.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *ContractGrant) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovAuthz(uint64(l)) - } - if m.Limit != nil { - l = m.Limit.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - if m.Filter != nil { - l = m.Filter.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - return n -} - -func (m *MaxCallsLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Remaining != 0 { - n += 1 + sovAuthz(uint64(m.Remaining)) - } - return n -} - -func (m *MaxFundsLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Amounts) > 0 { - for _, e := range m.Amounts { - l = e.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *CombinedLimit) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CallsRemaining != 0 { - n += 1 + sovAuthz(uint64(m.CallsRemaining)) - } - if len(m.Amounts) > 0 { - for _, e := range m.Amounts { - l = e.Size() - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *AllowAllMessagesFilter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *AcceptedMessageKeysFilter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Keys) > 0 { - for _, s := range m.Keys { - l = len(s) - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func (m *AcceptedMessagesFilter) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Messages) > 0 { - for _, b := range m.Messages { - l = len(b) - n += 1 + l + sovAuthz(uint64(l)) - } - } - return n -} - -func sovAuthz(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozAuthz(x uint64) (n int) { - return sovAuthz(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *ContractExecutionAuthorization) 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 ErrIntOverflowAuthz - } - 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: ContractExecutionAuthorization: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractExecutionAuthorization: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Grants", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Grants = append(m.Grants, ContractGrant{}) - if err := m.Grants[len(m.Grants)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ContractMigrationAuthorization) 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 ErrIntOverflowAuthz - } - 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: ContractMigrationAuthorization: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractMigrationAuthorization: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Grants", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Grants = append(m.Grants, ContractGrant{}) - if err := m.Grants[len(m.Grants)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ContractGrant) 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 ErrIntOverflowAuthz - } - 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: ContractGrant: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractGrant: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - 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 ErrInvalidLengthAuthz - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Limit == nil { - m.Limit = &types.Any{} - } - if err := m.Limit.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Filter", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Filter == nil { - m.Filter = &types.Any{} - } - if err := m.Filter.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MaxCallsLimit) 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 ErrIntOverflowAuthz - } - 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: MaxCallsLimit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MaxCallsLimit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Remaining", wireType) - } - m.Remaining = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Remaining |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MaxFundsLimit) 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 ErrIntOverflowAuthz - } - 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: MaxFundsLimit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MaxFundsLimit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amounts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amounts = append(m.Amounts, types1.Coin{}) - if err := m.Amounts[len(m.Amounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *CombinedLimit) 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 ErrIntOverflowAuthz - } - 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: CombinedLimit: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CombinedLimit: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CallsRemaining", wireType) - } - m.CallsRemaining = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CallsRemaining |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Amounts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Amounts = append(m.Amounts, types1.Coin{}) - if err := m.Amounts[len(m.Amounts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AllowAllMessagesFilter) 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 ErrIntOverflowAuthz - } - 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: AllowAllMessagesFilter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AllowAllMessagesFilter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AcceptedMessageKeysFilter) 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 ErrIntOverflowAuthz - } - 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: AcceptedMessageKeysFilter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AcceptedMessageKeysFilter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Keys", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - 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 ErrInvalidLengthAuthz - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Keys = append(m.Keys, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AcceptedMessagesFilter) 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 ErrIntOverflowAuthz - } - 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: AcceptedMessagesFilter: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AcceptedMessagesFilter: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Messages", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowAuthz - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthAuthz - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthAuthz - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Messages = append(m.Messages, make([]byte, postIndex-iNdEx)) - copy(m.Messages[len(m.Messages)-1], dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipAuthz(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthAuthz - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipAuthz(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, ErrIntOverflowAuthz - } - 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, ErrIntOverflowAuthz - } - 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, ErrIntOverflowAuthz - } - 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, ErrInvalidLengthAuthz - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupAuthz - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthAuthz - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthAuthz = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowAuthz = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupAuthz = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/authz_test.go b/x/wasm/types/authz_test.go deleted file mode 100644 index 79d279b..0000000 --- a/x/wasm/types/authz_test.go +++ /dev/null @@ -1,729 +0,0 @@ -package types - -import ( - "math" - "testing" - - errorsmod "cosmossdk.io/errors" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - authztypes "github.com/cosmos/cosmos-sdk/x/authz" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestContractAuthzFilterValidate(t *testing.T) { - specs := map[string]struct { - src ContractAuthzFilterX - expErr bool - }{ - "allow all": { - src: &AllowAllMessagesFilter{}, - }, - "allow keys - single": { - src: NewAcceptedMessageKeysFilter("foo"), - }, - "allow keys - multi": { - src: NewAcceptedMessageKeysFilter("foo", "bar"), - }, - "allow keys - empty": { - src: NewAcceptedMessageKeysFilter(), - expErr: true, - }, - "allow keys - duplicates": { - src: NewAcceptedMessageKeysFilter("foo", "foo"), - expErr: true, - }, - "allow keys - whitespaces": { - src: NewAcceptedMessageKeysFilter(" foo"), - expErr: true, - }, - "allow keys - empty key": { - src: NewAcceptedMessageKeysFilter("", "bar"), - expErr: true, - }, - "allow keys - whitespace key": { - src: NewAcceptedMessageKeysFilter(" ", "bar"), - expErr: true, - }, - "allow message - single": { - src: NewAcceptedMessagesFilter([]byte(`{}`)), - }, - "allow message - multiple": { - src: NewAcceptedMessagesFilter([]byte(`{}`), []byte(`{"foo":"bar"}`)), - }, - "allow message - multiple with empty": { - src: NewAcceptedMessagesFilter([]byte(`{}`), nil), - expErr: true, - }, - "allow message - duplicate": { - src: NewAcceptedMessagesFilter([]byte(`{}`), []byte(`{}`)), - expErr: true, - }, - "allow message - non json": { - src: NewAcceptedMessagesFilter([]byte("non-json")), - expErr: true, - }, - "allow message - empty": { - src: NewAcceptedMessagesFilter(), - expErr: true, - }, - "allow all message - always valid": { - src: NewAllowAllMessagesFilter(), - }, - "undefined - always invalid": { - src: &UndefinedFilter{}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestContractAuthzFilterAccept(t *testing.T) { - specs := map[string]struct { - filter ContractAuthzFilterX - src RawContractMessage - exp bool - expGasConsumed sdk.Gas - expErr bool - }{ - "allow all - accepts json obj": { - filter: &AllowAllMessagesFilter{}, - src: []byte(`{}`), - exp: true, - }, - "allow all - accepts json array": { - filter: &AllowAllMessagesFilter{}, - src: []byte(`[{},{}]`), - exp: true, - }, - "allow all - rejects non json msg": { - filter: &AllowAllMessagesFilter{}, - src: []byte(``), - expErr: true, - }, - "allowed key - single": { - filter: NewAcceptedMessageKeysFilter("foo"), - src: []byte(`{"foo": "bar"}`), - exp: true, - expGasConsumed: sdk.Gas(len(`{"foo": "bar"}`)), - }, - "allowed key - multiple": { - filter: NewAcceptedMessageKeysFilter("foo", "other"), - src: []byte(`{"other": "value"}`), - exp: true, - expGasConsumed: sdk.Gas(len(`{"other": "value"}`)), - }, - "allowed key - non accepted key": { - filter: NewAcceptedMessageKeysFilter("foo"), - src: []byte(`{"bar": "value"}`), - exp: false, - expGasConsumed: sdk.Gas(len(`{"bar": "value"}`)), - }, - "allowed key - unsupported array msg": { - filter: NewAcceptedMessageKeysFilter("foo", "other"), - src: []byte(`[{"foo":"bar"}]`), - expErr: false, - expGasConsumed: sdk.Gas(len(`[{"foo":"bar"}]`)), - }, - "allowed key - invalid msg": { - filter: NewAcceptedMessageKeysFilter("foo", "other"), - src: []byte(`not a json msg`), - expErr: true, - }, - "allow message - single": { - filter: NewAcceptedMessagesFilter([]byte(`{}`)), - src: []byte(`{}`), - exp: true, - }, - "allow message - multiple": { - filter: NewAcceptedMessagesFilter([]byte(`[{"foo":"bar"}]`), []byte(`{"other":"value"}`)), - src: []byte(`[{"foo":"bar"}]`), - exp: true, - }, - "allow message - no match": { - filter: NewAcceptedMessagesFilter([]byte(`{"foo":"bar"}`)), - src: []byte(`{"other":"value"}`), - exp: false, - }, - "allow all message - always accept valid": { - filter: NewAllowAllMessagesFilter(), - src: []byte(`{"other":"value"}`), - exp: true, - }, - "allow all message - always reject invalid json": { - filter: NewAllowAllMessagesFilter(), - src: []byte(`not json`), - expErr: true, - }, - "undefined - always errors": { - filter: &UndefinedFilter{}, - src: []byte(`{"foo":"bar"}`), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gm := sdk.NewGasMeter(1_000_000) - allowed, gotErr := spec.filter.Accept(sdk.Context{}.WithGasMeter(gm), spec.src) - - // then - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.exp, allowed) - assert.Equal(t, spec.expGasConsumed, gm.GasConsumed()) - }) - } -} - -func TestContractAuthzLimitValidate(t *testing.T) { - oneToken := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) - specs := map[string]struct { - src ContractAuthzLimitX - expErr bool - }{ - "max calls": { - src: NewMaxCallsLimit(1), - }, - "max calls - max uint64": { - src: NewMaxCallsLimit(math.MaxUint64), - }, - "max calls - empty": { - src: NewMaxCallsLimit(0), - expErr: true, - }, - "max funds": { - src: NewMaxFundsLimit(oneToken), - }, - "max funds - empty coins": { - src: NewMaxFundsLimit(), - expErr: true, - }, - "max funds - duplicates": { - src: &MaxFundsLimit{Amounts: sdk.Coins{oneToken, oneToken}}, - expErr: true, - }, - "max funds - contains empty value": { - src: &MaxFundsLimit{Amounts: sdk.Coins{oneToken, sdk.NewCoin("other", sdk.ZeroInt())}.Sort()}, - expErr: true, - }, - "max funds - unsorted": { - src: &MaxFundsLimit{Amounts: sdk.Coins{oneToken, sdk.NewCoin("other", sdk.OneInt())}}, - expErr: true, - }, - "combined": { - src: NewCombinedLimit(1, oneToken), - }, - "combined - empty calls": { - src: NewCombinedLimit(0, oneToken), - expErr: true, - }, - "combined - empty amounts": { - src: NewCombinedLimit(1), - expErr: true, - }, - "combined - invalid amounts": { - src: &CombinedLimit{CallsRemaining: 1, Amounts: sdk.Coins{oneToken, oneToken}}, - expErr: true, - }, - "undefined": { - src: &UndefinedLimit{}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestContractAuthzLimitAccept(t *testing.T) { - oneToken := sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt()) - otherToken := sdk.NewCoin("other", sdk.OneInt()) - specs := map[string]struct { - limit ContractAuthzLimitX - src AuthzableWasmMsg - exp *ContractAuthzLimitAcceptResult - expErr bool - }{ - "max calls - updated": { - limit: NewMaxCallsLimit(2), - src: &MsgExecuteContract{}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewMaxCallsLimit(1)}, - }, - "max calls - removed": { - limit: NewMaxCallsLimit(1), - src: &MsgExecuteContract{}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max calls - accepted with zero fund set": { - limit: NewMaxCallsLimit(1), - src: &MsgExecuteContract{Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.ZeroInt()))}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max calls - rejected with some fund transfer": { - limit: NewMaxCallsLimit(1), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max calls - invalid": { - limit: &MaxCallsLimit{}, - src: &MsgExecuteContract{}, - expErr: true, - }, - "max funds - single updated": { - limit: NewMaxFundsLimit(oneToken.Add(oneToken)), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewMaxFundsLimit(oneToken)}, - }, - "max funds - single removed": { - limit: NewMaxFundsLimit(oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max funds - single with unknown token": { - limit: NewMaxFundsLimit(oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(otherToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max funds - single exceeds limit": { - limit: NewMaxFundsLimit(oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken.Add(oneToken))}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max funds - single with additional token send": { - limit: NewMaxFundsLimit(oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken, otherToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max funds - multi with other left": { - limit: NewMaxFundsLimit(oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewMaxFundsLimit(otherToken)}, - }, - "max funds - multi with all used": { - limit: NewMaxFundsLimit(oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken, otherToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max funds - multi with no tokens sent": { - limit: NewMaxFundsLimit(oneToken, otherToken), - src: &MsgExecuteContract{}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true}, - }, - "max funds - multi with other exceeds limit": { - limit: NewMaxFundsLimit(oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken, otherToken.Add(otherToken))}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max combined - multi amounts one consumed": { - limit: NewCombinedLimit(2, oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewCombinedLimit(1, otherToken)}, - }, - "max combined - multi amounts none consumed": { - limit: NewCombinedLimit(2, oneToken, otherToken), - src: &MsgExecuteContract{}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewCombinedLimit(1, oneToken, otherToken)}, - }, - "max combined - removed on last execution": { - limit: NewCombinedLimit(1, oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max combined - removed on last token": { - limit: NewCombinedLimit(2, oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, - }, - "max combined - update with token and calls remaining": { - limit: NewCombinedLimit(2, oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: true, UpdateLimit: NewCombinedLimit(1, otherToken)}, - }, - "max combined - multi with other exceeds limit": { - limit: NewCombinedLimit(2, oneToken, otherToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(oneToken, otherToken.Add(otherToken))}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "max combined - with unknown token": { - limit: NewCombinedLimit(2, oneToken), - src: &MsgExecuteContract{Funds: sdk.NewCoins(otherToken)}, - exp: &ContractAuthzLimitAcceptResult{Accepted: false}, - }, - "undefined": { - limit: &UndefinedLimit{}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotResult, gotErr := spec.limit.Accept(sdk.Context{}, spec.src) - // then - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.exp, gotResult) - }) - } -} - -func TestValidateContractGrant(t *testing.T) { - specs := map[string]struct { - setup func(t *testing.T) ContractGrant - expErr bool - }{ - "all good": { - setup: func(t *testing.T) ContractGrant { - return mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) - }, - }, - "invalid address": { - setup: func(t *testing.T) ContractGrant { - return mustGrant([]byte{}, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) - }, - expErr: true, - }, - "invalid limit": { - setup: func(t *testing.T) ContractGrant { - return mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(0), NewAllowAllMessagesFilter()) - }, - expErr: true, - }, - - "invalid filter ": { - setup: func(t *testing.T) ContractGrant { - return mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter()) - }, - expErr: true, - }, - "empty limit": { - setup: func(t *testing.T) ContractGrant { - r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(0), NewAllowAllMessagesFilter()) - r.Limit = nil - return r - }, - expErr: true, - }, - - "empty filter ": { - setup: func(t *testing.T) ContractGrant { - r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter()) - r.Filter = nil - return r - }, - expErr: true, - }, - "wrong limit type": { - setup: func(t *testing.T) ContractGrant { - r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(0), NewAllowAllMessagesFilter()) - r.Limit = r.Filter - return r - }, - expErr: true, - }, - - "wrong filter type": { - setup: func(t *testing.T) ContractGrant { - r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter()) - r.Filter = r.Limit - return r - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.setup(t).ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestValidateContractAuthorization(t *testing.T) { - validGrant, err := NewContractGrant(randBytes(SDKAddrLen), NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) - require.NoError(t, err) - invalidGrant, err := NewContractGrant(randBytes(SDKAddrLen), NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) - require.NoError(t, err) - invalidGrant.Limit = nil - - specs := map[string]struct { - setup func(t *testing.T) validatable - expErr bool - }{ - "contract execution": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant) - }, - }, - "contract execution - duplicate grants": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant, *validGrant) - }, - }, - "contract execution - invalid grant": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant, *invalidGrant) - }, - expErr: true, - }, - "contract execution - empty grants": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization() - }, - expErr: true, - }, - "contract migration": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant) - }, - }, - "contract migration - duplicate grants": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant, *validGrant) - }, - }, - "contract migration - invalid grant": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization(*validGrant, *invalidGrant) - }, - expErr: true, - }, - "contract migration - empty grant": { - setup: func(t *testing.T) validatable { - return NewContractMigrationAuthorization() - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.setup(t).ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestAcceptGrantedMessage(t *testing.T) { - myContractAddr := sdk.AccAddress(randBytes(SDKAddrLen)) - otherContractAddr := sdk.AccAddress(randBytes(SDKAddrLen)) - specs := map[string]struct { - auth authztypes.Authorization - msg sdk.Msg - expResult authztypes.AcceptResponse - expErr *errorsmod.Error - }{ - "accepted and updated - contract execution": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(2), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{ - Accept: true, - Updated: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - }, - }, - "accepted and not updated - limit not touched": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxFundsLimit(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{Accept: true}, - }, - "accepted and removed - single": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{Accept: true, Delete: true}, - }, - "accepted and updated - multi, one removed": { - auth: NewContractExecutionAuthorization( - mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()), - mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()), - ), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{ - Accept: true, - Updated: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - }, - }, - "accepted and updated - multi, one updated": { - auth: NewContractExecutionAuthorization( - mustGrant(otherContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()), - mustGrant(myContractAddr, NewMaxFundsLimit(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2))), NewAcceptedMessageKeysFilter("bar")), - mustGrant(myContractAddr, NewCombinedLimit(2, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2))), NewAcceptedMessageKeysFilter("foo")), - ), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - }, - expResult: authztypes.AcceptResponse{ - Accept: true, - Updated: NewContractExecutionAuthorization( - mustGrant(otherContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()), - mustGrant(myContractAddr, NewMaxFundsLimit(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2))), NewAcceptedMessageKeysFilter("bar")), - mustGrant(myContractAddr, NewCombinedLimit(1, sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(1))), NewAcceptedMessageKeysFilter("foo")), - ), - }, - }, - "not accepted - no matching contract address": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{Accept: false}, - }, - "not accepted - max calls but tokens": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - }, - expResult: authztypes.AcceptResponse{Accept: false}, - }, - "not accepted - funds exceeds limit": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxFundsLimit(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(2))), - }, - expResult: authztypes.AcceptResponse{Accept: false}, - }, - "not accepted - no matching filter": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter("other"))), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.OneInt())), - }, - expResult: authztypes.AcceptResponse{Accept: false}, - }, - "invalid msg type - contract execution": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgMigrateContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - CodeID: 1, - Msg: []byte(`{"foo":"bar"}`), - }, - expErr: sdkerrors.ErrInvalidType, - }, - "payload is empty": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - }, - expErr: sdkerrors.ErrInvalidType, - }, - "payload is invalid": { - auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`not json`), - }, - expErr: ErrInvalid, - }, - "invalid grant": { - auth: NewContractExecutionAuthorization(ContractGrant{Contract: myContractAddr.String()}), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expErr: sdkerrors.ErrNotFound, - }, - "invalid msg type - contract migration": { - auth: NewContractMigrationAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - msg: &MsgExecuteContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - Msg: []byte(`{"foo":"bar"}`), - }, - expErr: sdkerrors.ErrInvalidType, - }, - "accepted and updated - contract migration": { - auth: NewContractMigrationAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(2), NewAllowAllMessagesFilter())), - msg: &MsgMigrateContract{ - Sender: sdk.AccAddress(randBytes(SDKAddrLen)).String(), - Contract: myContractAddr.String(), - CodeID: 1, - Msg: []byte(`{"foo":"bar"}`), - }, - expResult: authztypes.AcceptResponse{ - Accept: true, - Updated: NewContractMigrationAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(1), NewAllowAllMessagesFilter())), - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - ctx := sdk.Context{}.WithGasMeter(sdk.NewInfiniteGasMeter()) - gotResult, gotErr := spec.auth.Accept(ctx, spec.msg) - if spec.expErr != nil { - require.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expResult, gotResult) - }) - } -} - -func mustGrant(contract sdk.AccAddress, limit ContractAuthzLimitX, filter ContractAuthzFilterX) ContractGrant { - g, err := NewContractGrant(contract, limit, filter) - if err != nil { - panic(err) - } - return *g -} diff --git a/x/wasm/types/codec.go b/x/wasm/types/codec.go deleted file mode 100644 index 10ff3af..0000000 --- a/x/wasm/types/codec.go +++ /dev/null @@ -1,141 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" - "github.com/cosmos/cosmos-sdk/x/authz" - authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" - govcodec "github.com/cosmos/cosmos-sdk/x/gov/codec" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - groupcodec "github.com/cosmos/cosmos-sdk/x/group/codec" -) - -// RegisterLegacyAminoCodec registers the account types and interface -func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgStoreCode{}, "wasm/MsgStoreCode", nil) - cdc.RegisterConcrete(&MsgInstantiateContract{}, "wasm/MsgInstantiateContract", nil) - cdc.RegisterConcrete(&MsgInstantiateContract2{}, "wasm/MsgInstantiateContract2", nil) - cdc.RegisterConcrete(&MsgExecuteContract{}, "wasm/MsgExecuteContract", nil) - cdc.RegisterConcrete(&MsgMigrateContract{}, "wasm/MsgMigrateContract", nil) - cdc.RegisterConcrete(&MsgUpdateAdmin{}, "wasm/MsgUpdateAdmin", nil) - cdc.RegisterConcrete(&MsgClearAdmin{}, "wasm/MsgClearAdmin", nil) - cdc.RegisterConcrete(&MsgUpdateInstantiateConfig{}, "wasm/MsgUpdateInstantiateConfig", nil) - cdc.RegisterConcrete(&MsgUpdateParams{}, "wasm/MsgUpdateParams", nil) - cdc.RegisterConcrete(&MsgSudoContract{}, "wasm/MsgSudoContract", nil) - cdc.RegisterConcrete(&MsgPinCodes{}, "wasm/MsgPinCodes", nil) - cdc.RegisterConcrete(&MsgUnpinCodes{}, "wasm/MsgUnpinCodes", nil) - cdc.RegisterConcrete(&MsgStoreAndInstantiateContract{}, "wasm/MsgStoreAndInstantiateContract", nil) - - cdc.RegisterConcrete(&PinCodesProposal{}, "wasm/PinCodesProposal", nil) - cdc.RegisterConcrete(&UnpinCodesProposal{}, "wasm/UnpinCodesProposal", nil) - cdc.RegisterConcrete(&StoreCodeProposal{}, "wasm/StoreCodeProposal", nil) - cdc.RegisterConcrete(&InstantiateContractProposal{}, "wasm/InstantiateContractProposal", nil) - cdc.RegisterConcrete(&InstantiateContract2Proposal{}, "wasm/InstantiateContract2Proposal", nil) - cdc.RegisterConcrete(&MigrateContractProposal{}, "wasm/MigrateContractProposal", nil) - cdc.RegisterConcrete(&SudoContractProposal{}, "wasm/SudoContractProposal", nil) - cdc.RegisterConcrete(&ExecuteContractProposal{}, "wasm/ExecuteContractProposal", nil) - cdc.RegisterConcrete(&UpdateAdminProposal{}, "wasm/UpdateAdminProposal", nil) - cdc.RegisterConcrete(&ClearAdminProposal{}, "wasm/ClearAdminProposal", nil) - cdc.RegisterConcrete(&UpdateInstantiateConfigProposal{}, "wasm/UpdateInstantiateConfigProposal", nil) - cdc.RegisterConcrete(&StoreAndInstantiateContractProposal{}, "wasm/StoreAndInstantiateContractProposal", nil) - - cdc.RegisterInterface((*ContractInfoExtension)(nil), nil) - - cdc.RegisterInterface((*ContractAuthzFilterX)(nil), nil) - cdc.RegisterConcrete(&AllowAllMessagesFilter{}, "wasm/AllowAllMessagesFilter", nil) - cdc.RegisterConcrete(&AcceptedMessageKeysFilter{}, "wasm/AcceptedMessageKeysFilter", nil) - cdc.RegisterConcrete(&AcceptedMessagesFilter{}, "wasm/AcceptedMessagesFilter", nil) - - cdc.RegisterInterface((*ContractAuthzLimitX)(nil), nil) - cdc.RegisterConcrete(&MaxCallsLimit{}, "wasm/MaxCallsLimit", nil) - cdc.RegisterConcrete(&MaxFundsLimit{}, "wasm/MaxFundsLimit", nil) - cdc.RegisterConcrete(&CombinedLimit{}, "wasm/CombinedLimit", nil) - - cdc.RegisterConcrete(&ContractExecutionAuthorization{}, "wasm/ContractExecutionAuthorization", nil) - cdc.RegisterConcrete(&ContractMigrationAuthorization{}, "wasm/ContractMigrationAuthorization", nil) -} - -func RegisterInterfaces(registry types.InterfaceRegistry) { - registry.RegisterImplementations( - (*sdk.Msg)(nil), - &MsgStoreCode{}, - &MsgInstantiateContract{}, - &MsgInstantiateContract2{}, - &MsgExecuteContract{}, - &MsgMigrateContract{}, - &MsgUpdateAdmin{}, - &MsgClearAdmin{}, - &MsgIBCCloseChannel{}, - &MsgIBCSend{}, - &MsgUpdateInstantiateConfig{}, - &MsgUpdateParams{}, - &MsgSudoContract{}, - &MsgPinCodes{}, - &MsgUnpinCodes{}, - &MsgStoreAndInstantiateContract{}, - ) - registry.RegisterImplementations( - (*v1beta1.Content)(nil), - &StoreCodeProposal{}, - &InstantiateContractProposal{}, - &InstantiateContract2Proposal{}, - &MigrateContractProposal{}, - &SudoContractProposal{}, - &ExecuteContractProposal{}, - &UpdateAdminProposal{}, - &ClearAdminProposal{}, - &PinCodesProposal{}, - &UnpinCodesProposal{}, - &UpdateInstantiateConfigProposal{}, - &StoreAndInstantiateContractProposal{}, - ) - - registry.RegisterInterface("cosmwasm.wasm.v1.ContractInfoExtension", (*ContractInfoExtension)(nil)) - - registry.RegisterInterface("cosmwasm.wasm.v1.ContractAuthzFilterX", (*ContractAuthzFilterX)(nil)) - registry.RegisterImplementations( - (*ContractAuthzFilterX)(nil), - &AllowAllMessagesFilter{}, - &AcceptedMessageKeysFilter{}, - &AcceptedMessagesFilter{}, - ) - - registry.RegisterInterface("cosmwasm.wasm.v1.ContractAuthzLimitX", (*ContractAuthzLimitX)(nil)) - registry.RegisterImplementations( - (*ContractAuthzLimitX)(nil), - &MaxCallsLimit{}, - &MaxFundsLimit{}, - &CombinedLimit{}, - ) - - registry.RegisterImplementations( - (*authz.Authorization)(nil), - &ContractExecutionAuthorization{}, - &ContractMigrationAuthorization{}, - ) - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - amino = codec.NewLegacyAmino() - - // ModuleCdc references the global x/wasm module codec. - - ModuleCdc = codec.NewAminoCodec(amino) -) - -func init() { - RegisterLegacyAminoCodec(amino) - cryptocodec.RegisterCrypto(amino) - amino.Seal() - - // Register all Amino interfaces and concrete types on the authz and gov Amino codec so that this can later be - // used to properly serialize MsgGrant, MsgExec and MsgSubmitProposal instances - RegisterLegacyAminoCodec(authzcodec.Amino) - RegisterLegacyAminoCodec(govcodec.Amino) - RegisterLegacyAminoCodec(groupcodec.Amino) -} diff --git a/x/wasm/types/errors.go b/x/wasm/types/errors.go deleted file mode 100644 index 378c25d..0000000 --- a/x/wasm/types/errors.go +++ /dev/null @@ -1,150 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" -) - -// Codes for wasm contract errors -var ( - DefaultCodespace = ModuleName - - // Note: never use code 1 for any errors - that is reserved for ErrInternal in the core cosmos sdk - - // ErrCreateFailed error for wasm code that has already been uploaded or failed - ErrCreateFailed = errorsmod.Register(DefaultCodespace, 2, "create wasm contract failed") - - // ErrAccountExists error for a contract account that already exists - ErrAccountExists = errorsmod.Register(DefaultCodespace, 3, "contract account already exists") - - // ErrInstantiateFailed error for rust instantiate contract failure - ErrInstantiateFailed = errorsmod.Register(DefaultCodespace, 4, "instantiate wasm contract failed") - - // ErrExecuteFailed error for rust execution contract failure - ErrExecuteFailed = errorsmod.Register(DefaultCodespace, 5, "execute wasm contract failed") - - // ErrGasLimit error for out of gas - ErrGasLimit = errorsmod.Register(DefaultCodespace, 6, "insufficient gas") - - // ErrInvalidGenesis error for invalid genesis file syntax - ErrInvalidGenesis = errorsmod.Register(DefaultCodespace, 7, "invalid genesis") - - // ErrNotFound error for an entry not found in the store - ErrNotFound = errorsmod.Register(DefaultCodespace, 8, "not found") - - // ErrQueryFailed error for rust smart query contract failure - ErrQueryFailed = errorsmod.Register(DefaultCodespace, 9, "query wasm contract failed") - - // ErrInvalidMsg error when we cannot process the error returned from the contract - ErrInvalidMsg = errorsmod.Register(DefaultCodespace, 10, "invalid CosmosMsg from the contract") - - // ErrMigrationFailed error for rust execution contract failure - ErrMigrationFailed = errorsmod.Register(DefaultCodespace, 11, "migrate wasm contract failed") - - // ErrEmpty error for empty content - ErrEmpty = errorsmod.Register(DefaultCodespace, 12, "empty") - - // ErrLimit error for content that exceeds a limit - ErrLimit = errorsmod.Register(DefaultCodespace, 13, "exceeds limit") - - // ErrInvalid error for content that is invalid in this context - ErrInvalid = errorsmod.Register(DefaultCodespace, 14, "invalid") - - // ErrDuplicate error for content that exists - ErrDuplicate = errorsmod.Register(DefaultCodespace, 15, "duplicate") - - // ErrMaxIBCChannels error for maximum number of ibc channels reached - ErrMaxIBCChannels = errorsmod.Register(DefaultCodespace, 16, "max transfer channels") - - // ErrUnsupportedForContract error when a capability is used that is not supported for/ by this contract - ErrUnsupportedForContract = errorsmod.Register(DefaultCodespace, 17, "unsupported for this contract") - - // ErrPinContractFailed error for pinning contract failures - ErrPinContractFailed = errorsmod.Register(DefaultCodespace, 18, "pinning contract failed") - - // ErrUnpinContractFailed error for unpinning contract failures - ErrUnpinContractFailed = errorsmod.Register(DefaultCodespace, 19, "unpinning contract failed") - - // ErrUnknownMsg error by a message handler to show that it is not responsible for this message type - ErrUnknownMsg = errorsmod.Register(DefaultCodespace, 20, "unknown message from the contract") - - // ErrInvalidEvent error if an attribute/event from the contract is invalid - ErrInvalidEvent = errorsmod.Register(DefaultCodespace, 21, "invalid event") - - // ErrNoSuchContractFn error factory for an error when an address does not belong to a contract - ErrNoSuchContractFn = WasmVMFlavouredErrorFactory(errorsmod.Register(DefaultCodespace, 22, "no such contract"), - func(addr string) error { return wasmvmtypes.NoSuchContract{Addr: addr} }, - ) - - // code 23 -26 were used for json parser - - // ErrExceedMaxQueryStackSize error if max query stack size is exceeded - ErrExceedMaxQueryStackSize = errorsmod.Register(DefaultCodespace, 27, "max query stack size exceeded") - - // ErrNoSuchCodeFn factory for an error when a code id does not belong to a code info - ErrNoSuchCodeFn = WasmVMFlavouredErrorFactory(errorsmod.Register(DefaultCodespace, 28, "no such code"), - func(id uint64) error { return wasmvmtypes.NoSuchCode{CodeID: id} }, - ) -) - -// WasmVMErrorable mapped error type in wasmvm and are not redacted -type WasmVMErrorable interface { - // ToWasmVMError convert instance to wasmvm friendly error if possible otherwise root cause. never nil - ToWasmVMError() error -} - -var _ WasmVMErrorable = WasmVMFlavouredError{} - -// WasmVMFlavouredError wrapper for sdk error that supports wasmvm error types -type WasmVMFlavouredError struct { - sdkErr *errorsmod.Error - wasmVMErr error -} - -// NewWasmVMFlavouredError constructor -func NewWasmVMFlavouredError(sdkErr *errorsmod.Error, wasmVMErr error) WasmVMFlavouredError { - return WasmVMFlavouredError{sdkErr: sdkErr, wasmVMErr: wasmVMErr} -} - -// WasmVMFlavouredErrorFactory is a factory method to build a WasmVMFlavouredError type -func WasmVMFlavouredErrorFactory[T any](sdkErr *errorsmod.Error, wasmVMErrBuilder func(T) error) func(T) WasmVMFlavouredError { - if wasmVMErrBuilder == nil { - panic("builder function required") - } - return func(d T) WasmVMFlavouredError { - return WasmVMFlavouredError{sdkErr: sdkErr, wasmVMErr: wasmVMErrBuilder(d)} - } -} - -// ToWasmVMError implements WasmVMError-able -func (e WasmVMFlavouredError) ToWasmVMError() error { - if e.wasmVMErr != nil { - return e.wasmVMErr - } - return e.sdkErr -} - -// implements stdlib error -func (e WasmVMFlavouredError) Error() string { - return e.sdkErr.Error() -} - -// Unwrap implements the built-in errors.Unwrap -func (e WasmVMFlavouredError) Unwrap() error { - return e.sdkErr -} - -// Cause is the same as unwrap but used by errors.abci -func (e WasmVMFlavouredError) Cause() error { - return e.Unwrap() -} - -// Wrap extends this error with additional information. -// It's a handy function to call Wrap with sdk errors. -func (e WasmVMFlavouredError) Wrap(desc string) error { return errorsmod.Wrap(e, desc) } - -// Wrapf extends this error with additional information. -// It's a handy function to call Wrapf with sdk errors. -func (e WasmVMFlavouredError) Wrapf(desc string, args ...interface{}) error { - return errorsmod.Wrapf(e, desc, args...) -} diff --git a/x/wasm/types/errors_test.go b/x/wasm/types/errors_test.go deleted file mode 100644 index 495f5e8..0000000 --- a/x/wasm/types/errors_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package types - -import ( - "errors" - "testing" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestWasmVMFlavouredError(t *testing.T) { - myErr := ErrNoSuchCodeFn(1) - specs := map[string]struct { - exec func(t *testing.T) - }{ - "IsOf": { - exec: func(t *testing.T) { - assert.True(t, errorsmod.IsOf(myErr, myErr.sdkErr)) - assert.Equal(t, myErr.sdkErr, myErr.Unwrap()) - }, - }, - "unwrapped": { - exec: func(t *testing.T) { - assert.Equal(t, myErr.sdkErr, myErr.Unwrap()) - }, - }, - "caused": { - exec: func(t *testing.T) { - assert.Equal(t, myErr.sdkErr, myErr.Cause()) - }, - }, - "wrapped supports WasmVMErrorable": { - exec: func(t *testing.T) { - var wasmvmErr WasmVMErrorable - require.True(t, errors.As(myErr.Wrap("my description"), &wasmvmErr)) - gotErr := wasmvmErr.ToWasmVMError() - assert.Equal(t, wasmvmtypes.NoSuchCode{CodeID: 1}, gotErr) - }, - }, - "wrappedf supports WasmVMErrorable": { - exec: func(t *testing.T) { - var wasmvmErr WasmVMErrorable - require.True(t, errors.As(myErr.Wrapf("my description: %d", 1), &wasmvmErr)) - gotErr := wasmvmErr.ToWasmVMError() - assert.Equal(t, wasmvmtypes.NoSuchCode{CodeID: 1}, gotErr) - }, - }, - "supports WasmVMErrorable": { - exec: func(t *testing.T) { - var wasmvmErr WasmVMErrorable - require.True(t, errors.As(myErr, &wasmvmErr)) - gotErr := wasmvmErr.ToWasmVMError() - assert.Equal(t, wasmvmtypes.NoSuchCode{CodeID: 1}, gotErr) - }, - }, - "fallback to sdk error when wasmvm error unset": { - exec: func(t *testing.T) { - var wasmvmErr WasmVMErrorable - require.True(t, errors.As(WasmVMFlavouredError{sdkErr: ErrEmpty}, &wasmvmErr)) - gotErr := wasmvmErr.ToWasmVMError() - assert.Equal(t, ErrEmpty, gotErr) - }, - }, - "abci info": { - exec: func(t *testing.T) { - codespace, code, log := errorsmod.ABCIInfo(myErr, false) - assert.Equal(t, DefaultCodespace, codespace) - assert.Equal(t, uint32(28), code) - assert.Equal(t, "no such code", log) - }, - }, - "abci info - wrapped": { - exec: func(t *testing.T) { - codespace, code, log := errorsmod.ABCIInfo(myErr.Wrap("my description"), false) - assert.Equal(t, DefaultCodespace, codespace) - assert.Equal(t, uint32(28), code) - assert.Equal(t, "my description: no such code", log) - }, - }, - } - for name, spec := range specs { - t.Run(name, spec.exec) - } -} diff --git a/x/wasm/types/events.go b/x/wasm/types/events.go deleted file mode 100644 index 442c3ed..0000000 --- a/x/wasm/types/events.go +++ /dev/null @@ -1,34 +0,0 @@ -package types - -const ( - // WasmModuleEventType is stored with any contract TX that returns non empty EventAttributes - WasmModuleEventType = "wasm" - // CustomContractEventPrefix contracts can create custom events. To not mix them with other system events they got the `wasm-` prefix. - CustomContractEventPrefix = "wasm-" - - EventTypeStoreCode = "store_code" - EventTypeInstantiate = "instantiate" - EventTypeExecute = "execute" - EventTypeMigrate = "migrate" - EventTypePinCode = "pin_code" - EventTypeUnpinCode = "unpin_code" - EventTypeSudo = "sudo" - EventTypeReply = "reply" - EventTypeGovContractResult = "gov_contract_result" - EventTypeUpdateContractAdmin = "update_contract_admin" - EventTypeUpdateCodeAccessConfig = "update_code_access_config" -) - -// event attributes returned from contract execution -const ( - AttributeReservedPrefix = "_" - - AttributeKeyContractAddr = "_contract_address" - AttributeKeyCodeID = "code_id" - AttributeKeyChecksum = "code_checksum" - AttributeKeyResultDataHex = "result" - AttributeKeyRequiredCapability = "required_capability" - AttributeKeyNewAdmin = "new_admin_address" - AttributeKeyCodePermission = "code_permission" - AttributeKeyAuthorizedAddresses = "authorized_addresses" -) diff --git a/x/wasm/types/expected_keepers.go b/x/wasm/types/expected_keepers.go deleted file mode 100644 index e9b5227..0000000 --- a/x/wasm/types/expected_keepers.go +++ /dev/null @@ -1,118 +0,0 @@ -package types - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - clienttypes "github.com/cosmos/ibc-go/v7/modules/core/02-client/types" - connectiontypes "github.com/cosmos/ibc-go/v7/modules/core/03-connection/types" - channeltypes "github.com/cosmos/ibc-go/v7/modules/core/04-channel/types" - ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" -) - -// BankViewKeeper defines a subset of methods implemented by the cosmos-sdk bank keeper -type BankViewKeeper interface { - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - GetSupply(ctx sdk.Context, denom string) sdk.Coin -} - -// Burner is a subset of the sdk bank keeper methods -type Burner interface { - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error -} - -// BankKeeper defines a subset of methods implemented by the cosmos-sdk bank keeper -type BankKeeper interface { - BankViewKeeper - Burner - IsSendEnabledCoins(ctx sdk.Context, coins ...sdk.Coin) error - BlockedAddr(addr sdk.AccAddress) bool - SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error -} - -// AccountKeeper defines a subset of methods implemented by the cosmos-sdk account keeper -type AccountKeeper interface { - // Return a new account with the next account number and the specified address. Does not save the new account to the store. - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - // Retrieve an account from the store. - GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI - // Set an account in the store. - SetAccount(ctx sdk.Context, acc authtypes.AccountI) -} - -// DistributionKeeper defines a subset of methods implemented by the cosmos-sdk distribution keeper -type DistributionKeeper interface { - DelegationRewards(c context.Context, req *distrtypes.QueryDelegationRewardsRequest) (*distrtypes.QueryDelegationRewardsResponse, error) -} - -// StakingKeeper defines a subset of methods implemented by the cosmos-sdk staking keeper -type StakingKeeper interface { - // BondDenom - Bondable coin denomination - BondDenom(ctx sdk.Context) (res string) - // GetValidator get a single validator - GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - // GetBondedValidatorsByPower get the current group of bonded validators sorted by power-rank - GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator - // GetAllDelegatorDelegations return all delegations for a delegator - GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress) []stakingtypes.Delegation - // GetDelegation return a specific delegation - GetDelegation(ctx sdk.Context, - delAddr sdk.AccAddress, valAddr sdk.ValAddress) (delegation stakingtypes.Delegation, found bool) - // HasReceivingRedelegation check if validator is receiving a redelegation - HasReceivingRedelegation(ctx sdk.Context, - delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool -} - -// ChannelKeeper defines the expected IBC channel keeper -type ChannelKeeper interface { - GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) - - // SendPacket is called by a module in order to send an IBC packet on a channel. - // The packet sequence generated for the packet to be sent is returned. An error - // is returned if one occurs. - SendPacket( - ctx sdk.Context, - channelCap *capabilitytypes.Capability, - sourcePort string, - sourceChannel string, - timeoutHeight clienttypes.Height, - timeoutTimestamp uint64, - data []byte, - ) (uint64, error) - ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error - GetAllChannels(ctx sdk.Context) (channels []channeltypes.IdentifiedChannel) - IterateChannels(ctx sdk.Context, cb func(channeltypes.IdentifiedChannel) bool) - SetChannel(ctx sdk.Context, portID, channelID string, channel channeltypes.Channel) -} - -// ClientKeeper defines the expected IBC client keeper -type ClientKeeper interface { - GetClientConsensusState(ctx sdk.Context, clientID string) (connection ibcexported.ConsensusState, found bool) -} - -// ConnectionKeeper defines the expected IBC connection keeper -type ConnectionKeeper interface { - GetConnection(ctx sdk.Context, connectionID string) (connection connectiontypes.ConnectionEnd, found bool) -} - -// PortKeeper defines the expected IBC port keeper -type PortKeeper interface { - BindPort(ctx sdk.Context, portID string) *capabilitytypes.Capability -} - -type CapabilityKeeper interface { - GetCapability(ctx sdk.Context, name string) (*capabilitytypes.Capability, bool) - ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error - AuthenticateCapability(ctx sdk.Context, capability *capabilitytypes.Capability, name string) bool -} - -// ICS20TransferPortSource is a subset of the ibc transfer keeper. -type ICS20TransferPortSource interface { - GetPort(ctx sdk.Context) string -} diff --git a/x/wasm/types/exported_keepers.go b/x/wasm/types/exported_keepers.go deleted file mode 100644 index dcf97cb..0000000 --- a/x/wasm/types/exported_keepers.go +++ /dev/null @@ -1,119 +0,0 @@ -package types - -import ( - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" - capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" -) - -// ViewKeeper provides read only operations -type ViewKeeper interface { - GetContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress) []ContractCodeHistoryEntry - QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []byte) ([]byte, error) - QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key []byte) []byte - HasContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) bool - GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *ContractInfo - IterateContractInfo(ctx sdk.Context, cb func(sdk.AccAddress, ContractInfo) bool) - IterateContractsByCreator(ctx sdk.Context, creator sdk.AccAddress, cb func(address sdk.AccAddress) bool) - IterateContractsByCode(ctx sdk.Context, codeID uint64, cb func(address sdk.AccAddress) bool) - IterateContractState(ctx sdk.Context, contractAddress sdk.AccAddress, cb func(key, value []byte) bool) - GetCodeInfo(ctx sdk.Context, codeID uint64) *CodeInfo - IterateCodeInfos(ctx sdk.Context, cb func(uint64, CodeInfo) bool) - GetByteCode(ctx sdk.Context, codeID uint64) ([]byte, error) - IsPinnedCode(ctx sdk.Context, codeID uint64) bool - GetParams(ctx sdk.Context) Params -} - -// ContractOpsKeeper contains mutable operations on a contract. -type ContractOpsKeeper interface { - // Create uploads and compiles a WASM contract, returning a short identifier for the contract - Create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, instantiateAccess *AccessConfig) (codeID uint64, checksum []byte, err error) - - // Instantiate creates an instance of a WASM contract using the classic sequence based address generator - Instantiate( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - ) (sdk.AccAddress, []byte, error) - - // Instantiate2 creates an instance of a WASM contract using the predictable address generator - Instantiate2( - ctx sdk.Context, - codeID uint64, - creator, admin sdk.AccAddress, - initMsg []byte, - label string, - deposit sdk.Coins, - salt []byte, - fixMsg bool, - ) (sdk.AccAddress, []byte, error) - - // Execute executes the contract instance - Execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, msg []byte, coins sdk.Coins) ([]byte, error) - - // Migrate allows to upgrade a contract to a new code with data migration. - Migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newCodeID uint64, msg []byte) ([]byte, error) - - // Sudo allows to call privileged entry point of a contract. - Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte) ([]byte, error) - - // UpdateContractAdmin sets the admin value on the ContractInfo. It must be a valid address (use ClearContractAdmin to remove it) - UpdateContractAdmin(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress, newAdmin sdk.AccAddress) error - - // ClearContractAdmin sets the admin value on the ContractInfo to nil, to disable further migrations/ updates. - ClearContractAdmin(ctx sdk.Context, contractAddress sdk.AccAddress, caller sdk.AccAddress) error - - // PinCode pins the wasm contract in wasmvm cache - PinCode(ctx sdk.Context, codeID uint64) error - - // UnpinCode removes the wasm contract from wasmvm cache - UnpinCode(ctx sdk.Context, codeID uint64) error - - // SetContractInfoExtension updates the extension point data that is stored with the contract info - SetContractInfoExtension(ctx sdk.Context, contract sdk.AccAddress, extra ContractInfoExtension) error - - // SetAccessConfig updates the access config of a code id. - SetAccessConfig(ctx sdk.Context, codeID uint64, caller sdk.AccAddress, newConfig AccessConfig) error -} - -// IBCContractKeeper IBC lifecycle event handler -type IBCContractKeeper interface { - OnOpenChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelOpenMsg, - ) (string, error) - OnConnectChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelConnectMsg, - ) error - OnCloseChannel( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCChannelCloseMsg, - ) error - OnRecvPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketReceiveMsg, - ) ([]byte, error) - OnAckPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - acknowledgement wasmvmtypes.IBCPacketAckMsg, - ) error - OnTimeoutPacket( - ctx sdk.Context, - contractAddr sdk.AccAddress, - msg wasmvmtypes.IBCPacketTimeoutMsg, - ) error - // ClaimCapability allows the transfer module to claim a capability - // that IBC module passes to it - ClaimCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) error - // AuthenticateCapability wraps the scopedKeeper's AuthenticateCapability function - AuthenticateCapability(ctx sdk.Context, cap *capabilitytypes.Capability, name string) bool -} diff --git a/x/wasm/types/feature_flag.go b/x/wasm/types/feature_flag.go deleted file mode 100644 index 959252c..0000000 --- a/x/wasm/types/feature_flag.go +++ /dev/null @@ -1,4 +0,0 @@ -package types - -// Tests should not fail on gas consumption -const EnableGasVerification = true diff --git a/x/wasm/types/genesis.go b/x/wasm/types/genesis.go deleted file mode 100644 index 8a5a156..0000000 --- a/x/wasm/types/genesis.go +++ /dev/null @@ -1,102 +0,0 @@ -package types - -import ( - errorsmod "cosmossdk.io/errors" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func (s Sequence) ValidateBasic() error { - if len(s.IDKey) == 0 { - return errorsmod.Wrap(ErrEmpty, "id key") - } - return nil -} - -func (s GenesisState) ValidateBasic() error { - if err := s.Params.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "params") - } - for i := range s.Codes { - if err := s.Codes[i].ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "code: %d", i) - } - } - for i := range s.Contracts { - if err := s.Contracts[i].ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "contract: %d", i) - } - } - for i := range s.Sequences { - if err := s.Sequences[i].ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "sequence: %d", i) - } - } - - return nil -} - -func (c Code) ValidateBasic() error { - if c.CodeID == 0 { - return errorsmod.Wrap(ErrEmpty, "code id") - } - if err := c.CodeInfo.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "code info") - } - if err := validateWasmCode(c.CodeBytes, MaxProposalWasmSize); err != nil { - return errorsmod.Wrap(err, "code bytes") - } - return nil -} - -func (c Contract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(c.ContractAddress); err != nil { - return errorsmod.Wrap(err, "contract address") - } - if err := c.ContractInfo.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "contract info") - } - - if c.ContractInfo.Created == nil { - return errorsmod.Wrap(ErrInvalid, "created must not be empty") - } - for i := range c.ContractState { - if err := c.ContractState[i].ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "contract state %d", i) - } - } - if len(c.ContractCodeHistory) == 0 { - return ErrEmpty.Wrap("code history") - } - for i, v := range c.ContractCodeHistory { - if err := v.ValidateBasic(); err != nil { - return errorsmod.Wrapf(err, "code history element %d", i) - } - } - return nil -} - -// ValidateGenesis performs basic validation of supply genesis data returning an -// error for any failed validation criteria. -func ValidateGenesis(data GenesisState) error { - return data.ValidateBasic() -} - -var _ codectypes.UnpackInterfacesMessage = GenesisState{} - -// UnpackInterfaces implements codectypes.UnpackInterfaces -func (s GenesisState) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - for _, v := range s.Contracts { - if err := v.UnpackInterfaces(unpacker); err != nil { - return err - } - } - return nil -} - -var _ codectypes.UnpackInterfacesMessage = &Contract{} - -// UnpackInterfaces implements codectypes.UnpackInterfaces -func (c *Contract) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - return c.ContractInfo.UnpackInterfaces(unpacker) -} diff --git a/x/wasm/types/genesis.pb.go b/x/wasm/types/genesis.pb.go deleted file mode 100644 index 4a946b0..0000000 --- a/x/wasm/types/genesis.pb.go +++ /dev/null @@ -1,1420 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/genesis.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = 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 - genesis state of x/wasm -type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - Codes []Code `protobuf:"bytes,2,rep,name=codes,proto3" json:"codes,omitempty"` - Contracts []Contract `protobuf:"bytes,3,rep,name=contracts,proto3" json:"contracts,omitempty"` - Sequences []Sequence `protobuf:"bytes,4,rep,name=sequences,proto3" json:"sequences,omitempty"` -} - -func (m *GenesisState) Reset() { *m = GenesisState{} } -func (m *GenesisState) String() string { return proto.CompactTextString(m) } -func (*GenesisState) ProtoMessage() {} -func (*GenesisState) Descriptor() ([]byte, []int) { - return fileDescriptor_2ab3f539b23472a6, []int{0} -} - -func (m *GenesisState) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *GenesisState) XXX_Merge(src proto.Message) { - xxx_messageInfo_GenesisState.Merge(m, src) -} - -func (m *GenesisState) XXX_Size() int { - return m.Size() -} - -func (m *GenesisState) XXX_DiscardUnknown() { - xxx_messageInfo_GenesisState.DiscardUnknown(m) -} - -var xxx_messageInfo_GenesisState proto.InternalMessageInfo - -func (m *GenesisState) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -func (m *GenesisState) GetCodes() []Code { - if m != nil { - return m.Codes - } - return nil -} - -func (m *GenesisState) GetContracts() []Contract { - if m != nil { - return m.Contracts - } - return nil -} - -func (m *GenesisState) GetSequences() []Sequence { - if m != nil { - return m.Sequences - } - return nil -} - -// Code struct encompasses CodeInfo and CodeBytes -type Code struct { - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - CodeInfo CodeInfo `protobuf:"bytes,2,opt,name=code_info,json=codeInfo,proto3" json:"code_info"` - CodeBytes []byte `protobuf:"bytes,3,opt,name=code_bytes,json=codeBytes,proto3" json:"code_bytes,omitempty"` - // Pinned to wasmvm cache - Pinned bool `protobuf:"varint,4,opt,name=pinned,proto3" json:"pinned,omitempty"` -} - -func (m *Code) Reset() { *m = Code{} } -func (m *Code) String() string { return proto.CompactTextString(m) } -func (*Code) ProtoMessage() {} -func (*Code) Descriptor() ([]byte, []int) { - return fileDescriptor_2ab3f539b23472a6, []int{1} -} - -func (m *Code) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Code) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Code.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 *Code) XXX_Merge(src proto.Message) { - xxx_messageInfo_Code.Merge(m, src) -} - -func (m *Code) XXX_Size() int { - return m.Size() -} - -func (m *Code) XXX_DiscardUnknown() { - xxx_messageInfo_Code.DiscardUnknown(m) -} - -var xxx_messageInfo_Code proto.InternalMessageInfo - -func (m *Code) GetCodeID() uint64 { - if m != nil { - return m.CodeID - } - return 0 -} - -func (m *Code) GetCodeInfo() CodeInfo { - if m != nil { - return m.CodeInfo - } - return CodeInfo{} -} - -func (m *Code) GetCodeBytes() []byte { - if m != nil { - return m.CodeBytes - } - return nil -} - -func (m *Code) GetPinned() bool { - if m != nil { - return m.Pinned - } - return false -} - -// Contract struct encompasses ContractAddress, ContractInfo, and ContractState -type Contract struct { - ContractAddress string `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3" json:"contract_address,omitempty"` - ContractInfo ContractInfo `protobuf:"bytes,2,opt,name=contract_info,json=contractInfo,proto3" json:"contract_info"` - ContractState []Model `protobuf:"bytes,3,rep,name=contract_state,json=contractState,proto3" json:"contract_state"` - ContractCodeHistory []ContractCodeHistoryEntry `protobuf:"bytes,4,rep,name=contract_code_history,json=contractCodeHistory,proto3" json:"contract_code_history"` -} - -func (m *Contract) Reset() { *m = Contract{} } -func (m *Contract) String() string { return proto.CompactTextString(m) } -func (*Contract) ProtoMessage() {} -func (*Contract) Descriptor() ([]byte, []int) { - return fileDescriptor_2ab3f539b23472a6, []int{2} -} - -func (m *Contract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Contract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Contract.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 *Contract) XXX_Merge(src proto.Message) { - xxx_messageInfo_Contract.Merge(m, src) -} - -func (m *Contract) XXX_Size() int { - return m.Size() -} - -func (m *Contract) XXX_DiscardUnknown() { - xxx_messageInfo_Contract.DiscardUnknown(m) -} - -var xxx_messageInfo_Contract proto.InternalMessageInfo - -func (m *Contract) GetContractAddress() string { - if m != nil { - return m.ContractAddress - } - return "" -} - -func (m *Contract) GetContractInfo() ContractInfo { - if m != nil { - return m.ContractInfo - } - return ContractInfo{} -} - -func (m *Contract) GetContractState() []Model { - if m != nil { - return m.ContractState - } - return nil -} - -func (m *Contract) GetContractCodeHistory() []ContractCodeHistoryEntry { - if m != nil { - return m.ContractCodeHistory - } - return nil -} - -// Sequence key and value of an id generation counter -type Sequence struct { - IDKey []byte `protobuf:"bytes,1,opt,name=id_key,json=idKey,proto3" json:"id_key,omitempty"` - Value uint64 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *Sequence) Reset() { *m = Sequence{} } -func (m *Sequence) String() string { return proto.CompactTextString(m) } -func (*Sequence) ProtoMessage() {} -func (*Sequence) Descriptor() ([]byte, []int) { - return fileDescriptor_2ab3f539b23472a6, []int{3} -} - -func (m *Sequence) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Sequence) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Sequence.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 *Sequence) XXX_Merge(src proto.Message) { - xxx_messageInfo_Sequence.Merge(m, src) -} - -func (m *Sequence) XXX_Size() int { - return m.Size() -} - -func (m *Sequence) XXX_DiscardUnknown() { - xxx_messageInfo_Sequence.DiscardUnknown(m) -} - -var xxx_messageInfo_Sequence proto.InternalMessageInfo - -func (m *Sequence) GetIDKey() []byte { - if m != nil { - return m.IDKey - } - return nil -} - -func (m *Sequence) GetValue() uint64 { - if m != nil { - return m.Value - } - return 0 -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "cosmwasm.wasm.v1.GenesisState") - proto.RegisterType((*Code)(nil), "cosmwasm.wasm.v1.Code") - proto.RegisterType((*Contract)(nil), "cosmwasm.wasm.v1.Contract") - proto.RegisterType((*Sequence)(nil), "cosmwasm.wasm.v1.Sequence") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/genesis.proto", fileDescriptor_2ab3f539b23472a6) } - -var fileDescriptor_2ab3f539b23472a6 = []byte{ - // 568 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x93, 0x41, 0x6f, 0xd3, 0x30, - 0x14, 0xc7, 0x9b, 0xae, 0x0d, 0xad, 0x57, 0xd8, 0x30, 0x63, 0x44, 0xd5, 0x48, 0xab, 0x72, 0x29, - 0x13, 0x6b, 0xb4, 0x71, 0xe4, 0x44, 0x18, 0x1a, 0x65, 0x02, 0xa1, 0xec, 0xb6, 0x4b, 0x95, 0x26, - 0x6f, 0x5d, 0xb4, 0xc5, 0x0e, 0xb1, 0xdb, 0x91, 0x6f, 0xc1, 0xa7, 0x40, 0x1c, 0xb9, 0xf3, 0x05, - 0x76, 0x63, 0x47, 0x4e, 0x15, 0x6a, 0x0f, 0x48, 0x7c, 0x0a, 0x64, 0x3b, 0xc9, 0xa2, 0x76, 0xbd, - 0x58, 0xc9, 0x7b, 0xff, 0xf7, 0xf3, 0xf3, 0xdf, 0xcf, 0xc8, 0xf4, 0x28, 0x0b, 0xaf, 0x5c, 0x16, - 0x5a, 0x72, 0x99, 0xec, 0x5b, 0x23, 0x20, 0xc0, 0x02, 0xd6, 0x8b, 0x62, 0xca, 0x29, 0xde, 0xcc, - 0xf2, 0x3d, 0xb9, 0x4c, 0xf6, 0x9b, 0x5b, 0x23, 0x3a, 0xa2, 0x32, 0x69, 0x89, 0x2f, 0xa5, 0x6b, - 0xee, 0x2c, 0x71, 0x78, 0x12, 0x41, 0x4a, 0x69, 0x3e, 0x74, 0xc3, 0x80, 0x50, 0x4b, 0xae, 0x2a, - 0xd4, 0xf9, 0x55, 0x46, 0x8d, 0x23, 0xb5, 0xd5, 0x09, 0x77, 0x39, 0xe0, 0x57, 0x48, 0x8f, 0xdc, - 0xd8, 0x0d, 0x99, 0xa1, 0xb5, 0xb5, 0xee, 0xfa, 0x81, 0xd1, 0x5b, 0xdc, 0xba, 0xf7, 0x49, 0xe6, - 0xed, 0xfa, 0xf5, 0xb4, 0x55, 0xfa, 0xfe, 0xf7, 0xc7, 0xae, 0xe6, 0xa4, 0x25, 0xf8, 0x3d, 0xaa, - 0x7a, 0xd4, 0x07, 0x66, 0x94, 0xdb, 0x6b, 0xdd, 0xf5, 0x83, 0xed, 0xe5, 0xda, 0x37, 0xd4, 0x07, - 0x7b, 0x47, 0x54, 0xfe, 0x9b, 0xb6, 0x36, 0xa4, 0xf8, 0x05, 0x0d, 0x03, 0x0e, 0x61, 0xc4, 0x13, - 0x05, 0x53, 0x08, 0x7c, 0x8a, 0xea, 0x1e, 0x25, 0x3c, 0x76, 0x3d, 0xce, 0x8c, 0x35, 0xc9, 0x6b, - 0xde, 0xc5, 0x53, 0x12, 0xbb, 0x9d, 0x32, 0x1f, 0xe5, 0x45, 0x8b, 0xdc, 0x5b, 0x9c, 0x60, 0x33, - 0xf8, 0x3c, 0x06, 0xe2, 0x01, 0x33, 0x2a, 0xab, 0xd8, 0x27, 0xa9, 0xe4, 0x96, 0x9d, 0x17, 0x2d, - 0xb1, 0xf3, 0x4c, 0xe7, 0x9b, 0x86, 0x2a, 0xe2, 0x94, 0xf8, 0x19, 0xba, 0x27, 0x4e, 0x32, 0x08, - 0x7c, 0x69, 0x65, 0xc5, 0x46, 0xb3, 0x69, 0x4b, 0x17, 0xa9, 0xfe, 0xa1, 0xa3, 0x8b, 0x54, 0xdf, - 0xc7, 0xb6, 0x38, 0xa5, 0x10, 0x91, 0x33, 0x6a, 0x94, 0xa5, 0xe3, 0xcd, 0xbb, 0x5d, 0xeb, 0x93, - 0x33, 0x5a, 0xf4, 0xbc, 0xe6, 0xa5, 0x41, 0xfc, 0x14, 0x21, 0xc9, 0x18, 0x26, 0x1c, 0x84, 0x55, - 0x5a, 0xb7, 0xe1, 0x48, 0xaa, 0x2d, 0x02, 0x78, 0x1b, 0xe9, 0x51, 0x40, 0x08, 0xf8, 0x46, 0xa5, - 0xad, 0x75, 0x6b, 0x4e, 0xfa, 0xd7, 0xf9, 0x59, 0x46, 0xb5, 0xcc, 0x3e, 0xfc, 0x1c, 0x6d, 0x66, - 0xf6, 0x0c, 0x5c, 0xdf, 0x8f, 0x81, 0xa9, 0x01, 0xa8, 0x3b, 0x1b, 0x59, 0xfc, 0xb5, 0x0a, 0xe3, - 0x8f, 0xe8, 0x7e, 0x2e, 0x2d, 0xb4, 0x6d, 0xae, 0xbe, 0x9c, 0xc5, 0xd6, 0x1b, 0x5e, 0x21, 0x81, - 0xfb, 0xe8, 0x41, 0xce, 0x63, 0x62, 0x06, 0xd3, 0xdb, 0x7e, 0xb2, 0x0c, 0xfc, 0x40, 0x7d, 0xb8, - 0x2c, 0x92, 0xf2, 0x4e, 0xd4, 0xf0, 0x06, 0xe8, 0x71, 0x8e, 0x92, 0x96, 0x9c, 0x07, 0x8c, 0xd3, - 0x38, 0x49, 0xef, 0x78, 0x77, 0x75, 0x8b, 0xc2, 0xe1, 0x77, 0x4a, 0xfc, 0x96, 0xf0, 0x38, 0x29, - 0x6e, 0x92, 0x8f, 0x54, 0x41, 0xd4, 0xb1, 0x51, 0x2d, 0x9b, 0x0f, 0xdc, 0x46, 0x7a, 0xe0, 0x0f, - 0x2e, 0x20, 0x91, 0x96, 0x35, 0xec, 0xfa, 0x6c, 0xda, 0xaa, 0xf6, 0x0f, 0x8f, 0x21, 0x71, 0xaa, - 0x81, 0x7f, 0x0c, 0x09, 0xde, 0x42, 0xd5, 0x89, 0x7b, 0x39, 0x06, 0xe9, 0x55, 0xc5, 0x51, 0x3f, - 0xf6, 0xd1, 0xf5, 0xcc, 0xd4, 0x6e, 0x66, 0xa6, 0xf6, 0x67, 0x66, 0x6a, 0x5f, 0xe7, 0x66, 0xe9, - 0x66, 0x6e, 0x96, 0x7e, 0xcf, 0xcd, 0xd2, 0xe9, 0xde, 0x28, 0xe0, 0xe7, 0xe3, 0x61, 0xcf, 0xa3, - 0xa1, 0xc5, 0x21, 0x8e, 0x08, 0xf0, 0x2b, 0x1a, 0x5f, 0xc8, 0xef, 0x3d, 0x8f, 0xc6, 0x60, 0x7d, - 0x51, 0x2f, 0x5c, 0x3e, 0xef, 0xa1, 0x2e, 0x1f, 0xf3, 0xcb, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff, - 0x2e, 0x99, 0x42, 0xb2, 0x47, 0x04, 0x00, 0x00, -} - -func (m *GenesisState) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Sequences) > 0 { - for iNdEx := len(m.Sequences) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Sequences[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.Contracts) > 0 { - for iNdEx := len(m.Contracts) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Contracts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Codes) > 0 { - for iNdEx := len(m.Codes) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Codes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *Code) 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 *Code) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Code) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pinned { - i-- - if m.Pinned { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x20 - } - if len(m.CodeBytes) > 0 { - i -= len(m.CodeBytes) - copy(dAtA[i:], m.CodeBytes) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.CodeBytes))) - i-- - dAtA[i] = 0x1a - } - { - size, err := m.CodeInfo.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.CodeID != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Contract) 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 *Contract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Contract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.ContractCodeHistory) > 0 { - for iNdEx := len(m.ContractCodeHistory) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ContractCodeHistory[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if len(m.ContractState) > 0 { - for iNdEx := len(m.ContractState) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.ContractState[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - { - size, err := m.ContractInfo.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.ContractAddress) > 0 { - i -= len(m.ContractAddress) - copy(dAtA[i:], m.ContractAddress) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.ContractAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *Sequence) 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 *Sequence) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Sequence) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Value != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.Value)) - i-- - dAtA[i] = 0x10 - } - if len(m.IDKey) > 0 { - i -= len(m.IDKey) - copy(dAtA[i:], m.IDKey) - i = encodeVarintGenesis(dAtA, i, uint64(len(m.IDKey))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.Codes) > 0 { - for _, e := range m.Codes { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Contracts) > 0 { - for _, e := range m.Contracts { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.Sequences) > 0 { - for _, e := range m.Sequences { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Code) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovGenesis(uint64(m.CodeID)) - } - l = m.CodeInfo.Size() - n += 1 + l + sovGenesis(uint64(l)) - l = len(m.CodeBytes) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if m.Pinned { - n += 2 - } - return n -} - -func (m *Contract) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.ContractAddress) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - l = m.ContractInfo.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.ContractState) > 0 { - for _, e := range m.ContractState { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if len(m.ContractCodeHistory) > 0 { - for _, e := range m.ContractCodeHistory { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - return n -} - -func (m *Sequence) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.IDKey) - if l > 0 { - n += 1 + l + sovGenesis(uint64(l)) - } - if m.Value != 0 { - n += 1 + sovGenesis(uint64(m.Value)) - } - return n -} - -func sovGenesis(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozGenesis(x uint64) (n int) { - return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *GenesisState) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Codes", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Codes = append(m.Codes, Code{}) - if err := m.Codes[len(m.Codes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contracts", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contracts = append(m.Contracts, Contract{}) - if err := m.Contracts[len(m.Contracts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sequences", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sequences = append(m.Sequences, Sequence{}) - if err := m.Sequences[len(m.Sequences)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *Code) 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: Code: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Code: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeInfo", 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.CodeInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeBytes", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeBytes = append(m.CodeBytes[:0], dAtA[iNdEx:postIndex]...) - if m.CodeBytes == nil { - m.CodeBytes = []byte{} - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Pinned", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Pinned = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *Contract) 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: Contract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Contract: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ContractAddress = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractInfo", 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.ContractInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractState", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ContractState = append(m.ContractState, Model{}) - if err := m.ContractState[len(m.ContractState)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractCodeHistory", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ContractCodeHistory = append(m.ContractCodeHistory, ContractCodeHistoryEntry{}) - if err := m.ContractCodeHistory[len(m.ContractCodeHistory)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *Sequence) 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: Sequence: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Sequence: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IDKey", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenesis - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenesis - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IDKey = append(m.IDKey[:0], dAtA[iNdEx:postIndex]...) - if m.IDKey == nil { - m.IDKey = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - m.Value = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Value |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipGenesis(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenesis - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func 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/wasm/types/genesis_test.go b/x/wasm/types/genesis_test.go deleted file mode 100644 index 258528c..0000000 --- a/x/wasm/types/genesis_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package types - -import ( - "bytes" - "testing" - "time" - - "github.com/cometbft/cometbft/libs/rand" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const invalidAddress = "invalid address" - -func TestValidateGenesisState(t *testing.T) { - specs := map[string]struct { - srcMutator func(*GenesisState) - expError bool - }{ - "all good": { - srcMutator: func(s *GenesisState) {}, - }, - "params invalid": { - srcMutator: func(s *GenesisState) { - s.Params = Params{} - }, - expError: true, - }, - "codeinfo invalid": { - srcMutator: func(s *GenesisState) { - s.Codes[0].CodeInfo.CodeHash = nil - }, - expError: true, - }, - "contract invalid": { - srcMutator: func(s *GenesisState) { - s.Contracts[0].ContractAddress = invalidAddress - }, - expError: true, - }, - "sequence invalid": { - srcMutator: func(s *GenesisState) { - s.Sequences[0].IDKey = nil - }, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := GenesisFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestCodeValidateBasic(t *testing.T) { - specs := map[string]struct { - srcMutator func(*Code) - expError bool - }{ - "all good": {srcMutator: func(_ *Code) {}}, - "code id invalid": { - srcMutator: func(c *Code) { - c.CodeID = 0 - }, - expError: true, - }, - "codeinfo invalid": { - srcMutator: func(c *Code) { - c.CodeInfo.CodeHash = nil - }, - expError: true, - }, - "codeBytes empty": { - srcMutator: func(c *Code) { - c.CodeBytes = []byte{} - }, - expError: true, - }, - "codeBytes nil": { - srcMutator: func(c *Code) { - c.CodeBytes = nil - }, - expError: true, - }, - "codeBytes greater limit": { - srcMutator: func(c *Code) { - c.CodeBytes = bytes.Repeat([]byte{0x1}, MaxProposalWasmSize+1) - }, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := CodeFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestContractValidateBasic(t *testing.T) { - specs := map[string]struct { - srcMutator func(*Contract) - expError bool - }{ - "all good": {srcMutator: func(_ *Contract) {}}, - "contract address invalid": { - srcMutator: func(c *Contract) { - c.ContractAddress = invalidAddress - }, - expError: true, - }, - "contract info invalid": { - srcMutator: func(c *Contract) { - c.ContractInfo.Creator = invalidAddress - }, - expError: true, - }, - "contract with created set": { - srcMutator: func(c *Contract) { - c.ContractInfo.Created = &AbsoluteTxPosition{} - }, - expError: false, - }, - "contract state invalid": { - srcMutator: func(c *Contract) { - c.ContractState = append(c.ContractState, Model{}) - }, - expError: true, - }, - "contract history invalid": { - srcMutator: func(c *Contract) { - c.ContractCodeHistory = []ContractCodeHistoryEntry{{}} - }, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := ContractFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestGenesisContractInfoMarshalUnmarshal(t *testing.T) { - var myAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) - var myOtherAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) - anyPos := AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2} - - anyTime := time.Now().UTC() - // using gov proposal here as a random protobuf types as it contains an Any type inside for nested unpacking - myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "bar"}, 1, anyTime, anyTime) - require.NoError(t, err) - myExtension.TotalDeposit = nil - - src := NewContractInfo(1, myAddr, myOtherAddr, "bar", &anyPos) - err = src.SetExtension(&myExtension) - require.NoError(t, err) - - interfaceRegistry := types.NewInterfaceRegistry() - marshaler := codec.NewProtoCodec(interfaceRegistry) - RegisterInterfaces(interfaceRegistry) - // register proposal as extension type - interfaceRegistry.RegisterImplementations( - (*ContractInfoExtension)(nil), - &v1beta1.Proposal{}, - ) - // register gov types for nested Anys - v1beta1.RegisterInterfaces(interfaceRegistry) - - // when encode - gs := GenesisState{ - Contracts: []Contract{{ - ContractInfo: src, - }}, - } - - bz, err := marshaler.Marshal(&gs) - require.NoError(t, err) - // and decode - var destGs GenesisState - err = marshaler.Unmarshal(bz, &destGs) - require.NoError(t, err) - // then - require.Len(t, destGs.Contracts, 1) - dest := destGs.Contracts[0].ContractInfo - assert.Equal(t, src, dest) - // and sanity check nested any - var destExt v1beta1.Proposal - require.NoError(t, dest.ReadExtension(&destExt)) - assert.Equal(t, destExt.GetTitle(), "bar") -} diff --git a/x/wasm/types/iavl_range_test.go b/x/wasm/types/iavl_range_test.go deleted file mode 100644 index fd3297b..0000000 --- a/x/wasm/types/iavl_range_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package types - -import ( - "testing" - - dbm "github.com/cometbft/cometbft-db" - "github.com/cosmos/cosmos-sdk/store" - "github.com/cosmos/cosmos-sdk/store/iavl" - iavl2 "github.com/cosmos/iavl" - "github.com/stretchr/testify/require" -) - -// This is modeled close to -// https://github.com/CosmWasm/cosmwasm-plus/blob/f97a7de44b6a930fd1d5179ee6f95b786a532f32/packages/storage-plus/src/prefix.rs#L183 -// and designed to ensure the IAVL store handles bounds the same way as the mock storage we use in Rust contract tests -func TestIavlRangeBounds(t *testing.T) { - memdb := dbm.NewMemDB() - tree, err := iavl2.NewMutableTree(memdb, 50, false) - require.NoError(t, err) - kvstore := iavl.UnsafeNewStore(tree) - - // values to compare with - expected := []KV{ - {[]byte("bar"), []byte("1")}, - {[]byte("ra"), []byte("2")}, - {[]byte("zi"), []byte("3")}, - } - reversed := []KV{ - {[]byte("zi"), []byte("3")}, - {[]byte("ra"), []byte("2")}, - {[]byte("bar"), []byte("1")}, - } - - // set up test cases, like `ensure_proper_range_bounds` in `cw-storage-plus` - for _, kv := range expected { - kvstore.Set(kv.Key, kv.Value) - } - - cases := map[string]struct { - start []byte - end []byte - reverse bool - expected []KV - }{ - "all ascending": {nil, nil, false, expected}, - "ascending start inclusive": {[]byte("ra"), nil, false, expected[1:]}, - "ascending end exclusive": {nil, []byte("ra"), false, expected[:1]}, - "ascending both points": {[]byte("bar"), []byte("zi"), false, expected[:2]}, - - "all descending": {nil, nil, true, reversed}, - "descending start inclusive": {[]byte("ra"), nil, true, reversed[:2]}, // "zi", "ra" - "descending end inclusive": {nil, []byte("ra"), true, reversed[2:]}, // "bar" - "descending both points": {[]byte("bar"), []byte("zi"), true, reversed[1:]}, // "ra", "bar" - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - var iter store.Iterator - if tc.reverse { - iter = kvstore.ReverseIterator(tc.start, tc.end) - } else { - iter = kvstore.Iterator(tc.start, tc.end) - } - items := consume(iter) - require.Equal(t, tc.expected, items) - iter.Close() - }) - } -} - -type KV struct { - Key []byte - Value []byte -} - -func consume(itr store.Iterator) []KV { - var res []KV - for ; itr.Valid(); itr.Next() { - k, v := itr.Key(), itr.Value() - res = append(res, KV{k, v}) - } - return res -} diff --git a/x/wasm/types/ibc.pb.go b/x/wasm/types/ibc.pb.go deleted file mode 100644 index cf1b535..0000000 --- a/x/wasm/types/ibc.pb.go +++ /dev/null @@ -1,766 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/ibc.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = 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 - -// MsgIBCSend -type MsgIBCSend struct { - // the channel by which the packet will be sent - Channel string `protobuf:"bytes,2,opt,name=channel,proto3" json:"channel,omitempty" yaml:"source_channel"` - // Timeout height relative to the current block height. - // The timeout is disabled when set to 0. - TimeoutHeight uint64 `protobuf:"varint,4,opt,name=timeout_height,json=timeoutHeight,proto3" json:"timeout_height,omitempty" yaml:"timeout_height"` - // Timeout timestamp (in nanoseconds) relative to the current block timestamp. - // The timeout is disabled when set to 0. - TimeoutTimestamp uint64 `protobuf:"varint,5,opt,name=timeout_timestamp,json=timeoutTimestamp,proto3" json:"timeout_timestamp,omitempty" yaml:"timeout_timestamp"` - // Data is the payload to transfer. We must not make assumption what format or - // content is in here. - Data []byte `protobuf:"bytes,6,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgIBCSend) Reset() { *m = MsgIBCSend{} } -func (m *MsgIBCSend) String() string { return proto.CompactTextString(m) } -func (*MsgIBCSend) ProtoMessage() {} -func (*MsgIBCSend) Descriptor() ([]byte, []int) { - return fileDescriptor_af0d1c43ea53c4b9, []int{0} -} - -func (m *MsgIBCSend) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgIBCSend) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgIBCSend.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 *MsgIBCSend) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgIBCSend.Merge(m, src) -} - -func (m *MsgIBCSend) XXX_Size() int { - return m.Size() -} - -func (m *MsgIBCSend) XXX_DiscardUnknown() { - xxx_messageInfo_MsgIBCSend.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgIBCSend proto.InternalMessageInfo - -// MsgIBCSendResponse -type MsgIBCSendResponse struct { - // Sequence number of the IBC packet sent - Sequence uint64 `protobuf:"varint,1,opt,name=sequence,proto3" json:"sequence,omitempty"` -} - -func (m *MsgIBCSendResponse) Reset() { *m = MsgIBCSendResponse{} } -func (m *MsgIBCSendResponse) String() string { return proto.CompactTextString(m) } -func (*MsgIBCSendResponse) ProtoMessage() {} -func (*MsgIBCSendResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_af0d1c43ea53c4b9, []int{1} -} - -func (m *MsgIBCSendResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgIBCSendResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgIBCSendResponse.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 *MsgIBCSendResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgIBCSendResponse.Merge(m, src) -} - -func (m *MsgIBCSendResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgIBCSendResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgIBCSendResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgIBCSendResponse proto.InternalMessageInfo - -// MsgIBCCloseChannel port and channel need to be owned by the contract -type MsgIBCCloseChannel struct { - Channel string `protobuf:"bytes,2,opt,name=channel,proto3" json:"channel,omitempty" yaml:"source_channel"` -} - -func (m *MsgIBCCloseChannel) Reset() { *m = MsgIBCCloseChannel{} } -func (m *MsgIBCCloseChannel) String() string { return proto.CompactTextString(m) } -func (*MsgIBCCloseChannel) ProtoMessage() {} -func (*MsgIBCCloseChannel) Descriptor() ([]byte, []int) { - return fileDescriptor_af0d1c43ea53c4b9, []int{2} -} - -func (m *MsgIBCCloseChannel) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgIBCCloseChannel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgIBCCloseChannel.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 *MsgIBCCloseChannel) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgIBCCloseChannel.Merge(m, src) -} - -func (m *MsgIBCCloseChannel) XXX_Size() int { - return m.Size() -} - -func (m *MsgIBCCloseChannel) XXX_DiscardUnknown() { - xxx_messageInfo_MsgIBCCloseChannel.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgIBCCloseChannel proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgIBCSend)(nil), "cosmwasm.wasm.v1.MsgIBCSend") - proto.RegisterType((*MsgIBCSendResponse)(nil), "cosmwasm.wasm.v1.MsgIBCSendResponse") - proto.RegisterType((*MsgIBCCloseChannel)(nil), "cosmwasm.wasm.v1.MsgIBCCloseChannel") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/ibc.proto", fileDescriptor_af0d1c43ea53c4b9) } - -var fileDescriptor_af0d1c43ea53c4b9 = []byte{ - // 334 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x51, 0xc1, 0x4e, 0xf2, 0x40, - 0x10, 0xee, 0xfe, 0xe1, 0x47, 0xdd, 0xa8, 0xc1, 0x8d, 0x26, 0x95, 0x98, 0x85, 0xec, 0x89, 0x0b, - 0x54, 0xc2, 0xcd, 0x93, 0x81, 0x8b, 0xc4, 0x78, 0xa9, 0x9e, 0xbc, 0x90, 0xb2, 0x4c, 0xda, 0x46, - 0xba, 0x5b, 0xbb, 0x5b, 0x90, 0xb7, 0xf0, 0xb1, 0x38, 0x72, 0xf4, 0x44, 0xb4, 0xbc, 0x01, 0x4f, - 0x60, 0x58, 0x5a, 0x94, 0xab, 0x97, 0xd9, 0x6f, 0xbe, 0xef, 0x9b, 0xd9, 0xcc, 0x0c, 0xae, 0x72, - 0xa9, 0xa2, 0xa9, 0xa7, 0x22, 0xc7, 0x84, 0x49, 0xdb, 0x09, 0x87, 0xbc, 0x15, 0x27, 0x52, 0x4b, - 0x52, 0x29, 0xb4, 0x96, 0x09, 0x93, 0x76, 0xf5, 0xdc, 0x97, 0xbe, 0x34, 0xa2, 0xb3, 0x41, 0x5b, - 0x1f, 0xcb, 0x10, 0xc6, 0x0f, 0xca, 0xef, 0x77, 0x7b, 0x8f, 0x20, 0x46, 0xa4, 0x83, 0x0f, 0x78, - 0xe0, 0x09, 0x01, 0x63, 0xfb, 0x5f, 0x1d, 0x35, 0x8e, 0xba, 0x97, 0xeb, 0x65, 0xed, 0x62, 0xe6, - 0x45, 0xe3, 0x1b, 0xa6, 0x64, 0x9a, 0x70, 0x18, 0xe4, 0x3a, 0x73, 0x0b, 0x27, 0xb9, 0xc5, 0xa7, - 0x3a, 0x8c, 0x40, 0xa6, 0x7a, 0x10, 0x40, 0xe8, 0x07, 0xda, 0x2e, 0xd5, 0x51, 0xa3, 0xf4, 0xbb, - 0x76, 0x5f, 0x67, 0xee, 0x49, 0x4e, 0xdc, 0x99, 0x9c, 0xf4, 0xf1, 0x59, 0xe1, 0xd8, 0xbc, 0x4a, - 0x7b, 0x51, 0x6c, 0xff, 0x37, 0x4d, 0xae, 0xd6, 0xcb, 0x9a, 0xbd, 0xdf, 0x64, 0x67, 0x61, 0x6e, - 0x25, 0xe7, 0x9e, 0x0a, 0x8a, 0x10, 0x5c, 0x1a, 0x79, 0xda, 0xb3, 0xcb, 0x75, 0xd4, 0x38, 0x76, - 0x0d, 0x66, 0xd7, 0x98, 0xfc, 0xcc, 0xe8, 0x82, 0x8a, 0xa5, 0x50, 0x40, 0xaa, 0xf8, 0x50, 0xc1, - 0x6b, 0x0a, 0x82, 0x83, 0x8d, 0x36, 0x7f, 0xb9, 0xbb, 0x9c, 0xf5, 0x8b, 0x8a, 0xde, 0x58, 0x2a, - 0xe8, 0xe5, 0x83, 0xfe, 0x65, 0x3b, 0xdd, 0xfb, 0xf9, 0x17, 0xb5, 0xe6, 0x19, 0x45, 0x8b, 0x8c, - 0xa2, 0xcf, 0x8c, 0xa2, 0xf7, 0x15, 0xb5, 0x16, 0x2b, 0x6a, 0x7d, 0xac, 0xa8, 0xf5, 0xdc, 0xf4, - 0x43, 0x1d, 0xa4, 0xc3, 0x16, 0x97, 0x91, 0xa3, 0x21, 0x89, 0x05, 0xe8, 0xa9, 0x4c, 0x5e, 0x0c, - 0x6e, 0x72, 0x99, 0x80, 0xf3, 0xb6, 0xbd, 0xae, 0x9e, 0xc5, 0xa0, 0x86, 0x65, 0x73, 0xb5, 0xce, - 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0xba, 0x9b, 0x72, 0x2c, 0xfb, 0x01, 0x00, 0x00, -} - -func (m *MsgIBCSend) 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 *MsgIBCSend) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgIBCSend) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintIbc(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x32 - } - if m.TimeoutTimestamp != 0 { - i = encodeVarintIbc(dAtA, i, uint64(m.TimeoutTimestamp)) - i-- - dAtA[i] = 0x28 - } - if m.TimeoutHeight != 0 { - i = encodeVarintIbc(dAtA, i, uint64(m.TimeoutHeight)) - i-- - dAtA[i] = 0x20 - } - if len(m.Channel) > 0 { - i -= len(m.Channel) - copy(dAtA[i:], m.Channel) - i = encodeVarintIbc(dAtA, i, uint64(len(m.Channel))) - i-- - dAtA[i] = 0x12 - } - return len(dAtA) - i, nil -} - -func (m *MsgIBCSendResponse) 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 *MsgIBCSendResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgIBCSendResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Sequence != 0 { - i = encodeVarintIbc(dAtA, i, uint64(m.Sequence)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgIBCCloseChannel) 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 *MsgIBCCloseChannel) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgIBCCloseChannel) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Channel) > 0 { - i -= len(m.Channel) - copy(dAtA[i:], m.Channel) - i = encodeVarintIbc(dAtA, i, uint64(len(m.Channel))) - i-- - dAtA[i] = 0x12 - } - return len(dAtA) - i, nil -} - -func encodeVarintIbc(dAtA []byte, offset int, v uint64) int { - offset -= sovIbc(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *MsgIBCSend) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Channel) - if l > 0 { - n += 1 + l + sovIbc(uint64(l)) - } - if m.TimeoutHeight != 0 { - n += 1 + sovIbc(uint64(m.TimeoutHeight)) - } - if m.TimeoutTimestamp != 0 { - n += 1 + sovIbc(uint64(m.TimeoutTimestamp)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovIbc(uint64(l)) - } - return n -} - -func (m *MsgIBCSendResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Sequence != 0 { - n += 1 + sovIbc(uint64(m.Sequence)) - } - return n -} - -func (m *MsgIBCCloseChannel) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Channel) - if l > 0 { - n += 1 + l + sovIbc(uint64(l)) - } - return n -} - -func sovIbc(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozIbc(x uint64) (n int) { - return sovIbc(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *MsgIBCSend) 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 ErrIntOverflowIbc - } - 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: MsgIBCSend: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgIBCSend: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Channel", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - 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 ErrInvalidLengthIbc - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthIbc - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Channel = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeoutHeight", wireType) - } - m.TimeoutHeight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TimeoutHeight |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TimeoutTimestamp", wireType) - } - m.TimeoutTimestamp = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TimeoutTimestamp |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthIbc - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthIbc - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipIbc(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIbc - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgIBCSendResponse) 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 ErrIntOverflowIbc - } - 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: MsgIBCSendResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgIBCSendResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) - } - m.Sequence = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Sequence |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipIbc(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIbc - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgIBCCloseChannel) 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 ErrIntOverflowIbc - } - 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: MsgIBCCloseChannel: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgIBCCloseChannel: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Channel", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowIbc - } - 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 ErrInvalidLengthIbc - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthIbc - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Channel = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipIbc(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIbc - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipIbc(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, ErrIntOverflowIbc - } - 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, ErrIntOverflowIbc - } - 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, ErrIntOverflowIbc - } - 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, ErrInvalidLengthIbc - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupIbc - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthIbc - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthIbc = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowIbc = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupIbc = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/json_matching.go b/x/wasm/types/json_matching.go deleted file mode 100644 index 34ff76d..0000000 --- a/x/wasm/types/json_matching.go +++ /dev/null @@ -1,34 +0,0 @@ -package types - -import ( - "encoding/json" -) - -// isJSONObjectWithTopLevelKey returns true if the given bytes are a valid JSON object -// with exactly one top-level key that is contained in the list of allowed keys. -func isJSONObjectWithTopLevelKey(jsonBytes RawContractMessage, allowedKeys []string) (bool, error) { - if err := jsonBytes.ValidateBasic(); err != nil { - return false, err - } - - document := map[string]interface{}{} - if err := json.Unmarshal(jsonBytes, &document); err != nil { - return false, nil // not a map - } - - if len(document) != 1 { - return false, nil // unsupported type - } - - // Loop is executed exactly once - for topLevelKey := range document { - for _, allowedKey := range allowedKeys { - if allowedKey == topLevelKey { - return true, nil - } - } - return false, nil - } - - panic("Reached unreachable code. This is a bug.") -} diff --git a/x/wasm/types/json_matching_test.go b/x/wasm/types/json_matching_test.go deleted file mode 100644 index 286fde3..0000000 --- a/x/wasm/types/json_matching_test.go +++ /dev/null @@ -1,134 +0,0 @@ -package types - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" - - // sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" -) - -func TestIsJSONObjectWithTopLevelKey(t *testing.T) { - specs := map[string]struct { - src []byte - allowedKeys []string - expResult bool - expErr error - }{ - "happy": { - src: []byte(`{"msg": {"foo":"bar"}}`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with many allowed keys 1": { - src: []byte(`{"claim": {"foo":"bar"}}`), - allowedKeys: []string{"claim", "swap", "burn", "mint"}, - expResult: true, - }, - "happy with many allowed keys 2": { - src: []byte(`{"burn": {"foo":"bar"}}`), - allowedKeys: []string{"claim", "swap", "burn", "mint"}, - expResult: true, - }, - "happy with many allowed keys 3": { - src: []byte(`{"mint": {"foo":"bar"}}`), - allowedKeys: []string{"claim", "swap", "burn", "mint"}, - expResult: true, - }, - "happy with number": { - src: []byte(`{"msg": 123}`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with array": { - src: []byte(`{"msg": [1, 2, 3, 4]}`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with null": { - src: []byte(`{"msg": null}`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with whitespace": { - src: []byte(`{ - "msg": null }`), - allowedKeys: []string{"msg"}, - expResult: true, - }, - "happy with escaped key": { - src: []byte(`{"event\u2468thing": {"foo":"bar"}}`), - allowedKeys: []string{"event⑨thing"}, - expResult: true, - }, - - // Invalid JSON object - "errors for bytes that are no JSON": { - src: []byte(`nope`), - allowedKeys: []string{"claim"}, - expErr: ErrInvalid, - }, - "false for valid JSON (string)": { - src: []byte(`"nope"`), - allowedKeys: []string{"claim"}, - expResult: false, - }, - "false for valid JSON (array)": { - src: []byte(`[1, 2, 3]`), - allowedKeys: []string{"claim"}, - expResult: false, - }, - // not supported: https://github.com/golang/go/issues/24415 - // "errors for duplicate key": { - // src: []byte(`{"claim": "foo", "claim":"bar"}`), - // allowedKeys: []string{"claim"}, - // expErr: ErrNotAJSONObject, - // }, - - // Not one top-level key - "false for no top-level key": { - src: []byte(`{}`), - allowedKeys: []string{"claim"}, - expResult: false, - }, - "false for multiple top-level keys": { - src: []byte(`{"claim": {}, "and_swap": {}}`), - allowedKeys: []string{"claim"}, - expResult: false, - }, - - // Wrong top-level key - "wrong top-level key 1": { - src: []byte(`{"claim": {}}`), - allowedKeys: []string{""}, - expResult: false, - }, - "wrong top-level key 2": { - src: []byte(`{"claim": {}}`), - allowedKeys: []string{"swap", "burn", "mint"}, - expResult: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - exists, gotErr := isJSONObjectWithTopLevelKey(spec.src, spec.allowedKeys) - if spec.expErr != nil { - assert.ErrorIs(t, gotErr, spec.expErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expResult, exists) - }) - } -} - -func TestDuplicateKeyGivesSameResult(t *testing.T) { - jsonBytes := []byte(`{"event⑨thing": "foo", "event⑨thing":"bar"}`) - for i := 0; i < 10000; i++ { - document := map[string]interface{}{} - require.NoError(t, json.Unmarshal(jsonBytes, &document)) - assert.Equal(t, "bar", document["event⑨thing"]) - } -} diff --git a/x/wasm/types/keys.go b/x/wasm/types/keys.go deleted file mode 100644 index 4f60587..0000000 --- a/x/wasm/types/keys.go +++ /dev/null @@ -1,131 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/address" -) - -const ( - // ModuleName is the name of the contract module - ModuleName = "wasm" - - // StoreKey is the string store representation - StoreKey = ModuleName - - // TStoreKey is the string transient store representation - TStoreKey = "transient_" + ModuleName - - // QuerierRoute is the querier route for the wasm module - QuerierRoute = ModuleName - - // RouterKey is the msg router key for the wasm module - RouterKey = ModuleName -) - -var ( - CodeKeyPrefix = []byte{0x01} - ContractKeyPrefix = []byte{0x02} - ContractStorePrefix = []byte{0x03} - SequenceKeyPrefix = []byte{0x04} - ContractCodeHistoryElementPrefix = []byte{0x05} - ContractByCodeIDAndCreatedSecondaryIndexPrefix = []byte{0x06} - PinnedCodeIndexPrefix = []byte{0x07} - TXCounterPrefix = []byte{0x08} - ContractsByCreatorPrefix = []byte{0x09} - ParamsKey = []byte{0x10} - - KeyLastCodeID = append(SequenceKeyPrefix, []byte("lastCodeId")...) - KeyLastInstanceID = append(SequenceKeyPrefix, []byte("lastContractId")...) -) - -// GetCodeKey constructs the key for retreiving the ID for the WASM code -func GetCodeKey(codeID uint64) []byte { - contractIDBz := sdk.Uint64ToBigEndian(codeID) - return append(CodeKeyPrefix, contractIDBz...) -} - -// GetContractAddressKey returns the key for the WASM contract instance -func GetContractAddressKey(addr sdk.AccAddress) []byte { - return append(ContractKeyPrefix, addr...) -} - -// GetContractsByCreatorPrefix returns the contracts by creator prefix for the WASM contract instance -func GetContractsByCreatorPrefix(addr sdk.AccAddress) []byte { - bz := address.MustLengthPrefix(addr) - return append(ContractsByCreatorPrefix, bz...) -} - -// GetContractStorePrefix returns the store prefix for the WASM contract instance -func GetContractStorePrefix(addr sdk.AccAddress) []byte { - return append(ContractStorePrefix, addr...) -} - -// GetContractByCreatedSecondaryIndexKey returns the key for the secondary index: -// `` -func GetContractByCreatedSecondaryIndexKey(contractAddr sdk.AccAddress, c ContractCodeHistoryEntry) []byte { - prefix := GetContractByCodeIDSecondaryIndexPrefix(c.CodeID) - prefixLen := len(prefix) - contractAddrLen := len(contractAddr) - r := make([]byte, prefixLen+AbsoluteTxPositionLen+contractAddrLen) - copy(r[0:], prefix) - copy(r[prefixLen:], c.Updated.Bytes()) - copy(r[prefixLen+AbsoluteTxPositionLen:], contractAddr) - return r -} - -// GetContractByCodeIDSecondaryIndexPrefix returns the prefix for the second index: `` -func GetContractByCodeIDSecondaryIndexPrefix(codeID uint64) []byte { - prefixLen := len(ContractByCodeIDAndCreatedSecondaryIndexPrefix) - const codeIDLen = 8 - r := make([]byte, prefixLen+codeIDLen) - copy(r[0:], ContractByCodeIDAndCreatedSecondaryIndexPrefix) - copy(r[prefixLen:], sdk.Uint64ToBigEndian(codeID)) - return r -} - -// GetContractByCreatorSecondaryIndexKey returns the key for the second index: `` -func GetContractByCreatorSecondaryIndexKey(bz []byte, position []byte, contractAddr sdk.AccAddress) []byte { - prefixBytes := GetContractsByCreatorPrefix(bz) - lenPrefixBytes := len(prefixBytes) - r := make([]byte, lenPrefixBytes+AbsoluteTxPositionLen+len(contractAddr)) - - copy(r[:lenPrefixBytes], prefixBytes) - copy(r[lenPrefixBytes:lenPrefixBytes+AbsoluteTxPositionLen], position) - copy(r[lenPrefixBytes+AbsoluteTxPositionLen:], contractAddr) - - return r -} - -// GetContractCodeHistoryElementKey returns the key a contract code history entry: `` -func GetContractCodeHistoryElementKey(contractAddr sdk.AccAddress, pos uint64) []byte { - prefix := GetContractCodeHistoryElementPrefix(contractAddr) - prefixLen := len(prefix) - r := make([]byte, prefixLen+8) - copy(r[0:], prefix) - copy(r[prefixLen:], sdk.Uint64ToBigEndian(pos)) - return r -} - -// GetContractCodeHistoryElementPrefix returns the key prefix for a contract code history entry: `` -func GetContractCodeHistoryElementPrefix(contractAddr sdk.AccAddress) []byte { - prefixLen := len(ContractCodeHistoryElementPrefix) - contractAddrLen := len(contractAddr) - r := make([]byte, prefixLen+contractAddrLen) - copy(r[0:], ContractCodeHistoryElementPrefix) - copy(r[prefixLen:], contractAddr) - return r -} - -// GetPinnedCodeIndexPrefix returns the key prefix for a code id pinned into the wasmvm cache -func GetPinnedCodeIndexPrefix(codeID uint64) []byte { - prefixLen := len(PinnedCodeIndexPrefix) - r := make([]byte, prefixLen+8) - copy(r[0:], PinnedCodeIndexPrefix) - copy(r[prefixLen:], sdk.Uint64ToBigEndian(codeID)) - return r -} - -// ParsePinnedCodeIndex converts the serialized code ID back. -func ParsePinnedCodeIndex(s []byte) uint64 { - return sdk.BigEndianToUint64(s) -} diff --git a/x/wasm/types/keys_test.go b/x/wasm/types/keys_test.go deleted file mode 100644 index a5cbce7..0000000 --- a/x/wasm/types/keys_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package types - -import ( - "bytes" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGetContractByCodeIDSecondaryIndexPrefix(t *testing.T) { - specs := map[string]struct { - src uint64 - exp []byte - }{ - "small number": { - src: 1, - exp: []byte{6, 0, 0, 0, 0, 0, 0, 0, 1}, - }, - "big number": { - src: 1 << (8 * 7), - exp: []byte{6, 1, 0, 0, 0, 0, 0, 0, 0}, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got := GetContractByCodeIDSecondaryIndexPrefix(spec.src) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestGetContractCodeHistoryElementPrefix(t *testing.T) { - // test that contract addresses of 20 length are still supported - addr := bytes.Repeat([]byte{4}, 20) - got := GetContractCodeHistoryElementPrefix(addr) - exp := []byte{ - 5, // prefix - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 20 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - } - assert.Equal(t, exp, got) - - addr = bytes.Repeat([]byte{4}, ContractAddrLen) - got = GetContractCodeHistoryElementPrefix(addr) - exp = []byte{ - 5, // prefix - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, - } - assert.Equal(t, exp, got) -} - -func TestGetContractByCreatedSecondaryIndexKey(t *testing.T) { - e := ContractCodeHistoryEntry{ - CodeID: 1, - Updated: &AbsoluteTxPosition{2 + 1<<(8*7), 3 + 1<<(8*7)}, - } - - // test that contract addresses of 20 length are still supported - addr := bytes.Repeat([]byte{4}, 20) - got := GetContractByCreatedSecondaryIndexKey(addr, e) - exp := []byte{ - 6, // prefix - 0, 0, 0, 0, 0, 0, 0, 1, // codeID - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - } - assert.Equal(t, exp, got) - - addr = bytes.Repeat([]byte{4}, ContractAddrLen) - got = GetContractByCreatedSecondaryIndexKey(addr, e) - exp = []byte{ - 6, // prefix - 0, 0, 0, 0, 0, 0, 0, 1, // codeID - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, - } - assert.Equal(t, exp, got) -} - -func TestGetContractByCreatorSecondaryIndexKey(t *testing.T) { - creatorAddr := bytes.Repeat([]byte{4}, 20) - e := ContractCodeHistoryEntry{ - CodeID: 1, - Updated: &AbsoluteTxPosition{2 + 1<<(8*7), 3 + 1<<(8*7)}, - } - - // test that contract addresses of 20 length are still supported - contractAddr := bytes.Repeat([]byte{4}, 20) - got := GetContractByCreatorSecondaryIndexKey(creatorAddr, e.Updated.Bytes(), contractAddr) - exp := []byte{ - 9, // prefix - 20, // creator address length - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // creator address with fixed length prefix - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 20 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - } - assert.Equal(t, exp, got) - - // test that contract addresses of 32 length are still supported - contractAddr = bytes.Repeat([]byte{4}, 32) - got = GetContractByCreatorSecondaryIndexKey(creatorAddr, e.Updated.Bytes(), contractAddr) - exp = []byte{ - 9, // prefix - 20, // creator address length - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // creator address with fixed length prefix - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, - } - assert.Equal(t, exp, got) - - // test that creator is contract addresses of 32 length - contractAddr = bytes.Repeat([]byte{4}, 32) - creatorAddr = bytes.Repeat([]byte{8}, 32) - got = GetContractByCreatorSecondaryIndexKey(creatorAddr, e.Updated.Bytes(), contractAddr) - exp = []byte{ - 9, // prefix - 32, // creator address length - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, // creator address is a contract address - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, - 1, 0, 0, 0, 0, 0, 0, 2, // height - 1, 0, 0, 0, 0, 0, 0, 3, // index - - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, // address 32 bytes - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, - } - assert.Equal(t, exp, got) -} diff --git a/x/wasm/types/params.go b/x/wasm/types/params.go deleted file mode 100644 index d06ba7e..0000000 --- a/x/wasm/types/params.go +++ /dev/null @@ -1,208 +0,0 @@ -package types - -import ( - "encoding/json" - "fmt" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/gogoproto/jsonpb" - "github.com/pkg/errors" - "gopkg.in/yaml.v2" -) - -var AllAccessTypes = []AccessType{ - AccessTypeNobody, - AccessTypeOnlyAddress, - AccessTypeAnyOfAddresses, - AccessTypeEverybody, -} - -func (a AccessType) With(addrs ...sdk.AccAddress) AccessConfig { - switch a { - case AccessTypeNobody: - return AllowNobody - case AccessTypeOnlyAddress: - if n := len(addrs); n != 1 { - panic(fmt.Sprintf("expected exactly 1 address but got %d", n)) - } - if err := sdk.VerifyAddressFormat(addrs[0]); err != nil { - panic(err) - } - return AccessConfig{Permission: AccessTypeOnlyAddress, Address: addrs[0].String()} - case AccessTypeEverybody: - return AllowEverybody - case AccessTypeAnyOfAddresses: - bech32Addrs := make([]string, len(addrs)) - for i, v := range addrs { - bech32Addrs[i] = v.String() - } - if err := assertValidAddresses(bech32Addrs); err != nil { - panic(errorsmod.Wrap(err, "addresses")) - } - return AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: bech32Addrs} - } - panic("unsupported access type") -} - -func (a AccessType) String() string { - switch a { - case AccessTypeNobody: - return "Nobody" - case AccessTypeOnlyAddress: - return "OnlyAddress" - case AccessTypeEverybody: - return "Everybody" - case AccessTypeAnyOfAddresses: - return "AnyOfAddresses" - } - return "Unspecified" -} - -func (a *AccessType) UnmarshalText(text []byte) error { - for _, v := range AllAccessTypes { - if v.String() == string(text) { - *a = v - return nil - } - } - *a = AccessTypeUnspecified - return nil -} - -func (a AccessType) MarshalText() ([]byte, error) { - return []byte(a.String()), nil -} - -func (a *AccessType) MarshalJSONPB(_ *jsonpb.Marshaler) ([]byte, error) { - return json.Marshal(a) -} - -func (a *AccessType) UnmarshalJSONPB(_ *jsonpb.Unmarshaler, data []byte) error { - return json.Unmarshal(data, a) -} - -func (a AccessConfig) Equals(o AccessConfig) bool { - return a.Permission == o.Permission && a.Address == o.Address -} - -var ( - DefaultUploadAccess = AllowEverybody - AllowEverybody = AccessConfig{Permission: AccessTypeEverybody} - AllowNobody = AccessConfig{Permission: AccessTypeNobody} -) - -// DefaultParams returns default wasm parameters -func DefaultParams() Params { - return Params{ - CodeUploadAccess: AllowEverybody, - InstantiateDefaultPermission: AccessTypeEverybody, - } -} - -func (p Params) String() string { - out, err := yaml.Marshal(p) - if err != nil { - panic(err) - } - return string(out) -} - -// ValidateBasic performs basic validation on wasm parameters -func (p Params) ValidateBasic() error { - if err := validateAccessType(p.InstantiateDefaultPermission); err != nil { - return errors.Wrap(err, "instantiate default permission") - } - if err := validateAccessConfig(p.CodeUploadAccess); err != nil { - return errors.Wrap(err, "upload access") - } - return nil -} - -func validateAccessConfig(i interface{}) error { - v, ok := i.(AccessConfig) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - return v.ValidateBasic() -} - -func validateAccessType(i interface{}) error { - a, ok := i.(AccessType) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - if a == AccessTypeUnspecified { - return errorsmod.Wrap(ErrEmpty, "type") - } - for _, v := range AllAccessTypes { - if v == a { - return nil - } - } - return errorsmod.Wrapf(ErrInvalid, "unknown type: %q", a) -} - -// ValidateBasic performs basic validation -func (a AccessConfig) ValidateBasic() error { - switch a.Permission { - case AccessTypeUnspecified: - return errorsmod.Wrap(ErrEmpty, "type") - case AccessTypeNobody, AccessTypeEverybody: - if len(a.Address) != 0 { - return errorsmod.Wrap(ErrInvalid, "address not allowed for this type") - } - return nil - case AccessTypeOnlyAddress: - if len(a.Addresses) != 0 { - return ErrInvalid.Wrap("addresses field set") - } - _, err := sdk.AccAddressFromBech32(a.Address) - return err - case AccessTypeAnyOfAddresses: - if a.Address != "" { - return ErrInvalid.Wrap("address field set") - } - return errorsmod.Wrap(assertValidAddresses(a.Addresses), "addresses") - } - return errorsmod.Wrapf(ErrInvalid, "unknown type: %q", a.Permission) -} - -func assertValidAddresses(addrs []string) error { - if len(addrs) == 0 { - return ErrEmpty - } - idx := make(map[string]struct{}, len(addrs)) - for _, a := range addrs { - if _, err := sdk.AccAddressFromBech32(a); err != nil { - return errorsmod.Wrapf(err, "address: %s", a) - } - if _, exists := idx[a]; exists { - return ErrDuplicate.Wrapf("address: %s", a) - } - idx[a] = struct{}{} - } - return nil -} - -// Allowed returns if permission includes the actor. -// Actor address must be valid and not nil -func (a AccessConfig) Allowed(actor sdk.AccAddress) bool { - switch a.Permission { - case AccessTypeNobody: - return false - case AccessTypeEverybody: - return true - case AccessTypeOnlyAddress: - return a.Address == actor.String() - case AccessTypeAnyOfAddresses: - for _, v := range a.Addresses { - if v == actor.String() { - return true - } - } - return false - default: - panic("unknown type") - } -} diff --git a/x/wasm/types/params_legacy.go b/x/wasm/types/params_legacy.go deleted file mode 100644 index db38cb8..0000000 --- a/x/wasm/types/params_legacy.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -NOTE: Usage of x/params to manage parameters is deprecated in favor of x/gov -controlled execution of MsgUpdateParams messages. These types remains solely -for migration purposes and will be removed in a future release. -*/ -package types - -import paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - -var ( - ParamStoreKeyUploadAccess = []byte("uploadAccess") - ParamStoreKeyInstantiateAccess = []byte("instantiateAccess") -) - -// Deprecated: Type declaration for parameters -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// ParamSetPairs returns the parameter set pairs. -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(ParamStoreKeyUploadAccess, &p.CodeUploadAccess, validateAccessConfig), - paramtypes.NewParamSetPair(ParamStoreKeyInstantiateAccess, &p.InstantiateDefaultPermission, validateAccessType), - } -} diff --git a/x/wasm/types/params_test.go b/x/wasm/types/params_test.go deleted file mode 100644 index 77ac8b7..0000000 --- a/x/wasm/types/params_test.go +++ /dev/null @@ -1,306 +0,0 @@ -package types - -import ( - "bytes" - "encoding/json" - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestValidateParams(t *testing.T) { - var ( - anyAddress sdk.AccAddress = make([]byte, ContractAddrLen) - otherAddress sdk.AccAddress = bytes.Repeat([]byte{1}, ContractAddrLen) - invalidAddress = "invalid address" - ) - - specs := map[string]struct { - src Params - expErr bool - }{ - "all good with defaults": { - src: DefaultParams(), - }, - "all good with nobody": { - src: Params{ - CodeUploadAccess: AllowNobody, - InstantiateDefaultPermission: AccessTypeNobody, - }, - }, - "all good with everybody": { - src: Params{ - CodeUploadAccess: AllowEverybody, - InstantiateDefaultPermission: AccessTypeEverybody, - }, - }, - "all good with only address": { - src: Params{ - CodeUploadAccess: AccessTypeOnlyAddress.With(anyAddress), - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - }, - "all good with anyOf address": { - src: Params{ - CodeUploadAccess: AccessTypeAnyOfAddresses.With(anyAddress), - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - }, - "all good with anyOf addresses": { - src: Params{ - CodeUploadAccess: AccessTypeAnyOfAddresses.With(anyAddress, otherAddress), - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - }, - "reject empty type in instantiate permission": { - src: Params{ - CodeUploadAccess: AllowNobody, - }, - expErr: true, - }, - "reject unknown type in instantiate": { - src: Params{ - CodeUploadAccess: AllowNobody, - InstantiateDefaultPermission: 1111, - }, - expErr: true, - }, - "reject invalid address in only address": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeOnlyAddress, Address: invalidAddress}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject wrong field addresses in only address": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeOnlyAddress, Address: anyAddress.String(), Addresses: []string{anyAddress.String()}}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject CodeUploadAccess Everybody with obsolete address": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeEverybody, Address: anyAddress.String()}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject CodeUploadAccess Nobody with obsolete address": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeNobody, Address: anyAddress.String()}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject empty CodeUploadAccess": { - src: Params{ - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject undefined permission in CodeUploadAccess": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeUnspecified}, - InstantiateDefaultPermission: AccessTypeOnlyAddress, - }, - expErr: true, - }, - "reject empty addresses in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{}}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - "reject addresses not set in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - "reject invalid address in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{invalidAddress}}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - "reject duplicate address in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{anyAddress.String(), anyAddress.String()}}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - "reject wrong field address in any of addresses": { - src: Params{ - CodeUploadAccess: AccessConfig{Permission: AccessTypeAnyOfAddresses, Address: anyAddress.String(), Addresses: []string{anyAddress.String()}}, - InstantiateDefaultPermission: AccessTypeAnyOfAddresses, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestAccessTypeMarshalJson(t *testing.T) { - specs := map[string]struct { - src AccessType - exp string - }{ - "Unspecified": {src: AccessTypeUnspecified, exp: `"Unspecified"`}, - "Nobody": {src: AccessTypeNobody, exp: `"Nobody"`}, - "OnlyAddress": {src: AccessTypeOnlyAddress, exp: `"OnlyAddress"`}, - "AccessTypeAnyOfAddresses": {src: AccessTypeAnyOfAddresses, exp: `"AnyOfAddresses"`}, - "Everybody": {src: AccessTypeEverybody, exp: `"Everybody"`}, - "unknown": {src: 999, exp: `"Unspecified"`}, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - got, err := json.Marshal(spec.src) - require.NoError(t, err) - assert.Equal(t, []byte(spec.exp), got) - }) - } -} - -func TestAccessTypeUnmarshalJson(t *testing.T) { - specs := map[string]struct { - src string - exp AccessType - }{ - "Unspecified": {src: `"Unspecified"`, exp: AccessTypeUnspecified}, - "Nobody": {src: `"Nobody"`, exp: AccessTypeNobody}, - "OnlyAddress": {src: `"OnlyAddress"`, exp: AccessTypeOnlyAddress}, - "AnyOfAddresses": {src: `"AnyOfAddresses"`, exp: AccessTypeAnyOfAddresses}, - "Everybody": {src: `"Everybody"`, exp: AccessTypeEverybody}, - "unknown": {src: `""`, exp: AccessTypeUnspecified}, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - var got AccessType - err := json.Unmarshal([]byte(spec.src), &got) - require.NoError(t, err) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestParamsUnmarshalJson(t *testing.T) { - specs := map[string]struct { - src string - exp Params - }{ - "defaults": { - src: `{"code_upload_access": {"permission": "Everybody"}, - "instantiate_default_permission": "Everybody"}`, - exp: DefaultParams(), - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - var val Params - interfaceRegistry := codectypes.NewInterfaceRegistry() - marshaler := codec.NewProtoCodec(interfaceRegistry) - - err := marshaler.UnmarshalJSON([]byte(spec.src), &val) - require.NoError(t, err) - assert.Equal(t, spec.exp, val) - }) - } -} - -func TestAccessTypeWith(t *testing.T) { - myAddress := sdk.AccAddress(randBytes(SDKAddrLen)) - myOtherAddress := sdk.AccAddress(randBytes(SDKAddrLen)) - specs := map[string]struct { - src AccessType - addrs []sdk.AccAddress - exp AccessConfig - expPanic bool - }{ - "nobody": { - src: AccessTypeNobody, - exp: AccessConfig{Permission: AccessTypeNobody}, - }, - "nobody with address": { - src: AccessTypeNobody, - addrs: []sdk.AccAddress{myAddress}, - exp: AccessConfig{Permission: AccessTypeNobody}, - }, - "everybody": { - src: AccessTypeEverybody, - exp: AccessConfig{Permission: AccessTypeEverybody}, - }, - "everybody with address": { - src: AccessTypeEverybody, - addrs: []sdk.AccAddress{myAddress}, - exp: AccessConfig{Permission: AccessTypeEverybody}, - }, - "only address without address": { - src: AccessTypeOnlyAddress, - expPanic: true, - }, - "only address with address": { - src: AccessTypeOnlyAddress, - addrs: []sdk.AccAddress{myAddress}, - exp: AccessConfig{Permission: AccessTypeOnlyAddress, Address: myAddress.String()}, - }, - "only address with invalid address": { - src: AccessTypeOnlyAddress, - addrs: []sdk.AccAddress{nil}, - expPanic: true, - }, - "any of address without address": { - src: AccessTypeAnyOfAddresses, - expPanic: true, - }, - "any of address with single address": { - src: AccessTypeAnyOfAddresses, - addrs: []sdk.AccAddress{myAddress}, - exp: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{myAddress.String()}}, - }, - "any of address with multiple addresses": { - src: AccessTypeAnyOfAddresses, - addrs: []sdk.AccAddress{myAddress, myOtherAddress}, - exp: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{myAddress.String(), myOtherAddress.String()}}, - }, - "any of address with duplicate addresses": { - src: AccessTypeAnyOfAddresses, - addrs: []sdk.AccAddress{myAddress, myAddress}, - expPanic: true, - }, - "any of address with invalid address": { - src: AccessTypeAnyOfAddresses, - addrs: []sdk.AccAddress{nil}, - expPanic: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - if !spec.expPanic { - got := spec.src.With(spec.addrs...) - assert.Equal(t, spec.exp, got) - return - } - assert.Panics(t, func() { - spec.src.With(spec.addrs...) - }) - }) - } -} diff --git a/x/wasm/types/proposal.go b/x/wasm/types/proposal.go deleted file mode 100644 index 468f45b..0000000 --- a/x/wasm/types/proposal.go +++ /dev/null @@ -1,986 +0,0 @@ -package types - -import ( - "encoding/base64" - "encoding/hex" - "fmt" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" -) - -type ProposalType string - -const ( - ProposalTypeStoreCode ProposalType = "StoreCode" - ProposalTypeInstantiateContract ProposalType = "InstantiateContract" - ProposalTypeInstantiateContract2 ProposalType = "InstantiateContract2" - ProposalTypeMigrateContract ProposalType = "MigrateContract" - ProposalTypeSudoContract ProposalType = "SudoContract" - ProposalTypeExecuteContract ProposalType = "ExecuteContract" - ProposalTypeUpdateAdmin ProposalType = "UpdateAdmin" - ProposalTypeClearAdmin ProposalType = "ClearAdmin" - ProposalTypePinCodes ProposalType = "PinCodes" - ProposalTypeUnpinCodes ProposalType = "UnpinCodes" - ProposalTypeUpdateInstantiateConfig ProposalType = "UpdateInstantiateConfig" - ProposalTypeStoreAndInstantiateContractProposal ProposalType = "StoreAndInstantiateContract" -) - -// DisableAllProposals contains no wasm gov types. -var DisableAllProposals []ProposalType - -// EnableAllProposals contains all wasm gov types as keys. -var EnableAllProposals = []ProposalType{ - ProposalTypeStoreCode, - ProposalTypeInstantiateContract, - ProposalTypeInstantiateContract2, - ProposalTypeMigrateContract, - ProposalTypeSudoContract, - ProposalTypeExecuteContract, - ProposalTypeUpdateAdmin, - ProposalTypeClearAdmin, - ProposalTypePinCodes, - ProposalTypeUnpinCodes, - ProposalTypeUpdateInstantiateConfig, - ProposalTypeStoreAndInstantiateContractProposal, -} - -// ConvertToProposals maps each key to a ProposalType and returns a typed list. -// If any string is not a valid type (in this file), then return an error -func ConvertToProposals(keys []string) ([]ProposalType, error) { - valid := make(map[string]bool, len(EnableAllProposals)) - for _, key := range EnableAllProposals { - valid[string(key)] = true - } - - proposals := make([]ProposalType, len(keys)) - for i, key := range keys { - if _, ok := valid[key]; !ok { - return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "'%s' is not a valid ProposalType", key) - } - proposals[i] = ProposalType(key) - } - return proposals, nil -} - -func init() { // register new content types with the sdk - v1beta1.RegisterProposalType(string(ProposalTypeStoreCode)) - v1beta1.RegisterProposalType(string(ProposalTypeInstantiateContract)) - v1beta1.RegisterProposalType(string(ProposalTypeInstantiateContract2)) - v1beta1.RegisterProposalType(string(ProposalTypeMigrateContract)) - v1beta1.RegisterProposalType(string(ProposalTypeSudoContract)) - v1beta1.RegisterProposalType(string(ProposalTypeExecuteContract)) - v1beta1.RegisterProposalType(string(ProposalTypeUpdateAdmin)) - v1beta1.RegisterProposalType(string(ProposalTypeClearAdmin)) - v1beta1.RegisterProposalType(string(ProposalTypePinCodes)) - v1beta1.RegisterProposalType(string(ProposalTypeUnpinCodes)) - v1beta1.RegisterProposalType(string(ProposalTypeUpdateInstantiateConfig)) - v1beta1.RegisterProposalType(string(ProposalTypeStoreAndInstantiateContractProposal)) -} - -func NewStoreCodeProposal( - title string, - description string, - runAs string, - wasmBz []byte, - permission *AccessConfig, - unpinCode bool, - source string, - builder string, - codeHash []byte, -) *StoreCodeProposal { - return &StoreCodeProposal{title, description, runAs, wasmBz, permission, unpinCode, source, builder, codeHash} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p StoreCodeProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *StoreCodeProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p StoreCodeProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p StoreCodeProposal) ProposalType() string { return string(ProposalTypeStoreCode) } - -// ValidateBasic validates the proposal -func (p StoreCodeProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(err, "run as") - } - - if err := validateWasmCode(p.WASMByteCode, MaxProposalWasmSize); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) - } - - if p.InstantiatePermission != nil { - if err := p.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - } - - if err := ValidateVerificationInfo(p.Source, p.Builder, p.CodeHash); err != nil { - return errorsmod.Wrapf(err, "code verification info") - } - return nil -} - -// String implements the Stringer interface. -func (p StoreCodeProposal) String() string { - return fmt.Sprintf(`Store Code Proposal: - Title: %s - Description: %s - Run as: %s - WasmCode: %X - Source: %s - Builder: %s - Code Hash: %X -`, p.Title, p.Description, p.RunAs, p.WASMByteCode, p.Source, p.Builder, p.CodeHash) -} - -// MarshalYAML pretty prints the wasm byte code -func (p StoreCodeProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - RunAs string `yaml:"run_as"` - WASMByteCode string `yaml:"wasm_byte_code"` - InstantiatePermission *AccessConfig `yaml:"instantiate_permission"` - Source string `yaml:"source"` - Builder string `yaml:"builder"` - CodeHash string `yaml:"code_hash"` - }{ - Title: p.Title, - Description: p.Description, - RunAs: p.RunAs, - WASMByteCode: base64.StdEncoding.EncodeToString(p.WASMByteCode), - InstantiatePermission: p.InstantiatePermission, - Source: p.Source, - Builder: p.Builder, - CodeHash: hex.EncodeToString(p.CodeHash), - }, nil -} - -func NewInstantiateContractProposal( - title string, - description string, - runAs string, - admin string, - codeID uint64, - label string, - msg RawContractMessage, - funds sdk.Coins, -) *InstantiateContractProposal { - return &InstantiateContractProposal{title, description, runAs, admin, codeID, label, msg, funds} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p InstantiateContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *InstantiateContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p InstantiateContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p InstantiateContractProposal) ProposalType() string { - return string(ProposalTypeInstantiateContract) -} - -// ValidateBasic validates the proposal -func (p InstantiateContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "run as") - } - - if p.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - - if err := ValidateLabel(p.Label); err != nil { - return err - } - - if !p.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(p.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(p.Admin); err != nil { - return err - } - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p InstantiateContractProposal) String() string { - return fmt.Sprintf(`Instantiate Code Proposal: - Title: %s - Description: %s - Run as: %s - Admin: %s - Code id: %d - Label: %s - Msg: %q - Funds: %s -`, p.Title, p.Description, p.RunAs, p.Admin, p.CodeID, p.Label, p.Msg, p.Funds) -} - -// MarshalYAML pretty prints the init message -func (p InstantiateContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - RunAs string `yaml:"run_as"` - Admin string `yaml:"admin"` - CodeID uint64 `yaml:"code_id"` - Label string `yaml:"label"` - Msg string `yaml:"msg"` - Funds sdk.Coins `yaml:"funds"` - }{ - Title: p.Title, - Description: p.Description, - RunAs: p.RunAs, - Admin: p.Admin, - CodeID: p.CodeID, - Label: p.Label, - Msg: string(p.Msg), - Funds: p.Funds, - }, nil -} - -func NewInstantiateContract2Proposal( - title string, - description string, - runAs string, - admin string, - codeID uint64, - label string, - msg RawContractMessage, - funds sdk.Coins, - salt []byte, - fixMsg bool, -) *InstantiateContract2Proposal { - return &InstantiateContract2Proposal{title, description, runAs, admin, codeID, label, msg, funds, salt, fixMsg} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p InstantiateContract2Proposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *InstantiateContract2Proposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p InstantiateContract2Proposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p InstantiateContract2Proposal) ProposalType() string { - return string(ProposalTypeInstantiateContract2) -} - -// ValidateBasic validates the proposal -func (p InstantiateContract2Proposal) ValidateBasic() error { - // Validate title and description - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - // Validate run as - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "run as") - } - // Validate admin - if len(p.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(p.Admin); err != nil { - return err - } - } - // Validate codeid - if p.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - // Validate label - if err := ValidateLabel(p.Label); err != nil { - return err - } - // Validate msg - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - // Validate funds - if !p.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - // Validate salt - if len(p.Salt) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "salt is required") - } - return nil -} - -// String implements the Stringer interface. -func (p InstantiateContract2Proposal) String() string { - return fmt.Sprintf(`Instantiate Code Proposal: - Title: %s - Description: %s - Run as: %s - Admin: %s - Code id: %d - Label: %s - Msg: %q - Funds: %s - Salt: %X -`, p.Title, p.Description, p.RunAs, p.Admin, p.CodeID, p.Label, p.Msg, p.Funds, p.Salt) -} - -// MarshalYAML pretty prints the init message -func (p InstantiateContract2Proposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - RunAs string `yaml:"run_as"` - Admin string `yaml:"admin"` - CodeID uint64 `yaml:"code_id"` - Label string `yaml:"label"` - Msg string `yaml:"msg"` - Funds sdk.Coins `yaml:"funds"` - Salt string `yaml:"salt"` - }{ - Title: p.Title, - Description: p.Description, - RunAs: p.RunAs, - Admin: p.Admin, - CodeID: p.CodeID, - Label: p.Label, - Msg: string(p.Msg), - Funds: p.Funds, - Salt: base64.StdEncoding.EncodeToString(p.Salt), - }, nil -} - -func NewStoreAndInstantiateContractProposal( - title string, - description string, - runAs string, - wasmBz []byte, - source string, - builder string, - codeHash []byte, - permission *AccessConfig, - unpinCode bool, - admin string, - label string, - msg RawContractMessage, - funds sdk.Coins, -) *StoreAndInstantiateContractProposal { - return &StoreAndInstantiateContractProposal{ - Title: title, - Description: description, - RunAs: runAs, - WASMByteCode: wasmBz, - Source: source, - Builder: builder, - CodeHash: codeHash, - InstantiatePermission: permission, - UnpinCode: unpinCode, - Admin: admin, - Label: label, - Msg: msg, - Funds: funds, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p StoreAndInstantiateContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *StoreAndInstantiateContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p StoreAndInstantiateContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p StoreAndInstantiateContractProposal) ProposalType() string { - return string(ProposalTypeStoreAndInstantiateContractProposal) -} - -// ValidateBasic validates the proposal -func (p StoreAndInstantiateContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(err, "run as") - } - - if err := validateWasmCode(p.WASMByteCode, MaxProposalWasmSize); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) - } - - if err := ValidateVerificationInfo(p.Source, p.Builder, p.CodeHash); err != nil { - return errorsmod.Wrap(err, "code info") - } - - if p.InstantiatePermission != nil { - if err := p.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - } - - if err := ValidateLabel(p.Label); err != nil { - return err - } - - if !p.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(p.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(p.Admin); err != nil { - return err - } - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p StoreAndInstantiateContractProposal) String() string { - return fmt.Sprintf(`Store And Instantiate Coontract Proposal: - Title: %s - Description: %s - Run as: %s - WasmCode: %X - Source: %s - Builder: %s - Code Hash: %X - Instantiate permission: %s - Unpin code: %t - Admin: %s - Label: %s - Msg: %q - Funds: %s -`, p.Title, p.Description, p.RunAs, p.WASMByteCode, p.Source, p.Builder, p.CodeHash, p.InstantiatePermission, p.UnpinCode, p.Admin, p.Label, p.Msg, p.Funds) -} - -// MarshalYAML pretty prints the wasm byte code and the init message -func (p StoreAndInstantiateContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - RunAs string `yaml:"run_as"` - WASMByteCode string `yaml:"wasm_byte_code"` - Source string `yaml:"source"` - Builder string `yaml:"builder"` - CodeHash string `yaml:"code_hash"` - InstantiatePermission *AccessConfig `yaml:"instantiate_permission"` - UnpinCode bool `yaml:"unpin_code"` - Admin string `yaml:"admin"` - Label string `yaml:"label"` - Msg string `yaml:"msg"` - Funds sdk.Coins `yaml:"funds"` - }{ - Title: p.Title, - Description: p.Description, - RunAs: p.RunAs, - WASMByteCode: base64.StdEncoding.EncodeToString(p.WASMByteCode), - InstantiatePermission: p.InstantiatePermission, - UnpinCode: p.UnpinCode, - Admin: p.Admin, - Label: p.Label, - Source: p.Source, - Builder: p.Builder, - CodeHash: hex.EncodeToString(p.CodeHash), - Msg: string(p.Msg), - Funds: p.Funds, - }, nil -} - -func NewMigrateContractProposal( - title string, - description string, - contract string, - codeID uint64, - msg RawContractMessage, -) *MigrateContractProposal { - return &MigrateContractProposal{ - Title: title, - Description: description, - Contract: contract, - CodeID: codeID, - Msg: msg, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p MigrateContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *MigrateContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p MigrateContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p MigrateContractProposal) ProposalType() string { return string(ProposalTypeMigrateContract) } - -// ValidateBasic validates the proposal -func (p MigrateContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if p.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code_id is required") - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p MigrateContractProposal) String() string { - return fmt.Sprintf(`Migrate Contract Proposal: - Title: %s - Description: %s - Contract: %s - Code id: %d - Msg: %q -`, p.Title, p.Description, p.Contract, p.CodeID, p.Msg) -} - -// MarshalYAML pretty prints the migrate message -func (p MigrateContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - Contract string `yaml:"contract"` - CodeID uint64 `yaml:"code_id"` - Msg string `yaml:"msg"` - }{ - Title: p.Title, - Description: p.Description, - Contract: p.Contract, - CodeID: p.CodeID, - Msg: string(p.Msg), - }, nil -} - -func NewSudoContractProposal( - title string, - description string, - contract string, - msg RawContractMessage, -) *SudoContractProposal { - return &SudoContractProposal{ - Title: title, - Description: description, - Contract: contract, - Msg: msg, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p SudoContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *SudoContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p SudoContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p SudoContractProposal) ProposalType() string { return string(ProposalTypeSudoContract) } - -// ValidateBasic validates the proposal -func (p SudoContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p SudoContractProposal) String() string { - return fmt.Sprintf(`Migrate Contract Proposal: - Title: %s - Description: %s - Contract: %s - Msg: %q -`, p.Title, p.Description, p.Contract, p.Msg) -} - -// MarshalYAML pretty prints the migrate message -func (p SudoContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - Contract string `yaml:"contract"` - Msg string `yaml:"msg"` - }{ - Title: p.Title, - Description: p.Description, - Contract: p.Contract, - Msg: string(p.Msg), - }, nil -} - -func NewExecuteContractProposal( - title string, - description string, - runAs string, - contract string, - msg RawContractMessage, - funds sdk.Coins, -) *ExecuteContractProposal { - return &ExecuteContractProposal{title, description, runAs, contract, msg, funds} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p ExecuteContractProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *ExecuteContractProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p ExecuteContractProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p ExecuteContractProposal) ProposalType() string { return string(ProposalTypeExecuteContract) } - -// ValidateBasic validates the proposal -func (p ExecuteContractProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return errorsmod.Wrap(err, "run as") - } - if !p.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - if err := p.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -// String implements the Stringer interface. -func (p ExecuteContractProposal) String() string { - return fmt.Sprintf(`Migrate Contract Proposal: - Title: %s - Description: %s - Contract: %s - Run as: %s - Msg: %q - Funds: %s -`, p.Title, p.Description, p.Contract, p.RunAs, p.Msg, p.Funds) -} - -// MarshalYAML pretty prints the migrate message -func (p ExecuteContractProposal) MarshalYAML() (interface{}, error) { - return struct { - Title string `yaml:"title"` - Description string `yaml:"description"` - Contract string `yaml:"contract"` - Msg string `yaml:"msg"` - RunAs string `yaml:"run_as"` - Funds sdk.Coins `yaml:"funds"` - }{ - Title: p.Title, - Description: p.Description, - Contract: p.Contract, - Msg: string(p.Msg), - RunAs: p.RunAs, - Funds: p.Funds, - }, nil -} - -func NewUpdateAdminProposal( - title string, - description string, - newAdmin string, - contract string, -) *UpdateAdminProposal { - return &UpdateAdminProposal{title, description, newAdmin, contract} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p UpdateAdminProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *UpdateAdminProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p UpdateAdminProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p UpdateAdminProposal) ProposalType() string { return string(ProposalTypeUpdateAdmin) } - -// ValidateBasic validates the proposal -func (p UpdateAdminProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if _, err := sdk.AccAddressFromBech32(p.NewAdmin); err != nil { - return errorsmod.Wrap(err, "new admin") - } - return nil -} - -// String implements the Stringer interface. -func (p UpdateAdminProposal) String() string { - return fmt.Sprintf(`Update Contract Admin Proposal: - Title: %s - Description: %s - Contract: %s - New Admin: %s -`, p.Title, p.Description, p.Contract, p.NewAdmin) -} - -func NewClearAdminProposal( - title string, - description string, - contract string, -) *ClearAdminProposal { - return &ClearAdminProposal{title, description, contract} -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p ClearAdminProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *ClearAdminProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p ClearAdminProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p ClearAdminProposal) ProposalType() string { return string(ProposalTypeClearAdmin) } - -// ValidateBasic validates the proposal -func (p ClearAdminProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - return nil -} - -// String implements the Stringer interface. -func (p ClearAdminProposal) String() string { - return fmt.Sprintf(`Clear Contract Admin Proposal: - Title: %s - Description: %s - Contract: %s -`, p.Title, p.Description, p.Contract) -} - -func NewPinCodesProposal( - title string, - description string, - codeIDs []uint64, -) *PinCodesProposal { - return &PinCodesProposal{ - Title: title, - Description: description, - CodeIDs: codeIDs, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p PinCodesProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *PinCodesProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p PinCodesProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p PinCodesProposal) ProposalType() string { return string(ProposalTypePinCodes) } - -// ValidateBasic validates the proposal -func (p PinCodesProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if len(p.CodeIDs) == 0 { - return errorsmod.Wrap(ErrEmpty, "code ids") - } - return nil -} - -// String implements the Stringer interface. -func (p PinCodesProposal) String() string { - return fmt.Sprintf(`Pin Wasm Codes Proposal: - Title: %s - Description: %s - Codes: %v -`, p.Title, p.Description, p.CodeIDs) -} - -func NewUnpinCodesProposal( - title string, - description string, - codeIDs []uint64, -) *UnpinCodesProposal { - return &UnpinCodesProposal{ - Title: title, - Description: description, - CodeIDs: codeIDs, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p UnpinCodesProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *UnpinCodesProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p UnpinCodesProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p UnpinCodesProposal) ProposalType() string { return string(ProposalTypeUnpinCodes) } - -// ValidateBasic validates the proposal -func (p UnpinCodesProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if len(p.CodeIDs) == 0 { - return errorsmod.Wrap(ErrEmpty, "code ids") - } - return nil -} - -// String implements the Stringer interface. -func (p UnpinCodesProposal) String() string { - return fmt.Sprintf(`Unpin Wasm Codes Proposal: - Title: %s - Description: %s - Codes: %v -`, p.Title, p.Description, p.CodeIDs) -} - -func validateProposalCommons(title, description string) error { - if strings.TrimSpace(title) != title { - return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal title must not start/end with white spaces") - } - if len(title) == 0 { - return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal title cannot be blank") - } - if len(title) > v1beta1.MaxTitleLength { - return errorsmod.Wrapf(govtypes.ErrInvalidProposalContent, "proposal title is longer than max length of %d", v1beta1.MaxTitleLength) - } - if strings.TrimSpace(description) != description { - return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal description must not start/end with white spaces") - } - if len(description) == 0 { - return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal description cannot be blank") - } - if len(description) > v1beta1.MaxDescriptionLength { - return errorsmod.Wrapf(govtypes.ErrInvalidProposalContent, "proposal description is longer than max length of %d", v1beta1.MaxDescriptionLength) - } - return nil -} - -func NewUpdateInstantiateConfigProposal( - title string, - description string, - accessConfigUpdates ...AccessConfigUpdate, -) *UpdateInstantiateConfigProposal { - return &UpdateInstantiateConfigProposal{ - Title: title, - Description: description, - AccessConfigUpdates: accessConfigUpdates, - } -} - -// ProposalRoute returns the routing key of a parameter change proposal. -func (p UpdateInstantiateConfigProposal) ProposalRoute() string { return RouterKey } - -// GetTitle returns the title of the proposal -func (p *UpdateInstantiateConfigProposal) GetTitle() string { return p.Title } - -// GetDescription returns the human readable description of the proposal -func (p UpdateInstantiateConfigProposal) GetDescription() string { return p.Description } - -// ProposalType returns the type -func (p UpdateInstantiateConfigProposal) ProposalType() string { - return string(ProposalTypeUpdateInstantiateConfig) -} - -// ValidateBasic validates the proposal -func (p UpdateInstantiateConfigProposal) ValidateBasic() error { - if err := validateProposalCommons(p.Title, p.Description); err != nil { - return err - } - if len(p.AccessConfigUpdates) == 0 { - return errorsmod.Wrap(ErrEmpty, "code updates") - } - dedup := make(map[uint64]bool) - for _, codeUpdate := range p.AccessConfigUpdates { - _, found := dedup[codeUpdate.CodeID] - if found { - return errorsmod.Wrapf(ErrDuplicate, "duplicate code: %d", codeUpdate.CodeID) - } - if err := codeUpdate.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - dedup[codeUpdate.CodeID] = true - } - return nil -} - -// String implements the Stringer interface. -func (p UpdateInstantiateConfigProposal) String() string { - return fmt.Sprintf(`Update Instantiate Config Proposal: - Title: %s - Description: %s - AccessConfigUpdates: %v -`, p.Title, p.Description, p.AccessConfigUpdates) -} - -// String implements the Stringer interface. -func (c AccessConfigUpdate) String() string { - return fmt.Sprintf(`AccessConfigUpdate: - CodeID: %d - AccessConfig: %v -`, c.CodeID, c.InstantiatePermission) -} diff --git a/x/wasm/types/proposal.pb.go b/x/wasm/types/proposal.pb.go deleted file mode 100644 index df66215..0000000 --- a/x/wasm/types/proposal.pb.go +++ /dev/null @@ -1,5856 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/proposal.proto - -package types - -import ( - bytes "bytes" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = 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 - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit StoreCodeProposal. To submit WASM code to the system, -// a simple MsgStoreCode can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type StoreCodeProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's environment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `protobuf:"bytes,4,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` - // InstantiatePermission to apply on contract creation, optional - InstantiatePermission *AccessConfig `protobuf:"bytes,7,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission,omitempty"` - // UnpinCode code on upload, optional - UnpinCode bool `protobuf:"varint,8,opt,name=unpin_code,json=unpinCode,proto3" json:"unpin_code,omitempty"` - // Source is the URL where the code is hosted - Source string `protobuf:"bytes,9,opt,name=source,proto3" json:"source,omitempty"` - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - Builder string `protobuf:"bytes,10,opt,name=builder,proto3" json:"builder,omitempty"` - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - CodeHash []byte `protobuf:"bytes,11,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` -} - -func (m *StoreCodeProposal) Reset() { *m = StoreCodeProposal{} } -func (*StoreCodeProposal) ProtoMessage() {} -func (*StoreCodeProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{0} -} - -func (m *StoreCodeProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *StoreCodeProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_StoreCodeProposal.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 *StoreCodeProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_StoreCodeProposal.Merge(m, src) -} - -func (m *StoreCodeProposal) XXX_Size() int { - return m.Size() -} - -func (m *StoreCodeProposal) XXX_DiscardUnknown() { - xxx_messageInfo_StoreCodeProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_StoreCodeProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit InstantiateContractProposal. To instantiate a contract, -// a simple MsgInstantiateContract can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type InstantiateContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's environment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,4,opt,name=admin,proto3" json:"admin,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,5,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Label is optional metadata to be stored with a constract instance. - Label string `protobuf:"bytes,6,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,7,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,8,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` -} - -func (m *InstantiateContractProposal) Reset() { *m = InstantiateContractProposal{} } -func (*InstantiateContractProposal) ProtoMessage() {} -func (*InstantiateContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{1} -} - -func (m *InstantiateContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *InstantiateContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InstantiateContractProposal.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 *InstantiateContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_InstantiateContractProposal.Merge(m, src) -} - -func (m *InstantiateContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *InstantiateContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_InstantiateContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_InstantiateContractProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit InstantiateContract2Proposal. To instantiate contract 2, -// a simple MsgInstantiateContract2 can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type InstantiateContract2Proposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's enviroment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,4,opt,name=admin,proto3" json:"admin,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,5,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Label is optional metadata to be stored with a constract instance. - Label string `protobuf:"bytes,6,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encode message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,7,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,8,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` - // Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - Salt []byte `protobuf:"bytes,9,opt,name=salt,proto3" json:"salt,omitempty"` - // FixMsg include the msg value into the hash for the predictable address. - // Default is false - FixMsg bool `protobuf:"varint,10,opt,name=fix_msg,json=fixMsg,proto3" json:"fix_msg,omitempty"` -} - -func (m *InstantiateContract2Proposal) Reset() { *m = InstantiateContract2Proposal{} } -func (*InstantiateContract2Proposal) ProtoMessage() {} -func (*InstantiateContract2Proposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{2} -} - -func (m *InstantiateContract2Proposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *InstantiateContract2Proposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_InstantiateContract2Proposal.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 *InstantiateContract2Proposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_InstantiateContract2Proposal.Merge(m, src) -} - -func (m *InstantiateContract2Proposal) XXX_Size() int { - return m.Size() -} - -func (m *InstantiateContract2Proposal) XXX_DiscardUnknown() { - xxx_messageInfo_InstantiateContract2Proposal.DiscardUnknown(m) -} - -var xxx_messageInfo_InstantiateContract2Proposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit MigrateContractProposal. To migrate a contract, -// a simple MsgMigrateContract can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type MigrateContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,4,opt,name=contract,proto3" json:"contract,omitempty"` - // CodeID references the new WASM code - CodeID uint64 `protobuf:"varint,5,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Msg json encoded message to be passed to the contract on migration - Msg RawContractMessage `protobuf:"bytes,6,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *MigrateContractProposal) Reset() { *m = MigrateContractProposal{} } -func (*MigrateContractProposal) ProtoMessage() {} -func (*MigrateContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{3} -} - -func (m *MigrateContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MigrateContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MigrateContractProposal.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 *MigrateContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_MigrateContractProposal.Merge(m, src) -} - -func (m *MigrateContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *MigrateContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_MigrateContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_MigrateContractProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit SudoContractProposal. To call sudo on a contract, -// a simple MsgSudoContract can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type SudoContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,3,opt,name=contract,proto3" json:"contract,omitempty"` - // Msg json encoded message to be passed to the contract as sudo - Msg RawContractMessage `protobuf:"bytes,4,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *SudoContractProposal) Reset() { *m = SudoContractProposal{} } -func (*SudoContractProposal) ProtoMessage() {} -func (*SudoContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{4} -} - -func (m *SudoContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *SudoContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_SudoContractProposal.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 *SudoContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_SudoContractProposal.Merge(m, src) -} - -func (m *SudoContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *SudoContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_SudoContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_SudoContractProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit ExecuteContractProposal. To call execute on a contract, -// a simple MsgExecuteContract can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type ExecuteContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's environment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,4,opt,name=contract,proto3" json:"contract,omitempty"` - // Msg json encoded message to be passed to the contract as execute - Msg RawContractMessage `protobuf:"bytes,5,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` -} - -func (m *ExecuteContractProposal) Reset() { *m = ExecuteContractProposal{} } -func (*ExecuteContractProposal) ProtoMessage() {} -func (*ExecuteContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{5} -} - -func (m *ExecuteContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ExecuteContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ExecuteContractProposal.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 *ExecuteContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExecuteContractProposal.Merge(m, src) -} - -func (m *ExecuteContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *ExecuteContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_ExecuteContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_ExecuteContractProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UpdateAdminProposal. To set an admin for a contract, -// a simple MsgUpdateAdmin can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type UpdateAdminProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // NewAdmin address to be set - NewAdmin string `protobuf:"bytes,3,opt,name=new_admin,json=newAdmin,proto3" json:"new_admin,omitempty" yaml:"new_admin"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,4,opt,name=contract,proto3" json:"contract,omitempty"` -} - -func (m *UpdateAdminProposal) Reset() { *m = UpdateAdminProposal{} } -func (*UpdateAdminProposal) ProtoMessage() {} -func (*UpdateAdminProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{6} -} - -func (m *UpdateAdminProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *UpdateAdminProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_UpdateAdminProposal.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 *UpdateAdminProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateAdminProposal.Merge(m, src) -} - -func (m *UpdateAdminProposal) XXX_Size() int { - return m.Size() -} - -func (m *UpdateAdminProposal) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateAdminProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateAdminProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit ClearAdminProposal. To clear the admin of a contract, -// a simple MsgClearAdmin can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type ClearAdminProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,3,opt,name=contract,proto3" json:"contract,omitempty"` -} - -func (m *ClearAdminProposal) Reset() { *m = ClearAdminProposal{} } -func (*ClearAdminProposal) ProtoMessage() {} -func (*ClearAdminProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{7} -} - -func (m *ClearAdminProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ClearAdminProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ClearAdminProposal.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 *ClearAdminProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_ClearAdminProposal.Merge(m, src) -} - -func (m *ClearAdminProposal) XXX_Size() int { - return m.Size() -} - -func (m *ClearAdminProposal) XXX_DiscardUnknown() { - xxx_messageInfo_ClearAdminProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_ClearAdminProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit PinCodesProposal. To pin a set of code ids in the wasmvm -// cache, a simple MsgPinCodes can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type PinCodesProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty" yaml:"title"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty" yaml:"description"` - // CodeIDs references the new WASM codes - CodeIDs []uint64 `protobuf:"varint,3,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty" yaml:"code_ids"` -} - -func (m *PinCodesProposal) Reset() { *m = PinCodesProposal{} } -func (*PinCodesProposal) ProtoMessage() {} -func (*PinCodesProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{8} -} - -func (m *PinCodesProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *PinCodesProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PinCodesProposal.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 *PinCodesProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_PinCodesProposal.Merge(m, src) -} - -func (m *PinCodesProposal) XXX_Size() int { - return m.Size() -} - -func (m *PinCodesProposal) XXX_DiscardUnknown() { - xxx_messageInfo_PinCodesProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_PinCodesProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UnpinCodesProposal. To unpin a set of code ids in the wasmvm -// cache, a simple MsgUnpinCodes can be invoked from the x/gov module via -// a v1 governance proposal. -// -// Deprecated: Do not use. -type UnpinCodesProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty" yaml:"title"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty" yaml:"description"` - // CodeIDs references the WASM codes - CodeIDs []uint64 `protobuf:"varint,3,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty" yaml:"code_ids"` -} - -func (m *UnpinCodesProposal) Reset() { *m = UnpinCodesProposal{} } -func (*UnpinCodesProposal) ProtoMessage() {} -func (*UnpinCodesProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{9} -} - -func (m *UnpinCodesProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *UnpinCodesProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_UnpinCodesProposal.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 *UnpinCodesProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_UnpinCodesProposal.Merge(m, src) -} - -func (m *UnpinCodesProposal) XXX_Size() int { - return m.Size() -} - -func (m *UnpinCodesProposal) XXX_DiscardUnknown() { - xxx_messageInfo_UnpinCodesProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_UnpinCodesProposal proto.InternalMessageInfo - -// AccessConfigUpdate contains the code id and the access config to be -// applied. -type AccessConfigUpdate struct { - // CodeID is the reference to the stored WASM code to be updated - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // InstantiatePermission to apply to the set of code ids - InstantiatePermission AccessConfig `protobuf:"bytes,2,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission"` -} - -func (m *AccessConfigUpdate) Reset() { *m = AccessConfigUpdate{} } -func (*AccessConfigUpdate) ProtoMessage() {} -func (*AccessConfigUpdate) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{10} -} - -func (m *AccessConfigUpdate) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AccessConfigUpdate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccessConfigUpdate.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 *AccessConfigUpdate) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccessConfigUpdate.Merge(m, src) -} - -func (m *AccessConfigUpdate) XXX_Size() int { - return m.Size() -} - -func (m *AccessConfigUpdate) XXX_DiscardUnknown() { - xxx_messageInfo_AccessConfigUpdate.DiscardUnknown(m) -} - -var xxx_messageInfo_AccessConfigUpdate proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit UpdateInstantiateConfigProposal. To update instantiate config -// to a set of code ids, a simple MsgUpdateInstantiateConfig can be invoked from -// the x/gov module via a v1 governance proposal. -// -// Deprecated: Do not use. -type UpdateInstantiateConfigProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty" yaml:"title"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty" yaml:"description"` - // AccessConfigUpdate contains the list of code ids and the access config - // to be applied. - AccessConfigUpdates []AccessConfigUpdate `protobuf:"bytes,3,rep,name=access_config_updates,json=accessConfigUpdates,proto3" json:"access_config_updates"` -} - -func (m *UpdateInstantiateConfigProposal) Reset() { *m = UpdateInstantiateConfigProposal{} } -func (*UpdateInstantiateConfigProposal) ProtoMessage() {} -func (*UpdateInstantiateConfigProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{11} -} - -func (m *UpdateInstantiateConfigProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *UpdateInstantiateConfigProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_UpdateInstantiateConfigProposal.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 *UpdateInstantiateConfigProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_UpdateInstantiateConfigProposal.Merge(m, src) -} - -func (m *UpdateInstantiateConfigProposal) XXX_Size() int { - return m.Size() -} - -func (m *UpdateInstantiateConfigProposal) XXX_DiscardUnknown() { - xxx_messageInfo_UpdateInstantiateConfigProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_UpdateInstantiateConfigProposal proto.InternalMessageInfo - -// Deprecated: Do not use. Since wasmd v0.40, there is no longer a need for -// an explicit StoreAndInstantiateContractProposal. To store and instantiate -// the contract, a simple MsgStoreAndInstantiateContract can be invoked from -// the x/gov module via a v1 governance proposal. -// -// Deprecated: Do not use. -type StoreAndInstantiateContractProposal struct { - // Title is a short summary - Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` - // Description is a human readable text - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - // RunAs is the address that is passed to the contract's environment as sender - RunAs string `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3" json:"run_as,omitempty"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `protobuf:"bytes,4,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` - // InstantiatePermission to apply on contract creation, optional - InstantiatePermission *AccessConfig `protobuf:"bytes,5,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission,omitempty"` - // UnpinCode code on upload, optional - UnpinCode bool `protobuf:"varint,6,opt,name=unpin_code,json=unpinCode,proto3" json:"unpin_code,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,7,opt,name=admin,proto3" json:"admin,omitempty"` - // Label is optional metadata to be stored with a constract instance. - Label string `protobuf:"bytes,8,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,9,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,10,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` - // Source is the URL where the code is hosted - Source string `protobuf:"bytes,11,opt,name=source,proto3" json:"source,omitempty"` - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - Builder string `protobuf:"bytes,12,opt,name=builder,proto3" json:"builder,omitempty"` - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - CodeHash []byte `protobuf:"bytes,13,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` -} - -func (m *StoreAndInstantiateContractProposal) Reset() { *m = StoreAndInstantiateContractProposal{} } -func (*StoreAndInstantiateContractProposal) ProtoMessage() {} -func (*StoreAndInstantiateContractProposal) Descriptor() ([]byte, []int) { - return fileDescriptor_be6422d717c730cb, []int{12} -} - -func (m *StoreAndInstantiateContractProposal) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *StoreAndInstantiateContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_StoreAndInstantiateContractProposal.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 *StoreAndInstantiateContractProposal) XXX_Merge(src proto.Message) { - xxx_messageInfo_StoreAndInstantiateContractProposal.Merge(m, src) -} - -func (m *StoreAndInstantiateContractProposal) XXX_Size() int { - return m.Size() -} - -func (m *StoreAndInstantiateContractProposal) XXX_DiscardUnknown() { - xxx_messageInfo_StoreAndInstantiateContractProposal.DiscardUnknown(m) -} - -var xxx_messageInfo_StoreAndInstantiateContractProposal proto.InternalMessageInfo - -func init() { - proto.RegisterType((*StoreCodeProposal)(nil), "cosmwasm.wasm.v1.StoreCodeProposal") - proto.RegisterType((*InstantiateContractProposal)(nil), "cosmwasm.wasm.v1.InstantiateContractProposal") - proto.RegisterType((*InstantiateContract2Proposal)(nil), "cosmwasm.wasm.v1.InstantiateContract2Proposal") - proto.RegisterType((*MigrateContractProposal)(nil), "cosmwasm.wasm.v1.MigrateContractProposal") - proto.RegisterType((*SudoContractProposal)(nil), "cosmwasm.wasm.v1.SudoContractProposal") - proto.RegisterType((*ExecuteContractProposal)(nil), "cosmwasm.wasm.v1.ExecuteContractProposal") - proto.RegisterType((*UpdateAdminProposal)(nil), "cosmwasm.wasm.v1.UpdateAdminProposal") - proto.RegisterType((*ClearAdminProposal)(nil), "cosmwasm.wasm.v1.ClearAdminProposal") - proto.RegisterType((*PinCodesProposal)(nil), "cosmwasm.wasm.v1.PinCodesProposal") - proto.RegisterType((*UnpinCodesProposal)(nil), "cosmwasm.wasm.v1.UnpinCodesProposal") - proto.RegisterType((*AccessConfigUpdate)(nil), "cosmwasm.wasm.v1.AccessConfigUpdate") - proto.RegisterType((*UpdateInstantiateConfigProposal)(nil), "cosmwasm.wasm.v1.UpdateInstantiateConfigProposal") - proto.RegisterType((*StoreAndInstantiateContractProposal)(nil), "cosmwasm.wasm.v1.StoreAndInstantiateContractProposal") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/proposal.proto", fileDescriptor_be6422d717c730cb) } - -var fileDescriptor_be6422d717c730cb = []byte{ - // 1175 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x58, 0xcd, 0x6f, 0xe3, 0x44, - 0x14, 0xcf, 0x34, 0x89, 0x93, 0x4c, 0x02, 0x64, 0xbd, 0xfd, 0x98, 0xed, 0x16, 0x3b, 0x78, 0x57, - 0x28, 0x5a, 0xa9, 0x09, 0x2d, 0x02, 0x41, 0xf8, 0x90, 0xe2, 0xb2, 0x88, 0xae, 0x54, 0xa9, 0x72, - 0x55, 0x21, 0x71, 0x09, 0x13, 0x7b, 0x92, 0x5a, 0x9b, 0x78, 0x22, 0x8f, 0xd3, 0x8f, 0x7f, 0x81, - 0x13, 0x27, 0x2e, 0xdc, 0x51, 0xc5, 0x69, 0x25, 0xf8, 0x17, 0x90, 0x2a, 0x4e, 0x7b, 0xe0, 0xb0, - 0x12, 0x52, 0x60, 0xd3, 0xc3, 0x1e, 0x38, 0x20, 0xf5, 0xc8, 0x01, 0x90, 0x67, 0xec, 0xd4, 0x6d, - 0x93, 0xb8, 0x0b, 0xed, 0x4a, 0x48, 0x5c, 0x1c, 0xbf, 0x79, 0x33, 0xf6, 0xef, 0xf7, 0x7e, 0xf3, - 0x9e, 0xdf, 0x04, 0xaa, 0x26, 0x65, 0xdd, 0x3d, 0xcc, 0xba, 0x55, 0x7e, 0xd9, 0x5d, 0xa9, 0xf6, - 0x5c, 0xda, 0xa3, 0x0c, 0x77, 0x2a, 0x3d, 0x97, 0x7a, 0x54, 0x2e, 0x86, 0x13, 0x2a, 0xfc, 0xb2, - 0xbb, 0xb2, 0x38, 0xdb, 0xa6, 0x6d, 0xca, 0x9d, 0x55, 0xff, 0x4e, 0xcc, 0x5b, 0xbc, 0xe5, 0xcf, - 0xa3, 0xac, 0x21, 0x1c, 0xc2, 0x08, 0x5c, 0x8a, 0xb0, 0xaa, 0x4d, 0xcc, 0x48, 0x75, 0x77, 0xa5, - 0x49, 0x3c, 0xbc, 0x52, 0x35, 0xa9, 0xed, 0x04, 0xfe, 0xa5, 0x0b, 0x18, 0xbc, 0x83, 0x1e, 0x09, - 0x57, 0xdf, 0xc0, 0x5d, 0xdb, 0xa1, 0x55, 0x7e, 0x15, 0x43, 0xda, 0x61, 0x12, 0xde, 0xd8, 0xf2, - 0xa8, 0x4b, 0xd6, 0xa8, 0x45, 0x36, 0x03, 0xbc, 0xf2, 0x2c, 0x4c, 0x7b, 0xb6, 0xd7, 0x21, 0x08, - 0x94, 0x40, 0x39, 0x67, 0x08, 0x43, 0x2e, 0xc1, 0xbc, 0x45, 0x98, 0xe9, 0xda, 0x3d, 0xcf, 0xa6, - 0x0e, 0x9a, 0xe1, 0xbe, 0xe8, 0x90, 0x3c, 0x07, 0x25, 0xb7, 0xef, 0x34, 0x30, 0x43, 0x49, 0xb1, - 0xd0, 0xed, 0x3b, 0x75, 0x26, 0xbf, 0x0d, 0x5f, 0xf6, 0xe1, 0x34, 0x9a, 0x07, 0x1e, 0x69, 0x98, - 0xd4, 0x22, 0x28, 0x55, 0x02, 0xe5, 0x82, 0x5e, 0x1c, 0x0e, 0xd4, 0xc2, 0xa7, 0xf5, 0xad, 0x0d, - 0xfd, 0xc0, 0xe3, 0x00, 0x8c, 0x82, 0x3f, 0x2f, 0xb4, 0xe4, 0x6d, 0x38, 0x6f, 0x3b, 0xcc, 0xc3, - 0x8e, 0x67, 0x63, 0x8f, 0x34, 0x7a, 0xc4, 0xed, 0xda, 0x8c, 0xf9, 0xef, 0xce, 0x94, 0x40, 0x39, - 0xbf, 0xaa, 0x54, 0xce, 0x47, 0xb4, 0x52, 0x37, 0x4d, 0xc2, 0xd8, 0x1a, 0x75, 0x5a, 0x76, 0xdb, - 0x98, 0x8b, 0xac, 0xde, 0x1c, 0x2d, 0x96, 0x5f, 0x85, 0xb0, 0xef, 0xf4, 0x6c, 0x47, 0x40, 0xc9, - 0x96, 0x40, 0x39, 0x6b, 0xe4, 0xf8, 0x08, 0x7f, 0xeb, 0x3c, 0x94, 0x18, 0xed, 0xbb, 0x26, 0x41, - 0x39, 0x4e, 0x22, 0xb0, 0x64, 0x04, 0x33, 0xcd, 0xbe, 0xdd, 0xb1, 0x88, 0x8b, 0x20, 0x77, 0x84, - 0xa6, 0x7c, 0x1b, 0xe6, 0xfc, 0x47, 0x35, 0x76, 0x30, 0xdb, 0x41, 0x79, 0x9f, 0x9a, 0x91, 0xf5, - 0x07, 0x3e, 0xc1, 0x6c, 0xa7, 0xf6, 0xde, 0x8f, 0xdf, 0x2f, 0x2f, 0x06, 0x22, 0xb6, 0xe9, 0x6e, - 0x25, 0x50, 0xad, 0xb2, 0x46, 0x1d, 0x8f, 0x38, 0xde, 0x17, 0xcf, 0x1e, 0xdd, 0x9b, 0xe7, 0x62, - 0x5d, 0x90, 0x01, 0x81, 0x07, 0xa9, 0x6c, 0xba, 0x28, 0x3d, 0x48, 0x65, 0xa5, 0x62, 0x46, 0xfb, - 0x2a, 0x09, 0x6f, 0xaf, 0x9f, 0x12, 0xf2, 0xd7, 0xbb, 0xd8, 0xf4, 0xae, 0x4b, 0xb4, 0x59, 0x98, - 0xc6, 0x56, 0xd7, 0x76, 0xb8, 0x56, 0x39, 0x43, 0x18, 0xf2, 0x1d, 0x98, 0xe1, 0x54, 0x6d, 0x0b, - 0xa5, 0x4b, 0xa0, 0x9c, 0xd2, 0xe1, 0x70, 0xa0, 0x4a, 0x3e, 0xea, 0xf5, 0x8f, 0x0c, 0xc9, 0x77, - 0xad, 0x5b, 0xfe, 0xd2, 0x0e, 0x6e, 0x92, 0x0e, 0x92, 0xc4, 0x52, 0x6e, 0xc8, 0x65, 0x98, 0xec, - 0xb2, 0x36, 0x97, 0xae, 0xa0, 0xcf, 0xff, 0x31, 0x50, 0x65, 0x03, 0xef, 0x85, 0x2c, 0x36, 0x08, - 0x63, 0xb8, 0x4d, 0x0c, 0x7f, 0x8a, 0xdc, 0x82, 0xe9, 0x56, 0xdf, 0xb1, 0x18, 0xca, 0x96, 0x92, - 0xe5, 0xfc, 0xea, 0xad, 0x4a, 0x10, 0x3e, 0x7f, 0xd7, 0x47, 0xe2, 0x67, 0x3b, 0xfa, 0x5b, 0x47, - 0x03, 0x35, 0xf1, 0xed, 0x2f, 0x6a, 0xb9, 0x6d, 0x7b, 0x3b, 0xfd, 0x66, 0xc5, 0xa4, 0xdd, 0x20, - 0x61, 0x82, 0x9f, 0x65, 0x66, 0x3d, 0x0c, 0x72, 0xc0, 0x5f, 0xc0, 0x0e, 0x9f, 0x3d, 0xba, 0x07, - 0x0c, 0xf1, 0xf8, 0xda, 0xfd, 0x78, 0x69, 0x4a, 0x5c, 0x9a, 0x29, 0x61, 0x47, 0x40, 0xfb, 0x21, - 0x09, 0x97, 0xc6, 0xcc, 0x58, 0xfd, 0x5f, 0x99, 0x7f, 0xaa, 0x8c, 0x2c, 0xc3, 0x14, 0xc3, 0x1d, - 0x8f, 0x67, 0x60, 0xc1, 0xe0, 0xf7, 0xf2, 0x02, 0xcc, 0xb4, 0xec, 0xfd, 0x86, 0x8f, 0x14, 0xf2, - 0x9c, 0x95, 0x5a, 0xf6, 0xfe, 0x06, 0x6b, 0xd7, 0x3e, 0x8e, 0x97, 0xf1, 0xb5, 0x49, 0x32, 0xae, - 0x46, 0x74, 0xfc, 0x0b, 0xc0, 0x85, 0x0d, 0xbb, 0xed, 0x5e, 0x65, 0x72, 0x2d, 0xc2, 0xac, 0x19, - 0x3c, 0x2b, 0x90, 0x6b, 0x64, 0x5f, 0x4e, 0xb1, 0x40, 0x1b, 0x29, 0x56, 0x9b, 0x5a, 0x3d, 0x3e, - 0x0c, 0x4b, 0x3c, 0x0c, 0x13, 0x38, 0x22, 0xa0, 0xfd, 0x04, 0xe0, 0xec, 0x56, 0xdf, 0xa2, 0xd7, - 0x42, 0x3f, 0x79, 0x8e, 0x7e, 0xc0, 0x2c, 0x15, 0xcf, 0xec, 0xc3, 0x78, 0x66, 0xb7, 0x44, 0x09, - 0x1d, 0x83, 0xdd, 0xa7, 0x35, 0x03, 0x17, 0xee, 0xef, 0x13, 0xb3, 0x7f, 0xfd, 0x55, 0x73, 0x9a, - 0xde, 0x01, 0xe1, 0x74, 0x7c, 0x9a, 0xe1, 0x30, 0xcd, 0xa4, 0xb8, 0x34, 0x7b, 0xe3, 0x79, 0xd3, - 0x2c, 0xac, 0x7d, 0x97, 0xde, 0x2d, 0x13, 0x02, 0x87, 0x80, 0xf6, 0x33, 0x80, 0x37, 0xb7, 0x7b, - 0x16, 0xf6, 0x48, 0xdd, 0xaf, 0x40, 0xff, 0x3a, 0xa4, 0x2b, 0x30, 0xe7, 0x90, 0xbd, 0x86, 0xa8, - 0x6d, 0x3c, 0xaa, 0xfa, 0xec, 0xc9, 0x40, 0x2d, 0x1e, 0xe0, 0x6e, 0xa7, 0xa6, 0x8d, 0x5c, 0x9a, - 0x91, 0x75, 0xc8, 0x1e, 0x7f, 0xe5, 0xb4, 0x70, 0xd7, 0x3e, 0x88, 0x67, 0x88, 0x38, 0xc3, 0x31, - 0x1c, 0x10, 0xd0, 0xbe, 0x01, 0x50, 0x5e, 0xeb, 0x10, 0xec, 0x5e, 0x0d, 0xb9, 0x29, 0x99, 0x50, - 0x7b, 0x3f, 0x1e, 0xe9, 0x02, 0x47, 0x7a, 0x11, 0x0f, 0x02, 0xda, 0x6f, 0x00, 0x16, 0x37, 0x45, - 0xef, 0xc2, 0x46, 0x30, 0x5f, 0x3f, 0x03, 0x53, 0x2f, 0x9e, 0x0c, 0xd4, 0x82, 0x88, 0x23, 0x1f, - 0xd6, 0x42, 0xe0, 0xef, 0x8c, 0x01, 0xae, 0xcf, 0x9f, 0x0c, 0x54, 0x59, 0xcc, 0x8e, 0x38, 0xb5, - 0xb3, 0x84, 0xde, 0x85, 0xd9, 0xa0, 0x7a, 0xf9, 0x29, 0x90, 0x2c, 0xa7, 0x74, 0x65, 0x38, 0x50, - 0x33, 0xa2, 0x7c, 0xb1, 0x93, 0x81, 0xfa, 0x8a, 0x78, 0x42, 0x38, 0x49, 0x33, 0x32, 0xa2, 0xa4, - 0xb1, 0x5a, 0x2d, 0x9e, 0xef, 0x1c, 0xe7, 0x7b, 0x9e, 0x16, 0x02, 0xda, 0xef, 0x00, 0xca, 0xdb, - 0x61, 0xaf, 0xf6, 0x1f, 0xe1, 0x7b, 0x69, 0x7d, 0x2f, 0x12, 0x43, 0x40, 0xfb, 0x1a, 0x40, 0x39, - 0xda, 0xd6, 0x8a, 0xed, 0x1a, 0xfd, 0x7a, 0x80, 0x89, 0x5f, 0x8f, 0xcf, 0x27, 0x76, 0xd0, 0x33, - 0x97, 0xe9, 0xa0, 0xf5, 0x9c, 0x5f, 0x5e, 0xc4, 0x97, 0x79, 0x7c, 0x33, 0xad, 0x7d, 0x37, 0x03, - 0x55, 0x81, 0xe8, 0xec, 0xd7, 0xb5, 0x65, 0xb7, 0x5f, 0xa0, 0x38, 0x26, 0x9c, 0xc3, 0x1c, 0x77, - 0xc3, 0xe4, 0xaf, 0x6e, 0xf4, 0x39, 0x24, 0xa1, 0x54, 0x7e, 0xf5, 0xee, 0x74, 0x9a, 0x02, 0x7f, - 0x94, 0xec, 0x4d, 0x7c, 0xc1, 0xcd, 0x6a, 0xeb, 0xf1, 0x32, 0xde, 0x8d, 0x14, 0x94, 0x89, 0xf1, - 0x40, 0x40, 0xfb, 0x33, 0x05, 0xef, 0xf0, 0x7e, 0xbf, 0xee, 0x58, 0x2f, 0xb0, 0xa7, 0xbf, 0xfa, - 0x83, 0x58, 0xfa, 0xea, 0x0e, 0x62, 0xd2, 0xf9, 0x83, 0xd8, 0xa8, 0xcf, 0xcd, 0x44, 0xfb, 0xdc, - 0x51, 0x0b, 0x9b, 0x1d, 0xd3, 0xc2, 0xe6, 0x9e, 0xa3, 0x85, 0x85, 0xd7, 0xdb, 0xc2, 0x9e, 0x1e, - 0x23, 0xf3, 0x93, 0x8e, 0x91, 0x85, 0x29, 0xc7, 0xc8, 0x97, 0xce, 0x1d, 0x23, 0x37, 0xe2, 0x37, - 0x5f, 0xf9, 0xf4, 0x18, 0x39, 0x7d, 0x5b, 0x21, 0xa0, 0x6f, 0x1d, 0x3d, 0x55, 0x12, 0x4f, 0x9e, - 0x2a, 0x89, 0xc3, 0xa1, 0x02, 0x8e, 0x86, 0x0a, 0x78, 0x3c, 0x54, 0xc0, 0xaf, 0x43, 0x05, 0x7c, - 0x79, 0xac, 0x24, 0x1e, 0x1f, 0x2b, 0x89, 0x27, 0xc7, 0x4a, 0xe2, 0xb3, 0xe5, 0x08, 0x73, 0x8f, - 0xb8, 0x3d, 0x87, 0x78, 0x7b, 0xd4, 0x7d, 0xc8, 0xef, 0x97, 0x4d, 0xea, 0x92, 0xea, 0xbe, 0xf8, - 0xa3, 0x81, 0x07, 0xa1, 0x29, 0xf1, 0xff, 0x14, 0xde, 0xfc, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x41, - 0x3d, 0x83, 0x5f, 0x0a, 0x11, 0x00, 0x00, -} - -func (this *StoreCodeProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*StoreCodeProposal) - if !ok { - that2, ok := that.(StoreCodeProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if !bytes.Equal(this.WASMByteCode, that1.WASMByteCode) { - return false - } - if !this.InstantiatePermission.Equal(that1.InstantiatePermission) { - return false - } - if this.UnpinCode != that1.UnpinCode { - return false - } - if this.Source != that1.Source { - return false - } - if this.Builder != that1.Builder { - return false - } - if !bytes.Equal(this.CodeHash, that1.CodeHash) { - return false - } - return true -} - -func (this *InstantiateContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*InstantiateContractProposal) - if !ok { - that2, ok := that.(InstantiateContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if this.Admin != that1.Admin { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if this.Label != that1.Label { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - if len(this.Funds) != len(that1.Funds) { - return false - } - for i := range this.Funds { - if !this.Funds[i].Equal(&that1.Funds[i]) { - return false - } - } - return true -} - -func (this *InstantiateContract2Proposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*InstantiateContract2Proposal) - if !ok { - that2, ok := that.(InstantiateContract2Proposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if this.Admin != that1.Admin { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if this.Label != that1.Label { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - if len(this.Funds) != len(that1.Funds) { - return false - } - for i := range this.Funds { - if !this.Funds[i].Equal(&that1.Funds[i]) { - return false - } - } - if !bytes.Equal(this.Salt, that1.Salt) { - return false - } - if this.FixMsg != that1.FixMsg { - return false - } - return true -} - -func (this *MigrateContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*MigrateContractProposal) - if !ok { - that2, ok := that.(MigrateContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.Contract != that1.Contract { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - return true -} - -func (this *SudoContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*SudoContractProposal) - if !ok { - that2, ok := that.(SudoContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.Contract != that1.Contract { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - return true -} - -func (this *ExecuteContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ExecuteContractProposal) - if !ok { - that2, ok := that.(ExecuteContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if this.Contract != that1.Contract { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - if len(this.Funds) != len(that1.Funds) { - return false - } - for i := range this.Funds { - if !this.Funds[i].Equal(&that1.Funds[i]) { - return false - } - } - return true -} - -func (this *UpdateAdminProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*UpdateAdminProposal) - if !ok { - that2, ok := that.(UpdateAdminProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.NewAdmin != that1.NewAdmin { - return false - } - if this.Contract != that1.Contract { - return false - } - return true -} - -func (this *ClearAdminProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ClearAdminProposal) - if !ok { - that2, ok := that.(ClearAdminProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.Contract != that1.Contract { - return false - } - return true -} - -func (this *PinCodesProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*PinCodesProposal) - if !ok { - that2, ok := that.(PinCodesProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if len(this.CodeIDs) != len(that1.CodeIDs) { - return false - } - for i := range this.CodeIDs { - if this.CodeIDs[i] != that1.CodeIDs[i] { - return false - } - } - return true -} - -func (this *UnpinCodesProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*UnpinCodesProposal) - if !ok { - that2, ok := that.(UnpinCodesProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if len(this.CodeIDs) != len(that1.CodeIDs) { - return false - } - for i := range this.CodeIDs { - if this.CodeIDs[i] != that1.CodeIDs[i] { - return false - } - } - return true -} - -func (this *AccessConfigUpdate) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*AccessConfigUpdate) - if !ok { - that2, ok := that.(AccessConfigUpdate) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if !this.InstantiatePermission.Equal(&that1.InstantiatePermission) { - return false - } - return true -} - -func (this *UpdateInstantiateConfigProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*UpdateInstantiateConfigProposal) - if !ok { - that2, ok := that.(UpdateInstantiateConfigProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if len(this.AccessConfigUpdates) != len(that1.AccessConfigUpdates) { - return false - } - for i := range this.AccessConfigUpdates { - if !this.AccessConfigUpdates[i].Equal(&that1.AccessConfigUpdates[i]) { - return false - } - } - return true -} - -func (this *StoreAndInstantiateContractProposal) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*StoreAndInstantiateContractProposal) - if !ok { - that2, ok := that.(StoreAndInstantiateContractProposal) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Title != that1.Title { - return false - } - if this.Description != that1.Description { - return false - } - if this.RunAs != that1.RunAs { - return false - } - if !bytes.Equal(this.WASMByteCode, that1.WASMByteCode) { - return false - } - if !this.InstantiatePermission.Equal(that1.InstantiatePermission) { - return false - } - if this.UnpinCode != that1.UnpinCode { - return false - } - if this.Admin != that1.Admin { - return false - } - if this.Label != that1.Label { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - if len(this.Funds) != len(that1.Funds) { - return false - } - for i := range this.Funds { - if !this.Funds[i].Equal(&that1.Funds[i]) { - return false - } - } - if this.Source != that1.Source { - return false - } - if this.Builder != that1.Builder { - return false - } - if !bytes.Equal(this.CodeHash, that1.CodeHash) { - return false - } - return true -} - -func (m *StoreCodeProposal) 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 *StoreCodeProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *StoreCodeProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeHash) > 0 { - i -= len(m.CodeHash) - copy(dAtA[i:], m.CodeHash) - i = encodeVarintProposal(dAtA, i, uint64(len(m.CodeHash))) - i-- - dAtA[i] = 0x5a - } - if len(m.Builder) > 0 { - i -= len(m.Builder) - copy(dAtA[i:], m.Builder) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Builder))) - i-- - dAtA[i] = 0x52 - } - if len(m.Source) > 0 { - i -= len(m.Source) - copy(dAtA[i:], m.Source) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Source))) - i-- - dAtA[i] = 0x4a - } - if m.UnpinCode { - i-- - if m.UnpinCode { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x40 - } - if m.InstantiatePermission != nil { - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - if len(m.WASMByteCode) > 0 { - i -= len(m.WASMByteCode) - copy(dAtA[i:], m.WASMByteCode) - i = encodeVarintProposal(dAtA, i, uint64(len(m.WASMByteCode))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *InstantiateContractProposal) 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 *InstantiateContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InstantiateContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x3a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x32 - } - if m.CodeID != 0 { - i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x28 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *InstantiateContract2Proposal) 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 *InstantiateContract2Proposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *InstantiateContract2Proposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.FixMsg { - i-- - if m.FixMsg { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x50 - } - if len(m.Salt) > 0 { - i -= len(m.Salt) - copy(dAtA[i:], m.Salt) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Salt))) - i-- - dAtA[i] = 0x4a - } - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x3a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x32 - } - if m.CodeID != 0 { - i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x28 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MigrateContractProposal) 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 *MigrateContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MigrateContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x32 - } - if m.CodeID != 0 { - i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x28 - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x22 - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *SudoContractProposal) 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 *SudoContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *SudoContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x22 - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ExecuteContractProposal) 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 *ExecuteContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ExecuteContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x2a - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *UpdateAdminProposal) 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 *UpdateAdminProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *UpdateAdminProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x22 - } - if len(m.NewAdmin) > 0 { - i -= len(m.NewAdmin) - copy(dAtA[i:], m.NewAdmin) - i = encodeVarintProposal(dAtA, i, uint64(len(m.NewAdmin))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ClearAdminProposal) 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 *ClearAdminProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ClearAdminProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *PinCodesProposal) 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 *PinCodesProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *PinCodesProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeIDs) > 0 { - dAtA3 := make([]byte, len(m.CodeIDs)*10) - var j2 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA3[j2] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j2++ - } - dAtA3[j2] = uint8(num) - j2++ - } - i -= j2 - copy(dAtA[i:], dAtA3[:j2]) - i = encodeVarintProposal(dAtA, i, uint64(j2)) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *UnpinCodesProposal) 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 *UnpinCodesProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *UnpinCodesProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeIDs) > 0 { - dAtA5 := make([]byte, len(m.CodeIDs)*10) - var j4 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA5[j4] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j4++ - } - dAtA5[j4] = uint8(num) - j4++ - } - i -= j4 - copy(dAtA[i:], dAtA5[:j4]) - i = encodeVarintProposal(dAtA, i, uint64(j4)) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *AccessConfigUpdate) 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 *AccessConfigUpdate) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccessConfigUpdate) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if m.CodeID != 0 { - i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *UpdateInstantiateConfigProposal) 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 *UpdateInstantiateConfigProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *UpdateInstantiateConfigProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.AccessConfigUpdates) > 0 { - for iNdEx := len(m.AccessConfigUpdates) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.AccessConfigUpdates[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *StoreAndInstantiateContractProposal) 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 *StoreAndInstantiateContractProposal) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *StoreAndInstantiateContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeHash) > 0 { - i -= len(m.CodeHash) - copy(dAtA[i:], m.CodeHash) - i = encodeVarintProposal(dAtA, i, uint64(len(m.CodeHash))) - i-- - dAtA[i] = 0x6a - } - if len(m.Builder) > 0 { - i -= len(m.Builder) - copy(dAtA[i:], m.Builder) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Builder))) - i-- - dAtA[i] = 0x62 - } - if len(m.Source) > 0 { - i -= len(m.Source) - copy(dAtA[i:], m.Source) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Source))) - i-- - dAtA[i] = 0x5a - } - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x4a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x42 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x3a - } - if m.UnpinCode { - i-- - if m.UnpinCode { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x30 - } - if m.InstantiatePermission != nil { - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintProposal(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - if len(m.WASMByteCode) > 0 { - i -= len(m.WASMByteCode) - copy(dAtA[i:], m.WASMByteCode) - i = encodeVarintProposal(dAtA, i, uint64(len(m.WASMByteCode))) - i-- - dAtA[i] = 0x22 - } - if len(m.RunAs) > 0 { - i -= len(m.RunAs) - copy(dAtA[i:], m.RunAs) - i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) - i-- - dAtA[i] = 0x1a - } - if len(m.Description) > 0 { - i -= len(m.Description) - copy(dAtA[i:], m.Description) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) - i-- - dAtA[i] = 0x12 - } - if len(m.Title) > 0 { - i -= len(m.Title) - copy(dAtA[i:], m.Title) - i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { - offset -= sovProposal(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *StoreCodeProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.WASMByteCode) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.InstantiatePermission != nil { - l = m.InstantiatePermission.Size() - n += 1 + l + sovProposal(uint64(l)) - } - if m.UnpinCode { - n += 2 - } - l = len(m.Source) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Builder) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.CodeHash) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *InstantiateContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovProposal(uint64(m.CodeID)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *InstantiateContract2Proposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovProposal(uint64(m.CodeID)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - l = len(m.Salt) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.FixMsg { - n += 2 - } - return n -} - -func (m *MigrateContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovProposal(uint64(m.CodeID)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *SudoContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *ExecuteContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *UpdateAdminProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.NewAdmin) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *ClearAdminProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func (m *PinCodesProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovProposal(uint64(e)) - } - n += 1 + sovProposal(uint64(l)) + l - } - return n -} - -func (m *UnpinCodesProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovProposal(uint64(e)) - } - n += 1 + sovProposal(uint64(l)) + l - } - return n -} - -func (m *AccessConfigUpdate) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovProposal(uint64(m.CodeID)) - } - l = m.InstantiatePermission.Size() - n += 1 + l + sovProposal(uint64(l)) - return n -} - -func (m *UpdateInstantiateConfigProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.AccessConfigUpdates) > 0 { - for _, e := range m.AccessConfigUpdates { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - return n -} - -func (m *StoreAndInstantiateContractProposal) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Title) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.RunAs) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.WASMByteCode) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if m.InstantiatePermission != nil { - l = m.InstantiatePermission.Size() - n += 1 + l + sovProposal(uint64(l)) - } - if m.UnpinCode { - n += 2 - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovProposal(uint64(l)) - } - } - l = len(m.Source) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.Builder) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - l = len(m.CodeHash) - if l > 0 { - n += 1 + l + sovProposal(uint64(l)) - } - return n -} - -func sovProposal(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozProposal(x uint64) (n int) { - return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *StoreCodeProposal) 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 ErrIntOverflowProposal - } - 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: StoreCodeProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: StoreCodeProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) - if m.WASMByteCode == nil { - m.WASMByteCode = []byte{} - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.InstantiatePermission == nil { - m.InstantiatePermission = &AccessConfig{} - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field UnpinCode", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.UnpinCode = bool(v != 0) - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Source = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Builder = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) - if m.CodeHash == nil { - m.CodeHash = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *InstantiateContractProposal) 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 ErrIntOverflowProposal - } - 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: InstantiateContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InstantiateContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *InstantiateContract2Proposal) 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 ErrIntOverflowProposal - } - 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: InstantiateContract2Proposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: InstantiateContract2Proposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Salt", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Salt = append(m.Salt[:0], dAtA[iNdEx:postIndex]...) - if m.Salt == nil { - m.Salt = []byte{} - } - iNdEx = postIndex - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field FixMsg", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.FixMsg = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MigrateContractProposal) 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 ErrIntOverflowProposal - } - 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: MigrateContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MigrateContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *SudoContractProposal) 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 ErrIntOverflowProposal - } - 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: SudoContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SudoContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ExecuteContractProposal) 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 ErrIntOverflowProposal - } - 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: ExecuteContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ExecuteContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *UpdateAdminProposal) 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 ErrIntOverflowProposal - } - 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: UpdateAdminProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: UpdateAdminProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewAdmin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.NewAdmin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ClearAdminProposal) 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 ErrIntOverflowProposal - } - 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: ClearAdminProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ClearAdminProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *PinCodesProposal) 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 ErrIntOverflowProposal - } - 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: PinCodesProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PinCodesProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *UnpinCodesProposal) 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 ErrIntOverflowProposal - } - 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: UnpinCodesProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: UnpinCodesProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AccessConfigUpdate) 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 ErrIntOverflowProposal - } - 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: AccessConfigUpdate: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccessConfigUpdate: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *UpdateInstantiateConfigProposal) 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 ErrIntOverflowProposal - } - 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: UpdateInstantiateConfigProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: UpdateInstantiateConfigProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AccessConfigUpdates", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AccessConfigUpdates = append(m.AccessConfigUpdates, AccessConfigUpdate{}) - if err := m.AccessConfigUpdates[len(m.AccessConfigUpdates)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *StoreAndInstantiateContractProposal) 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 ErrIntOverflowProposal - } - 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: StoreAndInstantiateContractProposal: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: StoreAndInstantiateContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Title = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RunAs = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) - if m.WASMByteCode == nil { - m.WASMByteCode = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.InstantiatePermission == nil { - m.InstantiatePermission = &AccessConfig{} - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field UnpinCode", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.UnpinCode = bool(v != 0) - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Source = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - 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 ErrInvalidLengthProposal - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Builder = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 13: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProposal - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProposal - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthProposal - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) - if m.CodeHash == nil { - m.CodeHash = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProposal(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthProposal - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipProposal(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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrIntOverflowProposal - } - 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, ErrInvalidLengthProposal - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupProposal - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthProposal - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/proposal_test.go b/x/wasm/types/proposal_test.go deleted file mode 100644 index 8952f8c..0000000 --- a/x/wasm/types/proposal_test.go +++ /dev/null @@ -1,1123 +0,0 @@ -package types - -import ( - "bytes" - "encoding/json" - "strings" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "gopkg.in/yaml.v2" -) - -func TestValidateProposalCommons(t *testing.T) { - type commonProposal struct { - Title, Description string - } - - specs := map[string]struct { - src commonProposal - expErr bool - }{ - "all good": {src: commonProposal{ - Title: "Foo", - Description: "Bar", - }}, - "prevent empty title": { - src: commonProposal{ - Description: "Bar", - }, - expErr: true, - }, - "prevent white space only title": { - src: commonProposal{ - Title: " ", - Description: "Bar", - }, - expErr: true, - }, - "prevent leading white spaces in title": { - src: commonProposal{ - Title: " Foo", - Description: "Bar", - }, - expErr: true, - }, - "prevent title exceeds max length ": { - src: commonProposal{ - Title: strings.Repeat("a", v1beta1.MaxTitleLength+1), - Description: "Bar", - }, - expErr: true, - }, - "prevent empty description": { - src: commonProposal{ - Title: "Foo", - }, - expErr: true, - }, - "prevent leading white spaces in description": { - src: commonProposal{ - Title: "Foo", - Description: " Bar", - }, - expErr: true, - }, - "prevent white space only description": { - src: commonProposal{ - Title: "Foo", - Description: " ", - }, - expErr: true, - }, - "prevent descr exceeds max length ": { - src: commonProposal{ - Title: "Foo", - Description: strings.Repeat("a", v1beta1.MaxDescriptionLength+1), - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := validateProposalCommons(spec.src.Title, spec.src.Description) - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateStoreCodeProposal(t *testing.T) { - var anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, ContractAddrLen) - - specs := map[string]struct { - src *StoreCodeProposal - expErr bool - }{ - "all good": { - src: StoreCodeProposalFixture(), - }, - "all good no code verification info": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.Source = "" - p.Builder = "" - p.CodeHash = nil - }), - }, - "source missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.Source = "" - }), - expErr: true, - }, - "builder missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.Builder = "" - }), - expErr: true, - }, - "code hash missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.CodeHash = nil - }), - expErr: true, - }, - "with instantiate permission": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - accessConfig := AccessTypeOnlyAddress.With(anyAddress) - p.InstantiatePermission = &accessConfig - }), - }, - "base data missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.Title = "" - }), - expErr: true, - }, - "run_as missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.RunAs = "" - }), - expErr: true, - }, - "run_as invalid": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - "wasm code missing": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.WASMByteCode = nil - }), - expErr: true, - }, - "wasm code invalid": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.WASMByteCode = bytes.Repeat([]byte{0x0}, MaxProposalWasmSize+1) - }), - expErr: true, - }, - "with invalid instantiate permission": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.InstantiatePermission = &AccessConfig{} - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateInstantiateContractProposal(t *testing.T) { - specs := map[string]struct { - src *InstantiateContractProposal - expErr bool - }{ - "all good": { - src: InstantiateContractProposalFixture(), - }, - "without admin": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Admin = "" - }), - }, - "without init msg": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "with invalid init msg": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Msg = []byte("not a json string") - }), - expErr: true, - }, - "without init funds": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = nil - }), - }, - "base data missing": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "run_as missing": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.RunAs = "" - }), - expErr: true, - }, - "run_as invalid": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - "admin invalid": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Admin = invalidAddress - }), - expErr: true, - }, - "code id empty": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.CodeID = 0 - }), - expErr: true, - }, - "label empty": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Label = "" - }), - expErr: true, - }, - "init funds negative": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(-1)}} - }), - expErr: true, - }, - "init funds with duplicates": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "foo", Amount: sdk.NewInt(2)}} - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateInstantiateContract2Proposal(t *testing.T) { - specs := map[string]struct { - src *InstantiateContract2Proposal - expErr bool - }{ - "all good": { - src: InstantiateContract2ProposalFixture(), - }, - "without admin": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Admin = "" - }), - }, - "without init msg": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Msg = nil - }), - expErr: true, - }, - "with invalid init msg": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Msg = []byte("not a json string") - }), - expErr: true, - }, - "without init funds": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Funds = nil - }), - }, - "base data missing": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Title = "" - }), - expErr: true, - }, - "run_as missing": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.RunAs = "" - }), - expErr: true, - }, - "run_as invalid": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - "admin invalid": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Admin = invalidAddress - }), - expErr: true, - }, - "code id empty": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.CodeID = 0 - }), - expErr: true, - }, - "label empty": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Label = "" - }), - expErr: true, - }, - "init funds negative": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(-1)}} - }), - expErr: true, - }, - "init funds with duplicates": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "foo", Amount: sdk.NewInt(2)}} - }), - expErr: true, - }, - "init with empty salt": { - src: InstantiateContract2ProposalFixture(func(p *InstantiateContract2Proposal) { - p.Salt = nil - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateStoreAndInstantiateContractProposal(t *testing.T) { - var anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, ContractAddrLen) - - specs := map[string]struct { - src *StoreAndInstantiateContractProposal - expErr bool - }{ - "all good": { - src: StoreAndInstantiateContractProposalFixture(), - }, - "all good no code verification info": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Source = "" - p.Builder = "" - p.CodeHash = nil - }), - }, - "source missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Source = "" - }), - expErr: true, - }, - "builder missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Builder = "" - }), - expErr: true, - }, - "code hash missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.CodeHash = nil - }), - expErr: true, - }, - "with instantiate permission": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - accessConfig := AccessTypeOnlyAddress.With(anyAddress) - p.InstantiatePermission = &accessConfig - }), - }, - "base data missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "run_as missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.RunAs = "" - }), - expErr: true, - }, - "run_as invalid": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - "wasm code missing": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.WASMByteCode = nil - }), - expErr: true, - }, - "wasm code invalid": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.WASMByteCode = bytes.Repeat([]byte{0x0}, MaxProposalWasmSize+1) - }), - expErr: true, - }, - "with invalid instantiate permission": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.InstantiatePermission = &AccessConfig{} - }), - expErr: true, - }, - "without admin": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Admin = "" - }), - }, - "without init msg": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "with invalid init msg": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Msg = []byte("not a json string") - }), - expErr: true, - }, - "without init funds": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Funds = nil - }), - }, - "admin invalid": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Admin = invalidAddress - }), - expErr: true, - }, - "label empty": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Label = "" - }), - expErr: true, - }, - "init funds negative": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(-1)}} - }), - expErr: true, - }, - "init funds with duplicates": { - src: StoreAndInstantiateContractProposalFixture(func(p *StoreAndInstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "foo", Amount: sdk.NewInt(2)}} - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateMigrateContractProposal(t *testing.T) { - invalidAddress := "invalid address2" - - specs := map[string]struct { - src *MigrateContractProposal - expErr bool - }{ - "all good": { - src: MigrateContractProposalFixture(), - }, - "without migrate msg": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "migrate msg with invalid json": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Msg = []byte("not a json message") - }), - expErr: true, - }, - "base data missing": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - "code id empty": { - src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.CodeID = 0 - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateSudoContractProposal(t *testing.T) { - specs := map[string]struct { - src *SudoContractProposal - expErr bool - }{ - "all good": { - src: SudoContractProposalFixture(), - }, - "msg is nil": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "msg with invalid json": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Msg = []byte("not a json message") - }), - expErr: true, - }, - "base data missing": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: SudoContractProposalFixture(func(p *SudoContractProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateExecuteContractProposal(t *testing.T) { - specs := map[string]struct { - src *ExecuteContractProposal - expErr bool - }{ - "all good": { - src: ExecuteContractProposalFixture(), - }, - "msg is nil": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Msg = nil - }), - expErr: true, - }, - "msg with invalid json": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Msg = []byte("not a valid json message") - }), - expErr: true, - }, - "base data missing": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - "run as is invalid": { - src: ExecuteContractProposalFixture(func(p *ExecuteContractProposal) { - p.RunAs = invalidAddress - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateUpdateAdminProposal(t *testing.T) { - specs := map[string]struct { - src *UpdateAdminProposal - expErr bool - }{ - "all good": { - src: UpdateAdminProposalFixture(), - }, - "base data missing": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - "admin missing": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.NewAdmin = "" - }), - expErr: true, - }, - "admin invalid": { - src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.NewAdmin = invalidAddress - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestValidateClearAdminProposal(t *testing.T) { - specs := map[string]struct { - src *ClearAdminProposal - expErr bool - }{ - "all good": { - src: ClearAdminProposalFixture(), - }, - "base data missing": { - src: ClearAdminProposalFixture(func(p *ClearAdminProposal) { - p.Title = "" - }), - expErr: true, - }, - "contract missing": { - src: ClearAdminProposalFixture(func(p *ClearAdminProposal) { - p.Contract = "" - }), - expErr: true, - }, - "contract invalid": { - src: ClearAdminProposalFixture(func(p *ClearAdminProposal) { - p.Contract = invalidAddress - }), - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestProposalStrings(t *testing.T) { - specs := map[string]struct { - src v1beta1.Content - exp string - }{ - "store code": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.WASMByteCode = []byte{0o1, 0o2, 0o3, 0o4, 0o5, 0o6, 0o7, 0x08, 0x09, 0x0a} - }), - exp: `Store Code Proposal: - Title: Foo - Description: Bar - Run as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - WasmCode: 0102030405060708090A - Source: https://example.com/ - Builder: cosmwasm/workspace-optimizer:v0.12.8 - Code Hash: 6E340B9CFFB37A989CA544E6BB780A2C78901D3FB33738768511A30617AFA01D -`, - }, - "instantiate contract": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "bar", Amount: sdk.NewInt(2)}} - }), - exp: `Instantiate Code Proposal: - Title: Foo - Description: Bar - Run as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Code id: 1 - Label: testing - Msg: "{\"verifier\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\",\"beneficiary\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\"}" - Funds: 1foo,2bar -`, - }, - "instantiate contract without funds": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Funds = nil }), - exp: `Instantiate Code Proposal: - Title: Foo - Description: Bar - Run as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Code id: 1 - Label: testing - Msg: "{\"verifier\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\",\"beneficiary\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\"}" - Funds: -`, - }, - "instantiate contract without admin": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Admin = "" }), - exp: `Instantiate Code Proposal: - Title: Foo - Description: Bar - Run as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 - Admin: - Code id: 1 - Label: testing - Msg: "{\"verifier\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\",\"beneficiary\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\"}" - Funds: -`, - }, - "migrate contract": { - src: MigrateContractProposalFixture(), - exp: `Migrate Contract Proposal: - Title: Foo - Description: Bar - Contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr - Code id: 1 - Msg: "{\"verifier\":\"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4\"}" -`, - }, - "update admin": { - src: UpdateAdminProposalFixture(), - exp: `Update Contract Admin Proposal: - Title: Foo - Description: Bar - Contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr - New Admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -`, - }, - "clear admin": { - src: ClearAdminProposalFixture(), - exp: `Clear Contract Admin Proposal: - Title: Foo - Description: Bar - Contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr -`, - }, - "pin codes": { - src: &PinCodesProposal{ - Title: "Foo", - Description: "Bar", - CodeIDs: []uint64{1, 2, 3}, - }, - exp: `Pin Wasm Codes Proposal: - Title: Foo - Description: Bar - Codes: [1 2 3] -`, - }, - "unpin codes": { - src: &UnpinCodesProposal{ - Title: "Foo", - Description: "Bar", - CodeIDs: []uint64{3, 2, 1}, - }, - exp: `Unpin Wasm Codes Proposal: - Title: Foo - Description: Bar - Codes: [3 2 1] -`, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - assert.Equal(t, spec.exp, spec.src.String()) - }) - } -} - -func TestProposalYaml(t *testing.T) { - specs := map[string]struct { - src v1beta1.Content - exp string - }{ - "store code": { - src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.WASMByteCode = []byte{0o1, 0o2, 0o3, 0o4, 0o5, 0o6, 0o7, 0x08, 0x09, 0x0a} - }), - exp: `title: Foo -description: Bar -run_as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -wasm_byte_code: AQIDBAUGBwgJCg== -instantiate_permission: null -source: https://example.com/ -builder: cosmwasm/workspace-optimizer:v0.12.8 -code_hash: 6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d -`, - }, - "instantiate contract": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.Funds = sdk.Coins{{Denom: "foo", Amount: sdk.NewInt(1)}, {Denom: "bar", Amount: sdk.NewInt(2)}} - }), - exp: `title: Foo -description: Bar -run_as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -code_id: 1 -label: testing -msg: '{"verifier":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4","beneficiary":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4"}' -funds: -- denom: foo - amount: "1" -- denom: bar - amount: "2" -`, - }, - "instantiate contract without funds": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Funds = nil }), - exp: `title: Foo -description: Bar -run_as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -code_id: 1 -label: testing -msg: '{"verifier":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4","beneficiary":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4"}' -funds: [] -`, - }, - "instantiate contract without admin": { - src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { p.Admin = "" }), - exp: `title: Foo -description: Bar -run_as: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -admin: "" -code_id: 1 -label: testing -msg: '{"verifier":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4","beneficiary":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4"}' -funds: [] -`, - }, - "migrate contract": { - src: MigrateContractProposalFixture(), - exp: `title: Foo -description: Bar -contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr -code_id: 1 -msg: '{"verifier":"cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4"}' -`, - }, - "update admin": { - src: UpdateAdminProposalFixture(), - exp: `title: Foo -description: Bar -new_admin: cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4 -contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr -`, - }, - "clear admin": { - src: ClearAdminProposalFixture(), - exp: `title: Foo -description: Bar -contract: cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr -`, - }, - "pin codes": { - src: &PinCodesProposal{ - Title: "Foo", - Description: "Bar", - CodeIDs: []uint64{1, 2, 3}, - }, - exp: `title: Foo -description: Bar -code_ids: -- 1 -- 2 -- 3 -`, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - v, err := yaml.Marshal(&spec.src) - require.NoError(t, err) - assert.Equal(t, spec.exp, string(v)) - }) - } -} - -func TestConvertToProposals(t *testing.T) { - cases := map[string]struct { - input string - isError bool - proposals []ProposalType - }{ - "one proper item": { - input: "UpdateAdmin", - proposals: []ProposalType{ProposalTypeUpdateAdmin}, - }, - "multiple proper items": { - input: "StoreCode,InstantiateContract,MigrateContract", - proposals: []ProposalType{ProposalTypeStoreCode, ProposalTypeInstantiateContract, ProposalTypeMigrateContract}, - }, - "empty trailing item": { - input: "StoreCode,", - isError: true, - }, - "invalid item": { - input: "StoreCode,InvalidProposalType", - isError: true, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - chunks := strings.Split(tc.input, ",") - proposals, err := ConvertToProposals(chunks) - if tc.isError { - require.Error(t, err) - } else { - require.NoError(t, err) - require.Equal(t, proposals, tc.proposals) - } - }) - } -} - -func TestUnmarshalContentFromJson(t *testing.T) { - specs := map[string]struct { - src string - got v1beta1.Content - exp v1beta1.Content - }{ - "instantiate ": { - src: ` -{ - "title": "foo", - "description": "bar", - "admin": "myAdminAddress", - "code_id": 1, - "funds": [{"denom": "ALX", "amount": "2"},{"denom": "BLX","amount": "3"}], - "msg": {}, - "label": "testing", - "run_as": "myRunAsAddress" -}`, - got: &InstantiateContractProposal{}, - exp: &InstantiateContractProposal{ - Title: "foo", - Description: "bar", - RunAs: "myRunAsAddress", - Admin: "myAdminAddress", - CodeID: 1, - Label: "testing", - Msg: []byte("{}"), - Funds: sdk.NewCoins(sdk.NewCoin("ALX", sdk.NewInt(2)), sdk.NewCoin("BLX", sdk.NewInt(3))), - }, - }, - "migrate ": { - src: ` -{ - "title": "foo", - "description": "bar", - "code_id": 1, - "contract": "myContractAddr", - "msg": {}, - "run_as": "myRunAsAddress" -}`, - got: &MigrateContractProposal{}, - exp: &MigrateContractProposal{ - Title: "foo", - Description: "bar", - Contract: "myContractAddr", - CodeID: 1, - Msg: []byte("{}"), - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - require.NoError(t, json.Unmarshal([]byte(spec.src), spec.got)) - assert.Equal(t, spec.exp, spec.got) - }) - } -} - -func TestProposalJsonSignBytes(t *testing.T) { - const myInnerMsg = `{"foo":"bar"}` - specs := map[string]struct { - src v1beta1.Content - exp string - }{ - "instantiate contract": { - src: &InstantiateContractProposal{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"cosmos-sdk/MsgSubmitProposal", - "value":{"content":{"type":"wasm/InstantiateContractProposal","value":{"funds":[],"msg":{"foo":"bar"}}},"initial_deposit":[]} -}`, - }, - "migrate contract": { - src: &MigrateContractProposal{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"cosmos-sdk/MsgSubmitProposal", - "value":{"content":{"type":"wasm/MigrateContractProposal","value":{"msg":{"foo":"bar"}}},"initial_deposit":[]} -}`, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - msg, err := v1beta1.NewMsgSubmitProposal(spec.src, sdk.NewCoins(), []byte{}) - require.NoError(t, err) - - bz := msg.GetSignBytes() - assert.JSONEq(t, spec.exp, string(bz), "exp %s\n got: %s\n", spec.exp, string(bz)) - }) - } -} diff --git a/x/wasm/types/query.pb.go b/x/wasm/types/query.pb.go deleted file mode 100644 index 0104998..0000000 --- a/x/wasm/types/query.pb.go +++ /dev/null @@ -1,5639 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/query.proto - -package types - -import ( - bytes "bytes" - context "context" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - github_com_cometbft_cometbft_libs_bytes "github.com/cometbft/cometbft/libs/bytes" - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "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" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = 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 - -// QueryContractInfoRequest is the request type for the Query/ContractInfo RPC -// method -type QueryContractInfoRequest struct { - // address is the address of the contract to query - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` -} - -func (m *QueryContractInfoRequest) Reset() { *m = QueryContractInfoRequest{} } -func (m *QueryContractInfoRequest) String() string { return proto.CompactTextString(m) } -func (*QueryContractInfoRequest) ProtoMessage() {} -func (*QueryContractInfoRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{0} -} - -func (m *QueryContractInfoRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractInfoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractInfoRequest.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 *QueryContractInfoRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractInfoRequest.Merge(m, src) -} - -func (m *QueryContractInfoRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractInfoRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractInfoRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractInfoRequest proto.InternalMessageInfo - -// QueryContractInfoResponse is the response type for the Query/ContractInfo RPC -// method -type QueryContractInfoResponse struct { - // address is the address of the contract - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - ContractInfo `protobuf:"bytes,2,opt,name=contract_info,json=contractInfo,proto3,embedded=contract_info" json:""` -} - -func (m *QueryContractInfoResponse) Reset() { *m = QueryContractInfoResponse{} } -func (m *QueryContractInfoResponse) String() string { return proto.CompactTextString(m) } -func (*QueryContractInfoResponse) ProtoMessage() {} -func (*QueryContractInfoResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{1} -} - -func (m *QueryContractInfoResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractInfoResponse.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 *QueryContractInfoResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractInfoResponse.Merge(m, src) -} - -func (m *QueryContractInfoResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractInfoResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractInfoResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractInfoResponse proto.InternalMessageInfo - -// QueryContractHistoryRequest is the request type for the Query/ContractHistory -// RPC method -type QueryContractHistoryRequest struct { - // address is the address of the contract to query - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractHistoryRequest) Reset() { *m = QueryContractHistoryRequest{} } -func (m *QueryContractHistoryRequest) String() string { return proto.CompactTextString(m) } -func (*QueryContractHistoryRequest) ProtoMessage() {} -func (*QueryContractHistoryRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{2} -} - -func (m *QueryContractHistoryRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractHistoryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractHistoryRequest.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 *QueryContractHistoryRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractHistoryRequest.Merge(m, src) -} - -func (m *QueryContractHistoryRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractHistoryRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractHistoryRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractHistoryRequest proto.InternalMessageInfo - -// QueryContractHistoryResponse is the response type for the -// Query/ContractHistory RPC method -type QueryContractHistoryResponse struct { - Entries []ContractCodeHistoryEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractHistoryResponse) Reset() { *m = QueryContractHistoryResponse{} } -func (m *QueryContractHistoryResponse) String() string { return proto.CompactTextString(m) } -func (*QueryContractHistoryResponse) ProtoMessage() {} -func (*QueryContractHistoryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{3} -} - -func (m *QueryContractHistoryResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractHistoryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractHistoryResponse.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 *QueryContractHistoryResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractHistoryResponse.Merge(m, src) -} - -func (m *QueryContractHistoryResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractHistoryResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractHistoryResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractHistoryResponse proto.InternalMessageInfo - -// QueryContractsByCodeRequest is the request type for the Query/ContractsByCode -// RPC method -type QueryContractsByCodeRequest struct { - CodeId uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractsByCodeRequest) Reset() { *m = QueryContractsByCodeRequest{} } -func (m *QueryContractsByCodeRequest) String() string { return proto.CompactTextString(m) } -func (*QueryContractsByCodeRequest) ProtoMessage() {} -func (*QueryContractsByCodeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{4} -} - -func (m *QueryContractsByCodeRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractsByCodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractsByCodeRequest.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 *QueryContractsByCodeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractsByCodeRequest.Merge(m, src) -} - -func (m *QueryContractsByCodeRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractsByCodeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractsByCodeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractsByCodeRequest proto.InternalMessageInfo - -// QueryContractsByCodeResponse is the response type for the -// Query/ContractsByCode RPC method -type QueryContractsByCodeResponse struct { - // contracts are a set of contract addresses - Contracts []string `protobuf:"bytes,1,rep,name=contracts,proto3" json:"contracts,omitempty"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractsByCodeResponse) Reset() { *m = QueryContractsByCodeResponse{} } -func (m *QueryContractsByCodeResponse) String() string { return proto.CompactTextString(m) } -func (*QueryContractsByCodeResponse) ProtoMessage() {} -func (*QueryContractsByCodeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{5} -} - -func (m *QueryContractsByCodeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractsByCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractsByCodeResponse.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 *QueryContractsByCodeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractsByCodeResponse.Merge(m, src) -} - -func (m *QueryContractsByCodeResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractsByCodeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractsByCodeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractsByCodeResponse proto.InternalMessageInfo - -// QueryAllContractStateRequest is the request type for the -// Query/AllContractState RPC method -type QueryAllContractStateRequest struct { - // address is the address of the contract - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllContractStateRequest) Reset() { *m = QueryAllContractStateRequest{} } -func (m *QueryAllContractStateRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAllContractStateRequest) ProtoMessage() {} -func (*QueryAllContractStateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{6} -} - -func (m *QueryAllContractStateRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryAllContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllContractStateRequest.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 *QueryAllContractStateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllContractStateRequest.Merge(m, src) -} - -func (m *QueryAllContractStateRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryAllContractStateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllContractStateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllContractStateRequest proto.InternalMessageInfo - -// QueryAllContractStateResponse is the response type for the -// Query/AllContractState RPC method -type QueryAllContractStateResponse struct { - Models []Model `protobuf:"bytes,1,rep,name=models,proto3" json:"models"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllContractStateResponse) Reset() { *m = QueryAllContractStateResponse{} } -func (m *QueryAllContractStateResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAllContractStateResponse) ProtoMessage() {} -func (*QueryAllContractStateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{7} -} - -func (m *QueryAllContractStateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryAllContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllContractStateResponse.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 *QueryAllContractStateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllContractStateResponse.Merge(m, src) -} - -func (m *QueryAllContractStateResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryAllContractStateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllContractStateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllContractStateResponse proto.InternalMessageInfo - -// QueryRawContractStateRequest is the request type for the -// Query/RawContractState RPC method -type QueryRawContractStateRequest struct { - // address is the address of the contract - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - QueryData []byte `protobuf:"bytes,2,opt,name=query_data,json=queryData,proto3" json:"query_data,omitempty"` -} - -func (m *QueryRawContractStateRequest) Reset() { *m = QueryRawContractStateRequest{} } -func (m *QueryRawContractStateRequest) String() string { return proto.CompactTextString(m) } -func (*QueryRawContractStateRequest) ProtoMessage() {} -func (*QueryRawContractStateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{8} -} - -func (m *QueryRawContractStateRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryRawContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRawContractStateRequest.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 *QueryRawContractStateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRawContractStateRequest.Merge(m, src) -} - -func (m *QueryRawContractStateRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryRawContractStateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRawContractStateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRawContractStateRequest proto.InternalMessageInfo - -// QueryRawContractStateResponse is the response type for the -// Query/RawContractState RPC method -type QueryRawContractStateResponse struct { - // Data contains the raw store data - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *QueryRawContractStateResponse) Reset() { *m = QueryRawContractStateResponse{} } -func (m *QueryRawContractStateResponse) String() string { return proto.CompactTextString(m) } -func (*QueryRawContractStateResponse) ProtoMessage() {} -func (*QueryRawContractStateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{9} -} - -func (m *QueryRawContractStateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryRawContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryRawContractStateResponse.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 *QueryRawContractStateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryRawContractStateResponse.Merge(m, src) -} - -func (m *QueryRawContractStateResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryRawContractStateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryRawContractStateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryRawContractStateResponse proto.InternalMessageInfo - -// QuerySmartContractStateRequest is the request type for the -// Query/SmartContractState RPC method -type QuerySmartContractStateRequest struct { - // address is the address of the contract - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // QueryData contains the query data passed to the contract - QueryData RawContractMessage `protobuf:"bytes,2,opt,name=query_data,json=queryData,proto3,casttype=RawContractMessage" json:"query_data,omitempty"` -} - -func (m *QuerySmartContractStateRequest) Reset() { *m = QuerySmartContractStateRequest{} } -func (m *QuerySmartContractStateRequest) String() string { return proto.CompactTextString(m) } -func (*QuerySmartContractStateRequest) ProtoMessage() {} -func (*QuerySmartContractStateRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{10} -} - -func (m *QuerySmartContractStateRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QuerySmartContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySmartContractStateRequest.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 *QuerySmartContractStateRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySmartContractStateRequest.Merge(m, src) -} - -func (m *QuerySmartContractStateRequest) XXX_Size() int { - return m.Size() -} - -func (m *QuerySmartContractStateRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySmartContractStateRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySmartContractStateRequest proto.InternalMessageInfo - -// QuerySmartContractStateResponse is the response type for the -// Query/SmartContractState RPC method -type QuerySmartContractStateResponse struct { - // Data contains the json data returned from the smart contract - Data RawContractMessage `protobuf:"bytes,1,opt,name=data,proto3,casttype=RawContractMessage" json:"data,omitempty"` -} - -func (m *QuerySmartContractStateResponse) Reset() { *m = QuerySmartContractStateResponse{} } -func (m *QuerySmartContractStateResponse) String() string { return proto.CompactTextString(m) } -func (*QuerySmartContractStateResponse) ProtoMessage() {} -func (*QuerySmartContractStateResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{11} -} - -func (m *QuerySmartContractStateResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QuerySmartContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QuerySmartContractStateResponse.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 *QuerySmartContractStateResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QuerySmartContractStateResponse.Merge(m, src) -} - -func (m *QuerySmartContractStateResponse) XXX_Size() int { - return m.Size() -} - -func (m *QuerySmartContractStateResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QuerySmartContractStateResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QuerySmartContractStateResponse proto.InternalMessageInfo - -// QueryCodeRequest is the request type for the Query/Code RPC method -type QueryCodeRequest struct { - CodeId uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` -} - -func (m *QueryCodeRequest) Reset() { *m = QueryCodeRequest{} } -func (m *QueryCodeRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCodeRequest) ProtoMessage() {} -func (*QueryCodeRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{12} -} - -func (m *QueryCodeRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryCodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCodeRequest.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 *QueryCodeRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCodeRequest.Merge(m, src) -} - -func (m *QueryCodeRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryCodeRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCodeRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCodeRequest proto.InternalMessageInfo - -// CodeInfoResponse contains code meta data from CodeInfo -type CodeInfoResponse struct { - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"id"` - Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"` - DataHash github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,3,opt,name=data_hash,json=dataHash,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"data_hash,omitempty"` - InstantiatePermission AccessConfig `protobuf:"bytes,6,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission"` -} - -func (m *CodeInfoResponse) Reset() { *m = CodeInfoResponse{} } -func (m *CodeInfoResponse) String() string { return proto.CompactTextString(m) } -func (*CodeInfoResponse) ProtoMessage() {} -func (*CodeInfoResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{13} -} - -func (m *CodeInfoResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *CodeInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CodeInfoResponse.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 *CodeInfoResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_CodeInfoResponse.Merge(m, src) -} - -func (m *CodeInfoResponse) XXX_Size() int { - return m.Size() -} - -func (m *CodeInfoResponse) XXX_DiscardUnknown() { - xxx_messageInfo_CodeInfoResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_CodeInfoResponse proto.InternalMessageInfo - -// QueryCodeResponse is the response type for the Query/Code RPC method -type QueryCodeResponse struct { - *CodeInfoResponse `protobuf:"bytes,1,opt,name=code_info,json=codeInfo,proto3,embedded=code_info" json:""` - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` -} - -func (m *QueryCodeResponse) Reset() { *m = QueryCodeResponse{} } -func (m *QueryCodeResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCodeResponse) ProtoMessage() {} -func (*QueryCodeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{14} -} - -func (m *QueryCodeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCodeResponse.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 *QueryCodeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCodeResponse.Merge(m, src) -} - -func (m *QueryCodeResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryCodeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCodeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCodeResponse proto.InternalMessageInfo - -// QueryCodesRequest is the request type for the Query/Codes RPC method -type QueryCodesRequest struct { - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryCodesRequest) Reset() { *m = QueryCodesRequest{} } -func (m *QueryCodesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryCodesRequest) ProtoMessage() {} -func (*QueryCodesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{15} -} - -func (m *QueryCodesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryCodesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCodesRequest.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 *QueryCodesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCodesRequest.Merge(m, src) -} - -func (m *QueryCodesRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryCodesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCodesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCodesRequest proto.InternalMessageInfo - -// QueryCodesResponse is the response type for the Query/Codes RPC method -type QueryCodesResponse struct { - CodeInfos []CodeInfoResponse `protobuf:"bytes,1,rep,name=code_infos,json=codeInfos,proto3" json:"code_infos"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryCodesResponse) Reset() { *m = QueryCodesResponse{} } -func (m *QueryCodesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryCodesResponse) ProtoMessage() {} -func (*QueryCodesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{16} -} - -func (m *QueryCodesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryCodesResponse.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 *QueryCodesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryCodesResponse.Merge(m, src) -} - -func (m *QueryCodesResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryCodesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryCodesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryCodesResponse proto.InternalMessageInfo - -// QueryPinnedCodesRequest is the request type for the Query/PinnedCodes -// RPC method -type QueryPinnedCodesRequest struct { - // pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPinnedCodesRequest) Reset() { *m = QueryPinnedCodesRequest{} } -func (m *QueryPinnedCodesRequest) String() string { return proto.CompactTextString(m) } -func (*QueryPinnedCodesRequest) ProtoMessage() {} -func (*QueryPinnedCodesRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{17} -} - -func (m *QueryPinnedCodesRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryPinnedCodesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPinnedCodesRequest.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 *QueryPinnedCodesRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPinnedCodesRequest.Merge(m, src) -} - -func (m *QueryPinnedCodesRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryPinnedCodesRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPinnedCodesRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPinnedCodesRequest proto.InternalMessageInfo - -// QueryPinnedCodesResponse is the response type for the -// Query/PinnedCodes RPC method -type QueryPinnedCodesResponse struct { - CodeIDs []uint64 `protobuf:"varint,1,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty"` - // pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryPinnedCodesResponse) Reset() { *m = QueryPinnedCodesResponse{} } -func (m *QueryPinnedCodesResponse) String() string { return proto.CompactTextString(m) } -func (*QueryPinnedCodesResponse) ProtoMessage() {} -func (*QueryPinnedCodesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{18} -} - -func (m *QueryPinnedCodesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryPinnedCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryPinnedCodesResponse.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 *QueryPinnedCodesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryPinnedCodesResponse.Merge(m, src) -} - -func (m *QueryPinnedCodesResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryPinnedCodesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryPinnedCodesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryPinnedCodesResponse proto.InternalMessageInfo - -// QueryParamsRequest is the 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_9677c207036b9f2b, []int{19} -} - -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 the response type for the Query/Params RPC method. -type QueryParamsResponse struct { - // params defines the parameters of the 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_9677c207036b9f2b, []int{20} -} - -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 - -// QueryContractsByCreatorRequest is the request type for the -// Query/ContractsByCreator RPC method. -type QueryContractsByCreatorRequest struct { - // CreatorAddress is the address of contract creator - CreatorAddress string `protobuf:"bytes,1,opt,name=creator_address,json=creatorAddress,proto3" json:"creator_address,omitempty"` - // Pagination defines an optional pagination for the request. - Pagination *query.PageRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractsByCreatorRequest) Reset() { *m = QueryContractsByCreatorRequest{} } -func (m *QueryContractsByCreatorRequest) String() string { return proto.CompactTextString(m) } -func (*QueryContractsByCreatorRequest) ProtoMessage() {} -func (*QueryContractsByCreatorRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{21} -} - -func (m *QueryContractsByCreatorRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractsByCreatorRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractsByCreatorRequest.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 *QueryContractsByCreatorRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractsByCreatorRequest.Merge(m, src) -} - -func (m *QueryContractsByCreatorRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractsByCreatorRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractsByCreatorRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractsByCreatorRequest proto.InternalMessageInfo - -// QueryContractsByCreatorResponse is the response type for the -// Query/ContractsByCreator RPC method. -type QueryContractsByCreatorResponse struct { - // ContractAddresses result set - ContractAddresses []string `protobuf:"bytes,1,rep,name=contract_addresses,json=contractAddresses,proto3" json:"contract_addresses,omitempty"` - // Pagination defines the pagination in the response. - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryContractsByCreatorResponse) Reset() { *m = QueryContractsByCreatorResponse{} } -func (m *QueryContractsByCreatorResponse) String() string { return proto.CompactTextString(m) } -func (*QueryContractsByCreatorResponse) ProtoMessage() {} -func (*QueryContractsByCreatorResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_9677c207036b9f2b, []int{22} -} - -func (m *QueryContractsByCreatorResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryContractsByCreatorResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryContractsByCreatorResponse.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 *QueryContractsByCreatorResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryContractsByCreatorResponse.Merge(m, src) -} - -func (m *QueryContractsByCreatorResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryContractsByCreatorResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryContractsByCreatorResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryContractsByCreatorResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*QueryContractInfoRequest)(nil), "cosmwasm.wasm.v1.QueryContractInfoRequest") - proto.RegisterType((*QueryContractInfoResponse)(nil), "cosmwasm.wasm.v1.QueryContractInfoResponse") - proto.RegisterType((*QueryContractHistoryRequest)(nil), "cosmwasm.wasm.v1.QueryContractHistoryRequest") - proto.RegisterType((*QueryContractHistoryResponse)(nil), "cosmwasm.wasm.v1.QueryContractHistoryResponse") - proto.RegisterType((*QueryContractsByCodeRequest)(nil), "cosmwasm.wasm.v1.QueryContractsByCodeRequest") - proto.RegisterType((*QueryContractsByCodeResponse)(nil), "cosmwasm.wasm.v1.QueryContractsByCodeResponse") - proto.RegisterType((*QueryAllContractStateRequest)(nil), "cosmwasm.wasm.v1.QueryAllContractStateRequest") - proto.RegisterType((*QueryAllContractStateResponse)(nil), "cosmwasm.wasm.v1.QueryAllContractStateResponse") - proto.RegisterType((*QueryRawContractStateRequest)(nil), "cosmwasm.wasm.v1.QueryRawContractStateRequest") - proto.RegisterType((*QueryRawContractStateResponse)(nil), "cosmwasm.wasm.v1.QueryRawContractStateResponse") - proto.RegisterType((*QuerySmartContractStateRequest)(nil), "cosmwasm.wasm.v1.QuerySmartContractStateRequest") - proto.RegisterType((*QuerySmartContractStateResponse)(nil), "cosmwasm.wasm.v1.QuerySmartContractStateResponse") - proto.RegisterType((*QueryCodeRequest)(nil), "cosmwasm.wasm.v1.QueryCodeRequest") - proto.RegisterType((*CodeInfoResponse)(nil), "cosmwasm.wasm.v1.CodeInfoResponse") - proto.RegisterType((*QueryCodeResponse)(nil), "cosmwasm.wasm.v1.QueryCodeResponse") - proto.RegisterType((*QueryCodesRequest)(nil), "cosmwasm.wasm.v1.QueryCodesRequest") - proto.RegisterType((*QueryCodesResponse)(nil), "cosmwasm.wasm.v1.QueryCodesResponse") - proto.RegisterType((*QueryPinnedCodesRequest)(nil), "cosmwasm.wasm.v1.QueryPinnedCodesRequest") - proto.RegisterType((*QueryPinnedCodesResponse)(nil), "cosmwasm.wasm.v1.QueryPinnedCodesResponse") - proto.RegisterType((*QueryParamsRequest)(nil), "cosmwasm.wasm.v1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "cosmwasm.wasm.v1.QueryParamsResponse") - proto.RegisterType((*QueryContractsByCreatorRequest)(nil), "cosmwasm.wasm.v1.QueryContractsByCreatorRequest") - proto.RegisterType((*QueryContractsByCreatorResponse)(nil), "cosmwasm.wasm.v1.QueryContractsByCreatorResponse") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/query.proto", fileDescriptor_9677c207036b9f2b) } - -var fileDescriptor_9677c207036b9f2b = []byte{ - // 1355 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x98, 0xcf, 0x6f, 0x1b, 0x45, - 0x1b, 0xc7, 0x3d, 0xa9, 0xe3, 0x1f, 0x93, 0xf6, 0xad, 0x33, 0x6f, 0x69, 0x8d, 0x49, 0xd7, 0xd1, - 0x52, 0xd2, 0xd4, 0x6d, 0x76, 0x9b, 0xb4, 0x55, 0x45, 0x11, 0x42, 0x71, 0x0b, 0xb4, 0x15, 0x55, - 0xd3, 0xad, 0x04, 0x12, 0x1c, 0xcc, 0x78, 0x3d, 0x71, 0x56, 0xc4, 0x3b, 0xce, 0xce, 0x24, 0xa9, - 0x15, 0x05, 0x50, 0x25, 0x4e, 0x70, 0x00, 0x55, 0x1c, 0xb8, 0x20, 0x0e, 0x15, 0x54, 0xe2, 0x82, - 0x38, 0x55, 0x5c, 0xb9, 0xe4, 0x18, 0x89, 0x0b, 0x27, 0x0b, 0x1c, 0x24, 0x50, 0xfe, 0x84, 0x9e, - 0xd0, 0xce, 0xce, 0xda, 0xbb, 0xb6, 0x37, 0x76, 0x2a, 0x8b, 0x8b, 0xb5, 0xbb, 0x33, 0xcf, 0xcc, - 0xe7, 0xf9, 0xce, 0x33, 0xcf, 0xf3, 0xc8, 0x70, 0xca, 0xa4, 0xac, 0xb6, 0x89, 0x59, 0x4d, 0x17, - 0x3f, 0x1b, 0xf3, 0xfa, 0xda, 0x3a, 0x71, 0x1a, 0x5a, 0xdd, 0xa1, 0x9c, 0xa2, 0x8c, 0x3f, 0xaa, - 0x89, 0x9f, 0x8d, 0xf9, 0xdc, 0x89, 0x2a, 0xad, 0x52, 0x31, 0xa8, 0xbb, 0x4f, 0xde, 0xbc, 0x5c, - 0xef, 0x2a, 0xbc, 0x51, 0x27, 0xcc, 0x1f, 0xad, 0x52, 0x5a, 0x5d, 0x25, 0x3a, 0xae, 0x5b, 0x3a, - 0xb6, 0x6d, 0xca, 0x31, 0xb7, 0xa8, 0xed, 0x8f, 0x16, 0x5c, 0x5b, 0xca, 0xf4, 0x32, 0x66, 0xc4, - 0xdb, 0x5c, 0xdf, 0x98, 0x2f, 0x13, 0x8e, 0xe7, 0xf5, 0x3a, 0xae, 0x5a, 0xb6, 0x98, 0x2c, 0xe7, - 0x4e, 0xe2, 0x9a, 0x65, 0x53, 0x5d, 0xfc, 0x7a, 0x9f, 0xd4, 0xcb, 0x30, 0x7b, 0xcf, 0x35, 0xba, - 0x4e, 0x6d, 0xee, 0x60, 0x93, 0xdf, 0xb2, 0x97, 0xa9, 0x41, 0xd6, 0xd6, 0x09, 0xe3, 0x28, 0x0b, - 0x93, 0xb8, 0x52, 0x71, 0x08, 0x63, 0x59, 0x30, 0x0d, 0x66, 0xd3, 0x86, 0xff, 0xaa, 0x3e, 0x02, - 0xf0, 0xc5, 0x3e, 0x66, 0xac, 0x4e, 0x6d, 0x46, 0xa2, 0xed, 0xd0, 0xbb, 0xf0, 0x98, 0x29, 0x2d, - 0x4a, 0x96, 0xbd, 0x4c, 0xb3, 0x63, 0xd3, 0x60, 0x76, 0x62, 0x41, 0xd1, 0xba, 0x85, 0xd2, 0x82, - 0x0b, 0x17, 0x27, 0x77, 0x9a, 0xf9, 0xd8, 0x6e, 0x33, 0x0f, 0xf6, 0x9b, 0xf9, 0xd8, 0x93, 0xbf, - 0x7f, 0x2a, 0x00, 0xe3, 0xa8, 0x19, 0x98, 0x70, 0x2d, 0xfe, 0xcf, 0x77, 0x79, 0xa0, 0x7e, 0x02, - 0x5f, 0x0a, 0x41, 0xdd, 0xb4, 0x18, 0xa7, 0x4e, 0x63, 0xa0, 0x3b, 0xe8, 0x2d, 0x08, 0x3b, 0x5a, - 0x49, 0xa6, 0x19, 0xcd, 0x13, 0x56, 0x73, 0x85, 0xd5, 0xbc, 0x53, 0x95, 0xc2, 0x6a, 0x4b, 0xb8, - 0x4a, 0xe4, 0xaa, 0x46, 0xc0, 0x52, 0x7d, 0x0a, 0xe0, 0x54, 0x7f, 0x02, 0xa9, 0xcc, 0x5d, 0x98, - 0x24, 0x36, 0x77, 0x2c, 0xe2, 0x22, 0x1c, 0x99, 0x9d, 0x58, 0x28, 0x44, 0x7b, 0x7e, 0x9d, 0x56, - 0x88, 0xb4, 0x7f, 0xd3, 0xe6, 0x4e, 0xa3, 0x98, 0xde, 0x69, 0x7b, 0xef, 0xaf, 0x82, 0xde, 0xee, - 0x43, 0x7e, 0x76, 0x20, 0xb9, 0x47, 0x13, 0x42, 0xff, 0xb8, 0x4b, 0x3b, 0x56, 0x6c, 0xb8, 0x00, - 0xbe, 0x76, 0xa7, 0x60, 0xd2, 0xa4, 0x15, 0x52, 0xb2, 0x2a, 0x42, 0xbb, 0xb8, 0x91, 0x70, 0x5f, - 0x6f, 0x55, 0x46, 0x26, 0xdd, 0x67, 0xdd, 0xd2, 0xb5, 0x01, 0xa4, 0x74, 0x53, 0x30, 0xed, 0x1f, - 0xb9, 0x27, 0x5e, 0xda, 0xe8, 0x7c, 0x18, 0x9d, 0x0e, 0x9f, 0xfa, 0x1c, 0x8b, 0xab, 0xab, 0x3e, - 0xca, 0x7d, 0x8e, 0x39, 0xf9, 0xef, 0xa2, 0xe8, 0x31, 0x80, 0xa7, 0x23, 0x10, 0xa4, 0x16, 0xd7, - 0x60, 0xa2, 0x46, 0x2b, 0x64, 0xd5, 0x8f, 0xa2, 0x53, 0xbd, 0x51, 0x74, 0xc7, 0x1d, 0x0f, 0x86, - 0x8c, 0xb4, 0x18, 0x9d, 0x52, 0xef, 0x49, 0xa1, 0x0c, 0xbc, 0x79, 0x48, 0xa1, 0x4e, 0x43, 0x28, - 0xf6, 0x28, 0x55, 0x30, 0xc7, 0x02, 0xe1, 0xa8, 0x91, 0x16, 0x5f, 0x6e, 0x60, 0x8e, 0xd5, 0x4b, - 0xd2, 0xfd, 0xde, 0x85, 0xa5, 0xfb, 0x08, 0xc6, 0x85, 0x25, 0x10, 0x96, 0xe2, 0x59, 0x5d, 0x83, - 0x8a, 0x30, 0xba, 0x5f, 0xc3, 0x0e, 0x3f, 0x24, 0xcf, 0x95, 0x5e, 0x9e, 0xe2, 0xc9, 0x67, 0xcd, - 0x3c, 0x0a, 0x10, 0xdc, 0x21, 0x8c, 0xb9, 0x4a, 0x04, 0x38, 0xef, 0xc0, 0x7c, 0xe4, 0x96, 0x92, - 0xb4, 0x10, 0x24, 0x8d, 0x5c, 0xd3, 0xf3, 0xe0, 0x3c, 0xcc, 0xc8, 0x0b, 0x30, 0xf8, 0xda, 0xa9, - 0xdf, 0x8e, 0xc1, 0x8c, 0x3b, 0x31, 0x94, 0x77, 0xcf, 0x75, 0xcd, 0x2e, 0x66, 0x5a, 0xcd, 0x7c, - 0x42, 0x4c, 0xbb, 0xb1, 0xdf, 0xcc, 0x8f, 0x59, 0x95, 0xf6, 0xb5, 0xcd, 0xc2, 0xa4, 0xe9, 0x10, - 0xcc, 0xa9, 0x23, 0xfc, 0x4d, 0x1b, 0xfe, 0x2b, 0xba, 0x07, 0xd3, 0x2e, 0x4e, 0x69, 0x05, 0xb3, - 0x95, 0xec, 0x11, 0xc1, 0x7d, 0xf9, 0x59, 0x33, 0x7f, 0xb1, 0x6a, 0xf1, 0x95, 0xf5, 0xb2, 0x66, - 0xd2, 0x9a, 0x6e, 0xd2, 0x1a, 0xe1, 0xe5, 0x65, 0xde, 0x79, 0x58, 0xb5, 0xca, 0x4c, 0x2f, 0x37, - 0x38, 0x61, 0xda, 0x4d, 0xf2, 0xa0, 0xe8, 0x3e, 0x18, 0x29, 0x77, 0x99, 0x9b, 0x98, 0xad, 0xa0, - 0x0f, 0xe1, 0x49, 0xcb, 0x66, 0x1c, 0xdb, 0xdc, 0xc2, 0x9c, 0x94, 0xea, 0xc4, 0xa9, 0x59, 0x8c, - 0xb9, 0xe1, 0x97, 0x88, 0x4a, 0xff, 0x8b, 0xa6, 0x49, 0x18, 0xbb, 0x4e, 0xed, 0x65, 0xab, 0x1a, - 0x8c, 0xe2, 0x17, 0x02, 0x0b, 0x2d, 0xb5, 0xd7, 0xf1, 0xf2, 0xff, 0xed, 0x78, 0x2a, 0x9e, 0x19, - 0xbf, 0x1d, 0x4f, 0x8d, 0x67, 0x12, 0xea, 0x43, 0x00, 0x27, 0x03, 0x72, 0x4a, 0x85, 0x6e, 0xb9, - 0x49, 0xc4, 0x55, 0xc8, 0xad, 0x3d, 0x40, 0x6c, 0xae, 0xf6, 0xcb, 0xc0, 0x61, 0x61, 0x8b, 0x29, - 0xbf, 0xf6, 0x18, 0x29, 0x53, 0x8e, 0xa1, 0x29, 0x79, 0xb4, 0x5e, 0xb8, 0xa4, 0xf6, 0x9b, 0x79, - 0xf1, 0xee, 0x1d, 0xa6, 0x2c, 0x48, 0x1f, 0x04, 0x18, 0x98, 0x7f, 0xa6, 0xe1, 0x34, 0x01, 0x9e, - 0x3b, 0x4d, 0xfc, 0x08, 0x20, 0x0a, 0xae, 0x2e, 0x5d, 0x7c, 0x07, 0xc2, 0xb6, 0x8b, 0x7e, 0x7e, - 0x18, 0xc6, 0xc7, 0x80, 0xc8, 0x69, 0xdf, 0xc9, 0x11, 0x66, 0x0b, 0x0c, 0x4f, 0x09, 0xd8, 0x25, - 0xcb, 0xb6, 0x49, 0xe5, 0x00, 0x41, 0x9e, 0x3f, 0x6f, 0x7e, 0x0e, 0x64, 0x2f, 0x13, 0xda, 0x43, - 0xca, 0x32, 0x03, 0x53, 0xf2, 0x6e, 0x78, 0xa2, 0xc4, 0x8b, 0x13, 0xad, 0x66, 0x3e, 0xe9, 0x5d, - 0x0e, 0x66, 0x24, 0xbd, 0x7b, 0x31, 0x42, 0x87, 0x4f, 0xc8, 0xd3, 0x59, 0xc2, 0x0e, 0xae, 0xf9, - 0xbe, 0xaa, 0x06, 0xfc, 0x7f, 0xe8, 0xab, 0xa4, 0x7b, 0x0d, 0x26, 0xea, 0xe2, 0x8b, 0x8c, 0x87, - 0x6c, 0xef, 0x81, 0x79, 0x16, 0xa1, 0x8c, 0xee, 0x99, 0xa8, 0x5f, 0x01, 0x99, 0xfb, 0x82, 0xa5, - 0xd3, 0xbb, 0xcd, 0xbe, 0xc4, 0x67, 0xe1, 0x71, 0x79, 0xbf, 0x4b, 0xe1, 0x1c, 0xf8, 0x3f, 0xf9, - 0x79, 0x71, 0xc4, 0x35, 0xec, 0x1b, 0x20, 0x93, 0x63, 0x3f, 0x26, 0xe9, 0xf4, 0x1c, 0x44, 0xed, - 0x66, 0x50, 0x52, 0x11, 0xbf, 0xb4, 0x4f, 0xfa, 0x23, 0x8b, 0xfe, 0xc0, 0xc8, 0x4e, 0x66, 0xe1, - 0xd7, 0x63, 0x70, 0x5c, 0xb0, 0xa1, 0xaf, 0x01, 0x3c, 0x1a, 0x6c, 0x34, 0x51, 0x9f, 0x76, 0x2c, - 0xaa, 0x3b, 0xce, 0x9d, 0x1f, 0x6a, 0xae, 0xb7, 0xbf, 0x7a, 0xe1, 0xe1, 0x6f, 0x7f, 0x3d, 0x1a, - 0x9b, 0x41, 0x67, 0xf4, 0x9e, 0x56, 0xdf, 0xf7, 0x54, 0xdf, 0x92, 0x22, 0x6c, 0xa3, 0xef, 0x01, - 0x3c, 0xde, 0xd5, 0x42, 0xa2, 0xb9, 0x01, 0xdb, 0x85, 0x9b, 0xdd, 0x9c, 0x36, 0xec, 0x74, 0x09, - 0x78, 0x59, 0x00, 0x6a, 0xe8, 0xc2, 0x30, 0x80, 0xfa, 0x8a, 0x84, 0x7a, 0x1c, 0x00, 0x95, 0x0d, - 0xdb, 0x40, 0xd0, 0x70, 0x67, 0x39, 0x10, 0xb4, 0xab, 0x0f, 0x54, 0x17, 0x04, 0xe8, 0x05, 0x54, - 0xe8, 0x07, 0x5a, 0x21, 0xfa, 0x96, 0xbc, 0xe6, 0xdb, 0x7a, 0xa7, 0x3b, 0xfc, 0x01, 0xc0, 0x4c, - 0x77, 0x33, 0x85, 0xa2, 0x36, 0x8e, 0x68, 0xfc, 0x72, 0xfa, 0xd0, 0xf3, 0x87, 0x21, 0xed, 0x91, - 0x94, 0x09, 0xa8, 0x9f, 0x01, 0xcc, 0x74, 0xf7, 0x3d, 0x91, 0xa4, 0x11, 0x9d, 0x57, 0x24, 0x69, - 0x54, 0x43, 0xa5, 0xbe, 0x2e, 0x48, 0xaf, 0xa2, 0x2b, 0x43, 0x91, 0x3a, 0x78, 0x53, 0xdf, 0xea, - 0x34, 0x4c, 0xdb, 0xe8, 0x17, 0x00, 0x51, 0x6f, 0x13, 0x84, 0x2e, 0x46, 0x60, 0x44, 0xb6, 0x68, - 0xb9, 0xf9, 0x43, 0x58, 0x48, 0xf4, 0x37, 0x04, 0xfa, 0xab, 0xe8, 0xea, 0x70, 0x22, 0xbb, 0x0b, - 0x85, 0xe1, 0x1b, 0x30, 0x2e, 0xc2, 0x56, 0x8d, 0x8c, 0xc3, 0x4e, 0xac, 0xbe, 0x7c, 0xe0, 0x1c, - 0x49, 0x34, 0x2b, 0x88, 0x54, 0x34, 0x3d, 0x28, 0x40, 0x91, 0x03, 0xc7, 0x45, 0x91, 0x42, 0x07, - 0xad, 0xeb, 0x97, 0x8e, 0xdc, 0x99, 0x83, 0x27, 0xc9, 0xdd, 0x15, 0xb1, 0x7b, 0x16, 0x9d, 0xec, - 0xbf, 0x3b, 0xfa, 0x02, 0xc0, 0x89, 0x40, 0x7d, 0x44, 0xe7, 0x22, 0x56, 0xed, 0xad, 0xd3, 0xb9, - 0xc2, 0x30, 0x53, 0x25, 0xc6, 0x8c, 0xc0, 0x98, 0x46, 0x4a, 0x7f, 0x0c, 0xa6, 0xd7, 0x85, 0x11, - 0xda, 0x86, 0x09, 0xaf, 0xb0, 0xa1, 0x28, 0xf7, 0x42, 0xf5, 0x33, 0xf7, 0xca, 0x80, 0x59, 0x43, - 0x6f, 0xef, 0x6d, 0xfa, 0x14, 0x40, 0xd4, 0x5b, 0xa1, 0x22, 0x23, 0x37, 0xb2, 0xc0, 0x46, 0x46, - 0x6e, 0x74, 0xf9, 0x1b, 0xe6, 0xd2, 0x31, 0x5d, 0x96, 0x67, 0x7d, 0xab, 0xab, 0x7c, 0x6f, 0x17, - 0xef, 0xee, 0xfc, 0xa9, 0xc4, 0x9e, 0xb4, 0x94, 0xd8, 0x4e, 0x4b, 0x01, 0xbb, 0x2d, 0x05, 0xfc, - 0xd1, 0x52, 0xc0, 0x97, 0x7b, 0x4a, 0x6c, 0x77, 0x4f, 0x89, 0xfd, 0xbe, 0xa7, 0xc4, 0xde, 0x9f, - 0x0b, 0xb4, 0xec, 0x9c, 0x38, 0x75, 0x9b, 0xf0, 0x4d, 0xea, 0x7c, 0x24, 0x9e, 0xe7, 0x4c, 0xea, - 0x10, 0xfd, 0x81, 0xb7, 0xa3, 0xf8, 0xb3, 0xa9, 0x9c, 0x10, 0x7f, 0x08, 0x5d, 0xfa, 0x37, 0x00, - 0x00, 0xff, 0xff, 0x16, 0xa8, 0x59, 0xd9, 0xd3, 0x12, 0x00, 0x00, -} - -func (this *QueryContractInfoResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryContractInfoResponse) - if !ok { - that2, ok := that.(QueryContractInfoResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Address != that1.Address { - return false - } - if !this.ContractInfo.Equal(&that1.ContractInfo) { - return false - } - return true -} - -func (this *CodeInfoResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*CodeInfoResponse) - if !ok { - that2, ok := that.(CodeInfoResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if this.Creator != that1.Creator { - return false - } - if !bytes.Equal(this.DataHash, that1.DataHash) { - return false - } - if !this.InstantiatePermission.Equal(&that1.InstantiatePermission) { - return false - } - return true -} - -func (this *QueryCodeResponse) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*QueryCodeResponse) - if !ok { - that2, ok := that.(QueryCodeResponse) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.CodeInfoResponse.Equal(that1.CodeInfoResponse) { - return false - } - if !bytes.Equal(this.Data, that1.Data) { - return false - } - return true -} - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ context.Context - _ 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 { - // ContractInfo gets the contract meta data - ContractInfo(ctx context.Context, in *QueryContractInfoRequest, opts ...grpc.CallOption) (*QueryContractInfoResponse, error) - // ContractHistory gets the contract code history - ContractHistory(ctx context.Context, in *QueryContractHistoryRequest, opts ...grpc.CallOption) (*QueryContractHistoryResponse, error) - // ContractsByCode lists all smart contracts for a code id - ContractsByCode(ctx context.Context, in *QueryContractsByCodeRequest, opts ...grpc.CallOption) (*QueryContractsByCodeResponse, error) - // AllContractState gets all raw store data for a single contract - AllContractState(ctx context.Context, in *QueryAllContractStateRequest, opts ...grpc.CallOption) (*QueryAllContractStateResponse, error) - // RawContractState gets single key from the raw store data of a contract - RawContractState(ctx context.Context, in *QueryRawContractStateRequest, opts ...grpc.CallOption) (*QueryRawContractStateResponse, error) - // SmartContractState get smart query result from the contract - SmartContractState(ctx context.Context, in *QuerySmartContractStateRequest, opts ...grpc.CallOption) (*QuerySmartContractStateResponse, error) - // Code gets the binary code and metadata for a singe wasm code - Code(ctx context.Context, in *QueryCodeRequest, opts ...grpc.CallOption) (*QueryCodeResponse, error) - // Codes gets the metadata for all stored wasm codes - Codes(ctx context.Context, in *QueryCodesRequest, opts ...grpc.CallOption) (*QueryCodesResponse, error) - // PinnedCodes gets the pinned code ids - PinnedCodes(ctx context.Context, in *QueryPinnedCodesRequest, opts ...grpc.CallOption) (*QueryPinnedCodesResponse, error) - // Params gets the module params - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // ContractsByCreator gets the contracts by creator - ContractsByCreator(ctx context.Context, in *QueryContractsByCreatorRequest, opts ...grpc.CallOption) (*QueryContractsByCreatorResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) ContractInfo(ctx context.Context, in *QueryContractInfoRequest, opts ...grpc.CallOption) (*QueryContractInfoResponse, error) { - out := new(QueryContractInfoResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractInfo", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ContractHistory(ctx context.Context, in *QueryContractHistoryRequest, opts ...grpc.CallOption) (*QueryContractHistoryResponse, error) { - out := new(QueryContractHistoryResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractHistory", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ContractsByCode(ctx context.Context, in *QueryContractsByCodeRequest, opts ...grpc.CallOption) (*QueryContractsByCodeResponse, error) { - out := new(QueryContractsByCodeResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractsByCode", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) AllContractState(ctx context.Context, in *QueryAllContractStateRequest, opts ...grpc.CallOption) (*QueryAllContractStateResponse, error) { - out := new(QueryAllContractStateResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/AllContractState", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) RawContractState(ctx context.Context, in *QueryRawContractStateRequest, opts ...grpc.CallOption) (*QueryRawContractStateResponse, error) { - out := new(QueryRawContractStateResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/RawContractState", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) SmartContractState(ctx context.Context, in *QuerySmartContractStateRequest, opts ...grpc.CallOption) (*QuerySmartContractStateResponse, error) { - out := new(QuerySmartContractStateResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/SmartContractState", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Code(ctx context.Context, in *QueryCodeRequest, opts ...grpc.CallOption) (*QueryCodeResponse, error) { - out := new(QueryCodeResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/Code", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Codes(ctx context.Context, in *QueryCodesRequest, opts ...grpc.CallOption) (*QueryCodesResponse, error) { - out := new(QueryCodesResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/Codes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) PinnedCodes(ctx context.Context, in *QueryPinnedCodesRequest, opts ...grpc.CallOption) (*QueryPinnedCodesResponse, error) { - out := new(QueryPinnedCodesResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/PinnedCodes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) ContractsByCreator(ctx context.Context, in *QueryContractsByCreatorRequest, opts ...grpc.CallOption) (*QueryContractsByCreatorResponse, error) { - out := new(QueryContractsByCreatorResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Query/ContractsByCreator", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // ContractInfo gets the contract meta data - ContractInfo(context.Context, *QueryContractInfoRequest) (*QueryContractInfoResponse, error) - // ContractHistory gets the contract code history - ContractHistory(context.Context, *QueryContractHistoryRequest) (*QueryContractHistoryResponse, error) - // ContractsByCode lists all smart contracts for a code id - ContractsByCode(context.Context, *QueryContractsByCodeRequest) (*QueryContractsByCodeResponse, error) - // AllContractState gets all raw store data for a single contract - AllContractState(context.Context, *QueryAllContractStateRequest) (*QueryAllContractStateResponse, error) - // RawContractState gets single key from the raw store data of a contract - RawContractState(context.Context, *QueryRawContractStateRequest) (*QueryRawContractStateResponse, error) - // SmartContractState get smart query result from the contract - SmartContractState(context.Context, *QuerySmartContractStateRequest) (*QuerySmartContractStateResponse, error) - // Code gets the binary code and metadata for a singe wasm code - Code(context.Context, *QueryCodeRequest) (*QueryCodeResponse, error) - // Codes gets the metadata for all stored wasm codes - Codes(context.Context, *QueryCodesRequest) (*QueryCodesResponse, error) - // PinnedCodes gets the pinned code ids - PinnedCodes(context.Context, *QueryPinnedCodesRequest) (*QueryPinnedCodesResponse, error) - // Params gets the module params - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // ContractsByCreator gets the contracts by creator - ContractsByCreator(context.Context, *QueryContractsByCreatorRequest) (*QueryContractsByCreatorResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct{} - -func (*UnimplementedQueryServer) ContractInfo(ctx context.Context, req *QueryContractInfoRequest) (*QueryContractInfoResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ContractInfo not implemented") -} - -func (*UnimplementedQueryServer) ContractHistory(ctx context.Context, req *QueryContractHistoryRequest) (*QueryContractHistoryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ContractHistory not implemented") -} - -func (*UnimplementedQueryServer) ContractsByCode(ctx context.Context, req *QueryContractsByCodeRequest) (*QueryContractsByCodeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ContractsByCode not implemented") -} - -func (*UnimplementedQueryServer) AllContractState(ctx context.Context, req *QueryAllContractStateRequest) (*QueryAllContractStateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method AllContractState not implemented") -} - -func (*UnimplementedQueryServer) RawContractState(ctx context.Context, req *QueryRawContractStateRequest) (*QueryRawContractStateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RawContractState not implemented") -} - -func (*UnimplementedQueryServer) SmartContractState(ctx context.Context, req *QuerySmartContractStateRequest) (*QuerySmartContractStateResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SmartContractState not implemented") -} - -func (*UnimplementedQueryServer) Code(ctx context.Context, req *QueryCodeRequest) (*QueryCodeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Code not implemented") -} - -func (*UnimplementedQueryServer) Codes(ctx context.Context, req *QueryCodesRequest) (*QueryCodesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Codes not implemented") -} - -func (*UnimplementedQueryServer) PinnedCodes(ctx context.Context, req *QueryPinnedCodesRequest) (*QueryPinnedCodesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PinnedCodes not implemented") -} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} - -func (*UnimplementedQueryServer) ContractsByCreator(ctx context.Context, req *QueryContractsByCreatorRequest) (*QueryContractsByCreatorResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ContractsByCreator not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_ContractInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryContractInfoRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ContractInfo(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/ContractInfo", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ContractInfo(ctx, req.(*QueryContractInfoRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ContractHistory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryContractHistoryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ContractHistory(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/ContractHistory", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ContractHistory(ctx, req.(*QueryContractHistoryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ContractsByCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryContractsByCodeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ContractsByCode(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/ContractsByCode", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ContractsByCode(ctx, req.(*QueryContractsByCodeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_AllContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAllContractStateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).AllContractState(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/AllContractState", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).AllContractState(ctx, req.(*QueryAllContractStateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_RawContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRawContractStateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).RawContractState(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/RawContractState", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).RawContractState(ctx, req.(*QueryRawContractStateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_SmartContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QuerySmartContractStateRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).SmartContractState(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/SmartContractState", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).SmartContractState(ctx, req.(*QuerySmartContractStateRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Code_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCodeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Code(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/Code", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Code(ctx, req.(*QueryCodeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Codes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryCodesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Codes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/Codes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Codes(ctx, req.(*QueryCodesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_PinnedCodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryPinnedCodesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).PinnedCodes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/PinnedCodes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).PinnedCodes(ctx, req.(*QueryPinnedCodesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -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: "/cosmwasm.wasm.v1.Query/Params", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_ContractsByCreator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryContractsByCreatorRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).ContractsByCreator(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Query/ContractsByCreator", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).ContractsByCreator(ctx, req.(*QueryContractsByCreatorRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmwasm.wasm.v1.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "ContractInfo", - Handler: _Query_ContractInfo_Handler, - }, - { - MethodName: "ContractHistory", - Handler: _Query_ContractHistory_Handler, - }, - { - MethodName: "ContractsByCode", - Handler: _Query_ContractsByCode_Handler, - }, - { - MethodName: "AllContractState", - Handler: _Query_AllContractState_Handler, - }, - { - MethodName: "RawContractState", - Handler: _Query_RawContractState_Handler, - }, - { - MethodName: "SmartContractState", - Handler: _Query_SmartContractState_Handler, - }, - { - MethodName: "Code", - Handler: _Query_Code_Handler, - }, - { - MethodName: "Codes", - Handler: _Query_Codes_Handler, - }, - { - MethodName: "PinnedCodes", - Handler: _Query_PinnedCodes_Handler, - }, - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "ContractsByCreator", - Handler: _Query_ContractsByCreator_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmwasm/wasm/v1/query.proto", -} - -func (m *QueryContractInfoRequest) 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 *QueryContractInfoRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractInfoRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryContractInfoResponse) 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 *QueryContractInfoResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.ContractInfo.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryContractHistoryRequest) 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 *QueryContractHistoryRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractHistoryRequest) 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.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryContractHistoryResponse) 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 *QueryContractHistoryResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractHistoryResponse) 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.Entries) > 0 { - for iNdEx := len(m.Entries) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Entries[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryContractsByCodeRequest) 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 *QueryContractsByCodeRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractsByCodeRequest) 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 m.CodeId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.CodeId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryContractsByCodeResponse) 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 *QueryContractsByCodeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractsByCodeResponse) 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.Contracts) > 0 { - for iNdEx := len(m.Contracts) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Contracts[iNdEx]) - copy(dAtA[i:], m.Contracts[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Contracts[iNdEx]))) - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryAllContractStateRequest) 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 *QueryAllContractStateRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllContractStateRequest) 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.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryAllContractStateResponse) 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 *QueryAllContractStateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllContractStateResponse) 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.Models) > 0 { - for iNdEx := len(m.Models) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Models[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryRawContractStateRequest) 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 *QueryRawContractStateRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRawContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.QueryData) > 0 { - i -= len(m.QueryData) - copy(dAtA[i:], m.QueryData) - i = encodeVarintQuery(dAtA, i, uint64(len(m.QueryData))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryRawContractStateResponse) 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 *QueryRawContractStateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryRawContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QuerySmartContractStateRequest) 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 *QuerySmartContractStateRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySmartContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.QueryData) > 0 { - i -= len(m.QueryData) - copy(dAtA[i:], m.QueryData) - i = encodeVarintQuery(dAtA, i, uint64(len(m.QueryData))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QuerySmartContractStateResponse) 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 *QuerySmartContractStateResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QuerySmartContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCodeRequest) 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 *QueryCodeRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCodeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.CodeId != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.CodeId)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *CodeInfoResponse) 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 *CodeInfoResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CodeInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - if len(m.DataHash) > 0 { - i -= len(m.DataHash) - copy(dAtA[i:], m.DataHash) - i = encodeVarintQuery(dAtA, i, uint64(len(m.DataHash))) - i-- - dAtA[i] = 0x1a - } - 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] = 0x12 - } - if m.CodeID != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryCodeResponse) 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 *QueryCodeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintQuery(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x12 - } - if m.CodeInfoResponse != nil { - { - size, err := m.CodeInfoResponse.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 *QueryCodesRequest) 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 *QueryCodesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCodesRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Pagination != nil { - { - size, err := m.Pagination.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryCodesResponse) 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 *QueryCodesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryCodesResponse) 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.CodeInfos) > 0 { - for iNdEx := len(m.CodeInfos) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.CodeInfos[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func (m *QueryPinnedCodesRequest) 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 *QueryPinnedCodesRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPinnedCodesRequest) 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 - } - return len(dAtA) - i, nil -} - -func (m *QueryPinnedCodesResponse) 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 *QueryPinnedCodesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryPinnedCodesResponse) 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.CodeIDs) > 0 { - dAtA15 := make([]byte, len(m.CodeIDs)*10) - var j14 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA15[j14] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j14++ - } - dAtA15[j14] = uint8(num) - j14++ - } - i -= j14 - copy(dAtA[i:], dAtA15[:j14]) - i = encodeVarintQuery(dAtA, i, uint64(j14)) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -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 *QueryContractsByCreatorRequest) 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 *QueryContractsByCreatorRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractsByCreatorRequest) 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.CreatorAddress) > 0 { - i -= len(m.CreatorAddress) - copy(dAtA[i:], m.CreatorAddress) - i = encodeVarintQuery(dAtA, i, uint64(len(m.CreatorAddress))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *QueryContractsByCreatorResponse) 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 *QueryContractsByCreatorResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryContractsByCreatorResponse) 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.ContractAddresses) > 0 { - for iNdEx := len(m.ContractAddresses) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.ContractAddresses[iNdEx]) - copy(dAtA[i:], m.ContractAddresses[iNdEx]) - i = encodeVarintQuery(dAtA, i, uint64(len(m.ContractAddresses[iNdEx]))) - 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 *QueryContractInfoRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryContractInfoResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.ContractInfo.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryContractHistoryRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - 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 *QueryContractHistoryResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Entries) > 0 { - for _, e := range m.Entries { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryContractsByCodeRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeId != 0 { - n += 1 + sovQuery(uint64(m.CodeId)) - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryContractsByCodeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Contracts) > 0 { - for _, s := range m.Contracts { - l = len(s) - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryAllContractStateRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - 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 *QueryAllContractStateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Models) > 0 { - for _, e := range m.Models { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryRawContractStateRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.QueryData) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryRawContractStateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySmartContractStateRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.QueryData) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QuerySmartContractStateResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCodeRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeId != 0 { - n += 1 + sovQuery(uint64(m.CodeId)) - } - return n -} - -func (m *CodeInfoResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovQuery(uint64(m.CodeID)) - } - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.DataHash) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - l = m.InstantiatePermission.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryCodeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeInfoResponse != nil { - l = m.CodeInfoResponse.Size() - n += 1 + l + sovQuery(uint64(l)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCodesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryCodesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CodeInfos) > 0 { - for _, e := range m.CodeInfos { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPinnedCodesRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func (m *QueryPinnedCodesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovQuery(uint64(e)) - } - n += 1 + sovQuery(uint64(l)) + l - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -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 *QueryContractsByCreatorRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CreatorAddress) - 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 *QueryContractsByCreatorResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.ContractAddresses) > 0 { - for _, s := range m.ContractAddresses { - l = len(s) - 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 *QueryContractInfoRequest) 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: QueryContractInfoRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractInfoRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - 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 *QueryContractInfoResponse) 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: QueryContractInfoResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractInfo", 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.ContractInfo.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 *QueryContractHistoryRequest) 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: QueryContractHistoryRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractHistoryRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 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 *QueryContractHistoryResponse) 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: QueryContractHistoryResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractHistoryResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Entries", 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.Entries = append(m.Entries, ContractCodeHistoryEntry{}) - if err := m.Entries[len(m.Entries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryContractsByCodeRequest) 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: QueryContractsByCodeRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractsByCodeRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeId", wireType) - } - m.CodeId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - 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 *QueryContractsByCodeResponse) 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: QueryContractsByCodeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractsByCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contracts", 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.Contracts = append(m.Contracts, 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.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryAllContractStateRequest) 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: QueryAllContractStateRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 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 *QueryAllContractStateResponse) 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: QueryAllContractStateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Models", 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.Models = append(m.Models, Model{}) - if err := m.Models[len(m.Models)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryRawContractStateRequest) 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: QueryRawContractStateRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRawContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field QueryData", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.QueryData = append(m.QueryData[:0], dAtA[iNdEx:postIndex]...) - if m.QueryData == nil { - m.QueryData = []byte{} - } - 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 *QueryRawContractStateResponse) 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: QueryRawContractStateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryRawContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - 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 *QuerySmartContractStateRequest) 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: QuerySmartContractStateRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySmartContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field QueryData", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.QueryData = append(m.QueryData[:0], dAtA[iNdEx:postIndex]...) - if m.QueryData == nil { - m.QueryData = []byte{} - } - 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 *QuerySmartContractStateResponse) 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: QuerySmartContractStateResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QuerySmartContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - 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 *QueryCodeRequest) 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: QueryCodeRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCodeRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeId", wireType) - } - m.CodeId = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeId |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *CodeInfoResponse) 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: CodeInfoResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CodeInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - 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 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DataHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DataHash = append(m.DataHash[:0], dAtA[iNdEx:postIndex]...) - if m.DataHash == nil { - m.DataHash = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", 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.InstantiatePermission.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 *QueryCodeResponse) 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: QueryCodeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeInfoResponse", 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.CodeInfoResponse == nil { - m.CodeInfoResponse = &CodeInfoResponse{} - } - if err := m.CodeInfoResponse.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - 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 *QueryCodesRequest) 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: QueryCodesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCodesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageRequest{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryCodesResponse) 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: QueryCodesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeInfos", 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.CodeInfos = append(m.CodeInfos, CodeInfoResponse{}) - if err := m.CodeInfos[len(m.CodeInfos)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryPinnedCodesRequest) 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: QueryPinnedCodesRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPinnedCodesRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - 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 *QueryPinnedCodesResponse) 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: QueryPinnedCodesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryPinnedCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *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 *QueryContractsByCreatorRequest) 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: QueryContractsByCreatorRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractsByCreatorRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CreatorAddress", 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.CreatorAddress = 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 *QueryContractsByCreatorResponse) 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: QueryContractsByCreatorResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryContractsByCreatorResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ContractAddresses", 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.ContractAddresses = append(m.ContractAddresses, 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.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/wasm/types/query.pb.gw.go b/x/wasm/types/query.pb.gw.go deleted file mode 100644 index 32f3fd2..0000000 --- a/x/wasm/types/query.pb.gw.go +++ /dev/null @@ -1,1187 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: cosmwasm/wasm/v1/query.proto - -/* -Package types is a reverse proxy. - -It translates gRPC into RESTful JSON APIs. -*/ -package types - -import ( - "context" - "io" - "net/http" - - "github.com/golang/protobuf/descriptor" - "github.com/golang/protobuf/proto" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/grpc-ecosystem/grpc-gateway/utilities" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// Suppress "imported and not used" errors -var ( - _ codes.Code - _ io.Reader - _ status.Status - _ = runtime.String - _ = utilities.NewDoubleArray - _ = descriptor.ForMessage - _ = metadata.Join -) - -func request_Query_ContractInfo_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractInfoRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - msg, err := client.ContractInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_ContractInfo_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractInfoRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - msg, err := server.ContractInfo(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_ContractHistory_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} - -func request_Query_ContractHistory_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractHistoryRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", 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_ContractHistory_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.ContractHistory(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_ContractHistory_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractHistoryRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", 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_ContractHistory_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.ContractHistory(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_ContractsByCode_0 = &utilities.DoubleArray{Encoding: map[string]int{"code_id": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} - -func request_Query_ContractsByCode_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractsByCodeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["code_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") - } - - protoReq.CodeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ContractsByCode_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.ContractsByCode(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_ContractsByCode_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractsByCodeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["code_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") - } - - protoReq.CodeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) - } - - if err := req.ParseForm(); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ContractsByCode_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.ContractsByCode(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_AllContractState_0 = &utilities.DoubleArray{Encoding: map[string]int{"address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} - -func request_Query_AllContractState_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", 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_AllContractState_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.AllContractState(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_AllContractState_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", 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_AllContractState_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.AllContractState(ctx, &protoReq) - return msg, metadata, err -} - -func request_Query_RawContractState_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRawContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - val, ok = pathParams["query_data"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") - } - - protoReq.QueryData, err = runtime.Bytes(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) - } - - msg, err := client.RawContractState(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_RawContractState_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryRawContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - val, ok = pathParams["query_data"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") - } - - protoReq.QueryData, err = runtime.Bytes(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) - } - - msg, err := server.RawContractState(ctx, &protoReq) - return msg, metadata, err -} - -func request_Query_SmartContractState_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySmartContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - val, ok = pathParams["query_data"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") - } - - protoReq.QueryData, err = runtime.Bytes(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) - } - - msg, err := client.SmartContractState(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_SmartContractState_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QuerySmartContractStateRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") - } - - protoReq.Address, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) - } - - val, ok = pathParams["query_data"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") - } - - protoReq.QueryData, err = runtime.Bytes(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) - } - - msg, err := server.SmartContractState(ctx, &protoReq) - return msg, metadata, err -} - -func request_Query_Code_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCodeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["code_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") - } - - protoReq.CodeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) - } - - msg, err := client.Code(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_Code_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCodeRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["code_id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") - } - - protoReq.CodeId, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) - } - - msg, err := server.Code(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_Codes_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} - -func request_Query_Codes_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCodesRequest - 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_Codes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.Codes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_Codes_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryCodesRequest - 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_Codes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.Codes(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_PinnedCodes_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} - -func request_Query_PinnedCodes_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPinnedCodesRequest - 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_PinnedCodes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.PinnedCodes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_PinnedCodes_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryPinnedCodesRequest - 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_PinnedCodes_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.PinnedCodes(ctx, &protoReq) - return msg, metadata, err -} - -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 -} - -var filter_Query_ContractsByCreator_0 = &utilities.DoubleArray{Encoding: map[string]int{"creator_address": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} - -func request_Query_ContractsByCreator_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractsByCreatorRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["creator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "creator_address") - } - - protoReq.CreatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "creator_address", 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_ContractsByCreator_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.ContractsByCreator(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_ContractsByCreator_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryContractsByCreatorRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["creator_address"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "creator_address") - } - - protoReq.CreatorAddress, err = runtime.String(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "creator_address", 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_ContractsByCreator_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.ContractsByCreator(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_ContractInfo_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_ContractInfo_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_ContractInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractHistory_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_ContractHistory_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_ContractHistory_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractsByCode_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_ContractsByCode_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_ContractsByCode_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_AllContractState_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_AllContractState_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_AllContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_RawContractState_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_RawContractState_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_RawContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_SmartContractState_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_SmartContractState_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_SmartContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Code_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_Code_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_Code_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Codes_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_Codes_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_Codes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_PinnedCodes_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_PinnedCodes_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_PinnedCodes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - 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_ContractsByCreator_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_ContractsByCreator_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_ContractsByCreator_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_ContractInfo_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_ContractInfo_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_ContractInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractHistory_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_ContractHistory_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_ContractHistory_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_ContractsByCode_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_ContractsByCode_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_ContractsByCode_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_AllContractState_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_AllContractState_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_AllContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_RawContractState_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_RawContractState_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_RawContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_SmartContractState_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_SmartContractState_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_SmartContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Code_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_Code_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_Code_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Codes_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_Codes_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_Codes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_PinnedCodes_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_PinnedCodes_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_PinnedCodes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - 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_ContractsByCreator_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_ContractsByCreator_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_ContractsByCreator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - return nil -} - -var ( - pattern_Query_ContractInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmwasm", "wasm", "v1", "contract", "address"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ContractHistory_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmwasm", "wasm", "v1", "contract", "address", "history"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ContractsByCode_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmwasm", "wasm", "v1", "code", "code_id", "contracts"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_AllContractState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"cosmwasm", "wasm", "v1", "contract", "address", "state"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_RawContractState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 1, 0, 4, 1, 5, 6}, []string{"cosmwasm", "wasm", "v1", "contract", "address", "raw", "query_data"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_SmartContractState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5, 1, 0, 4, 1, 5, 6}, []string{"cosmwasm", "wasm", "v1", "contract", "address", "smart", "query_data"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Code_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"cosmwasm", "wasm", "v1", "code", "code_id"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Codes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmwasm", "wasm", "v1", "code"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_PinnedCodes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"cosmwasm", "wasm", "v1", "codes", "pinned"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4}, []string{"cosmwasm", "wasm", "v1", "codes", "params"}, "", runtime.AssumeColonVerbOpt(false))) - - pattern_Query_ContractsByCreator_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"cosmwasm", "wasm", "v1", "contracts", "creator", "creator_address"}, "", runtime.AssumeColonVerbOpt(false))) -) - -var ( - forward_Query_ContractInfo_0 = runtime.ForwardResponseMessage - - forward_Query_ContractHistory_0 = runtime.ForwardResponseMessage - - forward_Query_ContractsByCode_0 = runtime.ForwardResponseMessage - - forward_Query_AllContractState_0 = runtime.ForwardResponseMessage - - forward_Query_RawContractState_0 = runtime.ForwardResponseMessage - - forward_Query_SmartContractState_0 = runtime.ForwardResponseMessage - - forward_Query_Code_0 = runtime.ForwardResponseMessage - - forward_Query_Codes_0 = runtime.ForwardResponseMessage - - forward_Query_PinnedCodes_0 = runtime.ForwardResponseMessage - - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_ContractsByCreator_0 = runtime.ForwardResponseMessage -) diff --git a/x/wasm/types/test_fixtures.go b/x/wasm/types/test_fixtures.go deleted file mode 100644 index e84b61f..0000000 --- a/x/wasm/types/test_fixtures.go +++ /dev/null @@ -1,443 +0,0 @@ -package types - -import ( - "bytes" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "math/rand" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func GenesisFixture(mutators ...func(*GenesisState)) GenesisState { - const ( - numCodes = 2 - numContracts = 2 - numSequences = 2 - numMsg = 3 - ) - - fixture := GenesisState{ - Params: DefaultParams(), - Codes: make([]Code, numCodes), - Contracts: make([]Contract, numContracts), - Sequences: make([]Sequence, numSequences), - } - for i := 0; i < numCodes; i++ { - fixture.Codes[i] = CodeFixture() - } - for i := 0; i < numContracts; i++ { - fixture.Contracts[i] = ContractFixture() - } - for i := 0; i < numSequences; i++ { - fixture.Sequences[i] = Sequence{ - IDKey: randBytes(5), - Value: uint64(i), - } - } - - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func randBytes(n int) []byte { - r := make([]byte, n) - rand.Read(r) - return r -} - -func CodeFixture(mutators ...func(*Code)) Code { - wasmCode := randBytes(100) - - fixture := Code{ - CodeID: 1, - CodeInfo: CodeInfoFixture(WithSHA256CodeHash(wasmCode)), - CodeBytes: wasmCode, - } - - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func CodeInfoFixture(mutators ...func(*CodeInfo)) CodeInfo { - wasmCode := bytes.Repeat([]byte{0x1}, 10) - codeHash := sha256.Sum256(wasmCode) - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - fixture := CodeInfo{ - CodeHash: codeHash[:], - Creator: anyAddress, - InstantiateConfig: AllowEverybody, - } - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func ContractFixture(mutators ...func(*Contract)) Contract { - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - - fixture := Contract{ - ContractAddress: anyAddress, - ContractInfo: ContractInfoFixture(RandCreatedFields), - ContractState: []Model{{Key: []byte("anyKey"), Value: []byte("anyValue")}}, - } - fixture.ContractCodeHistory = []ContractCodeHistoryEntry{ContractCodeHistoryEntryFixture(func(e *ContractCodeHistoryEntry) { - e.Updated = fixture.ContractInfo.Created - })} - - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func OnlyGenesisFields(info *ContractInfo) { - info.Created = nil -} - -func RandCreatedFields(info *ContractInfo) { - info.Created = &AbsoluteTxPosition{BlockHeight: rand.Uint64(), TxIndex: rand.Uint64()} -} - -func ContractInfoFixture(mutators ...func(*ContractInfo)) ContractInfo { - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - - fixture := ContractInfo{ - CodeID: 1, - Creator: anyAddress, - Label: "any", - Created: &AbsoluteTxPosition{BlockHeight: 1, TxIndex: 1}, - } - - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -// ContractCodeHistoryEntryFixture test fixture -func ContractCodeHistoryEntryFixture(mutators ...func(*ContractCodeHistoryEntry)) ContractCodeHistoryEntry { - fixture := ContractCodeHistoryEntry{ - Operation: ContractCodeHistoryOperationTypeInit, - CodeID: 1, - Updated: ContractInfoFixture().Created, - Msg: []byte(`{"foo":"bar"}`), - } - for _, m := range mutators { - m(&fixture) - } - return fixture -} - -func WithSHA256CodeHash(wasmCode []byte) func(info *CodeInfo) { - return func(info *CodeInfo) { - codeHash := sha256.Sum256(wasmCode) - info.CodeHash = codeHash[:] - } -} - -func MsgStoreCodeFixture(mutators ...func(*MsgStoreCode)) *MsgStoreCode { - wasmIdent := []byte("\x00\x61\x73\x6D") - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - r := &MsgStoreCode{ - Sender: anyAddress, - WASMByteCode: wasmIdent, - InstantiatePermission: &AllowEverybody, - } - for _, m := range mutators { - m(r) - } - return r -} - -func MsgInstantiateContractFixture(mutators ...func(*MsgInstantiateContract)) *MsgInstantiateContract { - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - r := &MsgInstantiateContract{ - Sender: anyAddress, - Admin: anyAddress, - CodeID: 1, - Label: "testing", - Msg: []byte(`{"foo":"bar"}`), - Funds: sdk.Coins{{ - Denom: "stake", - Amount: sdk.NewInt(1), - }}, - } - for _, m := range mutators { - m(r) - } - return r -} - -func MsgExecuteContractFixture(mutators ...func(*MsgExecuteContract)) *MsgExecuteContract { - const ( - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - firstContractAddress = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - ) - r := &MsgExecuteContract{ - Sender: anyAddress, - Contract: firstContractAddress, - Msg: []byte(`{"do":"something"}`), - Funds: sdk.Coins{{ - Denom: "stake", - Amount: sdk.NewInt(1), - }}, - } - for _, m := range mutators { - m(r) - } - return r -} - -func StoreCodeProposalFixture(mutators ...func(*StoreCodeProposal)) *StoreCodeProposal { - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - wasm := []byte{0x0} - // got the value from shell sha256sum - codeHash, err := hex.DecodeString("6E340B9CFFB37A989CA544E6BB780A2C78901D3FB33738768511A30617AFA01D") - if err != nil { - panic(err) - } - - p := &StoreCodeProposal{ - Title: "Foo", - Description: "Bar", - RunAs: anyAddress, - WASMByteCode: wasm, - Source: "https://example.com/", - Builder: "cosmwasm/workspace-optimizer:v0.12.8", - CodeHash: codeHash, - } - for _, m := range mutators { - m(p) - } - return p -} - -func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractProposal)) *InstantiateContractProposal { - var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) - - initMsg = struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` - }{ - Verifier: anyValidAddress, - Beneficiary: anyValidAddress, - } - ) - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - - initMsgBz, err := json.Marshal(initMsg) - if err != nil { - panic(err) - } - p := &InstantiateContractProposal{ - Title: "Foo", - Description: "Bar", - RunAs: anyAddress, - Admin: anyAddress, - CodeID: 1, - Label: "testing", - Msg: initMsgBz, - Funds: nil, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func InstantiateContract2ProposalFixture(mutators ...func(p *InstantiateContract2Proposal)) *InstantiateContract2Proposal { - var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) - - initMsg = struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` - }{ - Verifier: anyValidAddress, - Beneficiary: anyValidAddress, - } - ) - const ( - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - mySalt = "myDefaultSalt" - ) - - initMsgBz, err := json.Marshal(initMsg) - if err != nil { - panic(err) - } - p := &InstantiateContract2Proposal{ - Title: "Foo", - Description: "Bar", - RunAs: anyAddress, - Admin: anyAddress, - CodeID: 1, - Label: "testing", - Msg: initMsgBz, - Funds: nil, - Salt: []byte(mySalt), - FixMsg: false, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func StoreAndInstantiateContractProposalFixture(mutators ...func(p *StoreAndInstantiateContractProposal)) *StoreAndInstantiateContractProposal { - var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) - - initMsg = struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` - }{ - Verifier: anyValidAddress, - Beneficiary: anyValidAddress, - } - ) - const anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - wasm := []byte{0x0} - // got the value from shell sha256sum - codeHash, err := hex.DecodeString("6E340B9CFFB37A989CA544E6BB780A2C78901D3FB33738768511A30617AFA01D") - if err != nil { - panic(err) - } - - initMsgBz, err := json.Marshal(initMsg) - if err != nil { - panic(err) - } - p := &StoreAndInstantiateContractProposal{ - Title: "Foo", - Description: "Bar", - RunAs: anyAddress, - WASMByteCode: wasm, - Source: "https://example.com/", - Builder: "cosmwasm/workspace-optimizer:v0.12.9", - CodeHash: codeHash, - Admin: anyAddress, - Label: "testing", - Msg: initMsgBz, - Funds: nil, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func MigrateContractProposalFixture(mutators ...func(p *MigrateContractProposal)) *MigrateContractProposal { - var ( - anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, ContractAddrLen) - - migMsg = struct { - Verifier sdk.AccAddress `json:"verifier"` - }{Verifier: anyValidAddress} - ) - - migMsgBz, err := json.Marshal(migMsg) - if err != nil { - panic(err) - } - const ( - contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - ) - p := &MigrateContractProposal{ - Title: "Foo", - Description: "Bar", - Contract: contractAddr, - CodeID: 1, - Msg: migMsgBz, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func SudoContractProposalFixture(mutators ...func(p *SudoContractProposal)) *SudoContractProposal { - const ( - contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - ) - - p := &SudoContractProposal{ - Title: "Foo", - Description: "Bar", - Contract: contractAddr, - Msg: []byte(`{"do":"something"}`), - } - - for _, m := range mutators { - m(p) - } - return p -} - -func ExecuteContractProposalFixture(mutators ...func(p *ExecuteContractProposal)) *ExecuteContractProposal { - const ( - contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - ) - - p := &ExecuteContractProposal{ - Title: "Foo", - Description: "Bar", - Contract: contractAddr, - RunAs: anyAddress, - Msg: []byte(`{"do":"something"}`), - Funds: sdk.Coins{{ - Denom: "stake", - Amount: sdk.NewInt(1), - }}, - } - - for _, m := range mutators { - m(p) - } - return p -} - -func UpdateAdminProposalFixture(mutators ...func(p *UpdateAdminProposal)) *UpdateAdminProposal { - const ( - contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - anyAddress = "cosmos1qyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqszqgpqyqs2m6sx4" - ) - - p := &UpdateAdminProposal{ - Title: "Foo", - Description: "Bar", - NewAdmin: anyAddress, - Contract: contractAddr, - } - for _, m := range mutators { - m(p) - } - return p -} - -func ClearAdminProposalFixture(mutators ...func(p *ClearAdminProposal)) *ClearAdminProposal { - const contractAddr = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr" - p := &ClearAdminProposal{ - Title: "Foo", - Description: "Bar", - Contract: contractAddr, - } - for _, m := range mutators { - m(p) - } - return p -} diff --git a/x/wasm/types/tx.go b/x/wasm/types/tx.go deleted file mode 100644 index 023cfdb..0000000 --- a/x/wasm/types/tx.go +++ /dev/null @@ -1,637 +0,0 @@ -package types - -import ( - "bytes" - "encoding/json" - "errors" - "strings" - - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// RawContractMessage defines a json message that is sent or returned by a wasm contract. -// This type can hold any type of bytes. Until validateBasic is called there should not be -// any assumptions made that the data is valid syntax or semantic. -type RawContractMessage []byte - -func (r RawContractMessage) MarshalJSON() ([]byte, error) { - return json.RawMessage(r).MarshalJSON() -} - -func (r *RawContractMessage) UnmarshalJSON(b []byte) error { - if r == nil { - return errors.New("unmarshalJSON on nil pointer") - } - *r = append((*r)[0:0], b...) - return nil -} - -func (r *RawContractMessage) ValidateBasic() error { - if r == nil { - return ErrEmpty - } - if !json.Valid(*r) { - return ErrInvalid - } - return nil -} - -// Bytes returns raw bytes type -func (r RawContractMessage) Bytes() []byte { - return r -} - -// Equal content is equal json. Byte equal but this can change in the future. -func (r RawContractMessage) Equal(o RawContractMessage) bool { - return bytes.Equal(r.Bytes(), o.Bytes()) -} - -func (msg MsgStoreCode) Route() string { - return RouterKey -} - -func (msg MsgStoreCode) Type() string { - return "store-code" -} - -func (msg MsgStoreCode) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return err - } - - if err := validateWasmCode(msg.WASMByteCode, MaxWasmSize); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) - } - - if msg.InstantiatePermission != nil { - if err := msg.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - // AccessTypeOnlyAddress is still considered valid as legacy instantiation permission - // but not for new contracts - if msg.InstantiatePermission.Permission == AccessTypeOnlyAddress { - return ErrInvalid.Wrap("unsupported type, use AccessTypeAnyOfAddresses instead") - } - } - return nil -} - -func (msg MsgStoreCode) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgStoreCode) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgInstantiateContract) Route() string { - return RouterKey -} - -func (msg MsgInstantiateContract) Type() string { - return "instantiate" -} - -func (msg MsgInstantiateContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - - if msg.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - - if err := ValidateLabel(msg.Label); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "label is required") - } - - if !msg.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(msg.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -func (msg MsgInstantiateContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgInstantiateContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgExecuteContract) Route() string { - return RouterKey -} - -func (msg MsgExecuteContract) Type() string { - return "execute" -} - -func (msg MsgExecuteContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - - if !msg.Funds.IsValid() { - return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "sentFunds") - } - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -func (msg MsgExecuteContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgExecuteContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -// GetMsg returns the payload message send to the contract -func (msg MsgExecuteContract) GetMsg() RawContractMessage { - return msg.Msg -} - -// GetFunds returns tokens send to the contract -func (msg MsgExecuteContract) GetFunds() sdk.Coins { - return msg.Funds -} - -// GetContract returns the bech32 address of the contract -func (msg MsgExecuteContract) GetContract() string { - return msg.Contract -} - -func (msg MsgMigrateContract) Route() string { - return RouterKey -} - -func (msg MsgMigrateContract) Type() string { - return "migrate" -} - -func (msg MsgMigrateContract) ValidateBasic() error { - if msg.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - - return nil -} - -func (msg MsgMigrateContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgMigrateContract) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -// GetMsg returns the payload message send to the contract -func (msg MsgMigrateContract) GetMsg() RawContractMessage { - return msg.Msg -} - -// GetFunds returns tokens send to the contract -func (msg MsgMigrateContract) GetFunds() sdk.Coins { - return sdk.NewCoins() -} - -// GetContract returns the bech32 address of the contract -func (msg MsgMigrateContract) GetContract() string { - return msg.Contract -} - -func (msg MsgUpdateAdmin) Route() string { - return RouterKey -} - -func (msg MsgUpdateAdmin) Type() string { - return "update-contract-admin" -} - -func (msg MsgUpdateAdmin) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if _, err := sdk.AccAddressFromBech32(msg.NewAdmin); err != nil { - return errorsmod.Wrap(err, "new admin") - } - if strings.EqualFold(msg.Sender, msg.NewAdmin) { - return errorsmod.Wrap(ErrInvalid, "new admin is the same as the old") - } - return nil -} - -func (msg MsgUpdateAdmin) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgUpdateAdmin) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgClearAdmin) Route() string { - return RouterKey -} - -func (msg MsgClearAdmin) Type() string { - return "clear-contract-admin" -} - -func (msg MsgClearAdmin) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - return nil -} - -func (msg MsgClearAdmin) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgClearAdmin) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgIBCSend) Route() string { - return RouterKey -} - -func (msg MsgIBCSend) Type() string { - return "wasm-ibc-send" -} - -func (msg MsgIBCSend) ValidateBasic() error { - return nil -} - -func (msg MsgIBCSend) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgIBCSend) GetSigners() []sdk.AccAddress { - return nil -} - -func (msg MsgIBCCloseChannel) Route() string { - return RouterKey -} - -func (msg MsgIBCCloseChannel) Type() string { - return "wasm-ibc-close" -} - -func (msg MsgIBCCloseChannel) ValidateBasic() error { - return nil -} - -func (msg MsgIBCCloseChannel) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgIBCCloseChannel) GetSigners() []sdk.AccAddress { - return nil -} - -var _ sdk.Msg = &MsgInstantiateContract2{} - -func (msg MsgInstantiateContract2) Route() string { - return RouterKey -} - -func (msg MsgInstantiateContract2) Type() string { - return "instantiate2" -} - -func (msg MsgInstantiateContract2) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - - if msg.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - - if err := ValidateLabel(msg.Label); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "label is required") - } - - if !msg.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(msg.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - if err := ValidateSalt(msg.Salt); err != nil { - return errorsmod.Wrap(err, "salt") - } - return nil -} - -func (msg MsgInstantiateContract2) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgInstantiateContract2) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgUpdateInstantiateConfig) Route() string { - return RouterKey -} - -func (msg MsgUpdateInstantiateConfig) Type() string { - return "update-instantiate-config" -} - -func (msg MsgUpdateInstantiateConfig) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return errorsmod.Wrap(err, "sender") - } - - if msg.CodeID == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") - } - - if msg.NewInstantiatePermission == nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "instantiate permission is required") - } - - if err := msg.NewInstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - // AccessTypeOnlyAddress is still considered valid as legacy instantiation permission - // but not for new contracts - if msg.NewInstantiatePermission.Permission == AccessTypeOnlyAddress { - return ErrInvalid.Wrap("unsupported type, use AccessTypeAnyOfAddresses instead") - } - // AccessTypeOnlyAddress is still considered valid as legacy instantiation permission - // but not for new contracts - if msg.NewInstantiatePermission.Permission == AccessTypeOnlyAddress { - return ErrInvalid.Wrap("unsupported type, use AccessTypeAnyOfAddresses instead") - } - - return nil -} - -func (msg MsgUpdateInstantiateConfig) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgUpdateInstantiateConfig) GetSigners() []sdk.AccAddress { - senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{senderAddr} -} - -func (msg MsgUpdateParams) Route() string { - return RouterKey -} - -func (msg MsgUpdateParams) Type() string { - return "update-params" -} - -func (msg MsgUpdateParams) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgUpdateParams) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgUpdateParams) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - return msg.Params.ValidateBasic() -} - -func (msg MsgPinCodes) Route() string { - return RouterKey -} - -func (msg MsgPinCodes) Type() string { - return "pin-codes" -} - -func (msg MsgPinCodes) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgPinCodes) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgPinCodes) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - if len(msg.CodeIDs) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "empty code ids") - } - return nil -} - -func (msg MsgUnpinCodes) Route() string { - return RouterKey -} - -func (msg MsgUnpinCodes) Type() string { - return "unpin-codes" -} - -func (msg MsgUnpinCodes) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgUnpinCodes) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgUnpinCodes) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - if len(msg.CodeIDs) == 0 { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "empty code ids") - } - return nil -} - -func (msg MsgSudoContract) Route() string { - return RouterKey -} - -func (msg MsgSudoContract) Type() string { - return "sudo-contract" -} - -func (msg MsgSudoContract) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgSudoContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgSudoContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return errorsmod.Wrap(err, "contract") - } - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - return nil -} - -func (msg MsgStoreAndInstantiateContract) Route() string { - return RouterKey -} - -func (msg MsgStoreAndInstantiateContract) Type() string { - return "store-and-instantiate-contract" -} - -func (msg MsgStoreAndInstantiateContract) GetSigners() []sdk.AccAddress { - authority, err := sdk.AccAddressFromBech32(msg.Authority) - if err != nil { // should never happen as valid basic rejects invalid addresses - panic(err.Error()) - } - return []sdk.AccAddress{authority} -} - -func (msg MsgStoreAndInstantiateContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) -} - -func (msg MsgStoreAndInstantiateContract) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(msg.Authority); err != nil { - return errorsmod.Wrap(err, "authority") - } - - if err := ValidateLabel(msg.Label); err != nil { - return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "label is required") - } - - if !msg.Funds.IsValid() { - return sdkerrors.ErrInvalidCoins - } - - if len(msg.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - - if err := ValidateVerificationInfo(msg.Source, msg.Builder, msg.CodeHash); err != nil { - return errorsmod.Wrapf(err, "code verification info") - } - - if err := msg.Msg.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "payload msg") - } - - if err := validateWasmCode(msg.WASMByteCode, MaxWasmSize); err != nil { - return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) - } - - if msg.InstantiatePermission != nil { - if err := msg.InstantiatePermission.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate permission") - } - // AccessTypeOnlyAddress is still considered valid as legacy instantiation permission - // but not for new contracts - if msg.InstantiatePermission.Permission == AccessTypeOnlyAddress { - return ErrInvalid.Wrap("unsupported type, use AccessTypeAnyOfAddresses instead") - } - } - return nil -} diff --git a/x/wasm/types/tx.pb.go b/x/wasm/types/tx.pb.go deleted file mode 100644 index ae7879a..0000000 --- a/x/wasm/types/tx.pb.go +++ /dev/null @@ -1,7139 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/cosmos/cosmos-proto" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" - types "github.com/cosmos/cosmos-sdk/types" - _ "github.com/cosmos/cosmos-sdk/types/msgservice" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "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" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = 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 - -// MsgStoreCode submit Wasm code to the system -type MsgStoreCode struct { - // Sender is the actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `protobuf:"bytes,2,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` - // InstantiatePermission access control to apply on contract creation, - // optional - InstantiatePermission *AccessConfig `protobuf:"bytes,5,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission,omitempty"` -} - -func (m *MsgStoreCode) Reset() { *m = MsgStoreCode{} } -func (m *MsgStoreCode) String() string { return proto.CompactTextString(m) } -func (*MsgStoreCode) ProtoMessage() {} -func (*MsgStoreCode) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{0} -} - -func (m *MsgStoreCode) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgStoreCode) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgStoreCode.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 *MsgStoreCode) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgStoreCode.Merge(m, src) -} - -func (m *MsgStoreCode) XXX_Size() int { - return m.Size() -} - -func (m *MsgStoreCode) XXX_DiscardUnknown() { - xxx_messageInfo_MsgStoreCode.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgStoreCode proto.InternalMessageInfo - -// MsgStoreCodeResponse returns store result data. -type MsgStoreCodeResponse struct { - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Checksum is the sha256 hash of the stored code - Checksum []byte `protobuf:"bytes,2,opt,name=checksum,proto3" json:"checksum,omitempty"` -} - -func (m *MsgStoreCodeResponse) Reset() { *m = MsgStoreCodeResponse{} } -func (m *MsgStoreCodeResponse) String() string { return proto.CompactTextString(m) } -func (*MsgStoreCodeResponse) ProtoMessage() {} -func (*MsgStoreCodeResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{1} -} - -func (m *MsgStoreCodeResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgStoreCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgStoreCodeResponse.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 *MsgStoreCodeResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgStoreCodeResponse.Merge(m, src) -} - -func (m *MsgStoreCodeResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgStoreCodeResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgStoreCodeResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgStoreCodeResponse proto.InternalMessageInfo - -// MsgInstantiateContract create a new smart contract instance for the given -// code id. -type MsgInstantiateContract struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,2,opt,name=admin,proto3" json:"admin,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,3,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Label is optional metadata to be stored with a contract instance. - Label string `protobuf:"bytes,4,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,5,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` -} - -func (m *MsgInstantiateContract) Reset() { *m = MsgInstantiateContract{} } -func (m *MsgInstantiateContract) String() string { return proto.CompactTextString(m) } -func (*MsgInstantiateContract) ProtoMessage() {} -func (*MsgInstantiateContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{2} -} - -func (m *MsgInstantiateContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgInstantiateContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgInstantiateContract.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 *MsgInstantiateContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgInstantiateContract.Merge(m, src) -} - -func (m *MsgInstantiateContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgInstantiateContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgInstantiateContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgInstantiateContract proto.InternalMessageInfo - -// MsgInstantiateContractResponse return instantiation result data -type MsgInstantiateContractResponse struct { - // Address is the bech32 address of the new contract instance. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgInstantiateContractResponse) Reset() { *m = MsgInstantiateContractResponse{} } -func (m *MsgInstantiateContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgInstantiateContractResponse) ProtoMessage() {} -func (*MsgInstantiateContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{3} -} - -func (m *MsgInstantiateContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgInstantiateContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgInstantiateContractResponse.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 *MsgInstantiateContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgInstantiateContractResponse.Merge(m, src) -} - -func (m *MsgInstantiateContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgInstantiateContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgInstantiateContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgInstantiateContractResponse proto.InternalMessageInfo - -// MsgInstantiateContract2 create a new smart contract instance for the given -// code id with a predicable address. -type MsgInstantiateContract2 struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,2,opt,name=admin,proto3" json:"admin,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,3,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Label is optional metadata to be stored with a contract instance. - Label string `protobuf:"bytes,4,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,5,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` - // Salt is an arbitrary value provided by the sender. Size can be 1 to 64. - Salt []byte `protobuf:"bytes,7,opt,name=salt,proto3" json:"salt,omitempty"` - // FixMsg include the msg value into the hash for the predictable address. - // Default is false - FixMsg bool `protobuf:"varint,8,opt,name=fix_msg,json=fixMsg,proto3" json:"fix_msg,omitempty"` -} - -func (m *MsgInstantiateContract2) Reset() { *m = MsgInstantiateContract2{} } -func (m *MsgInstantiateContract2) String() string { return proto.CompactTextString(m) } -func (*MsgInstantiateContract2) ProtoMessage() {} -func (*MsgInstantiateContract2) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{4} -} - -func (m *MsgInstantiateContract2) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgInstantiateContract2) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgInstantiateContract2.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 *MsgInstantiateContract2) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgInstantiateContract2.Merge(m, src) -} - -func (m *MsgInstantiateContract2) XXX_Size() int { - return m.Size() -} - -func (m *MsgInstantiateContract2) XXX_DiscardUnknown() { - xxx_messageInfo_MsgInstantiateContract2.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgInstantiateContract2 proto.InternalMessageInfo - -// MsgInstantiateContract2Response return instantiation result data -type MsgInstantiateContract2Response struct { - // Address is the bech32 address of the new contract instance. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgInstantiateContract2Response) Reset() { *m = MsgInstantiateContract2Response{} } -func (m *MsgInstantiateContract2Response) String() string { return proto.CompactTextString(m) } -func (*MsgInstantiateContract2Response) ProtoMessage() {} -func (*MsgInstantiateContract2Response) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{5} -} - -func (m *MsgInstantiateContract2Response) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgInstantiateContract2Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgInstantiateContract2Response.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 *MsgInstantiateContract2Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgInstantiateContract2Response.Merge(m, src) -} - -func (m *MsgInstantiateContract2Response) XXX_Size() int { - return m.Size() -} - -func (m *MsgInstantiateContract2Response) XXX_DiscardUnknown() { - xxx_messageInfo_MsgInstantiateContract2Response.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgInstantiateContract2Response proto.InternalMessageInfo - -// MsgExecuteContract submits the given message data to a smart contract -type MsgExecuteContract struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,2,opt,name=contract,proto3" json:"contract,omitempty"` - // Msg json encoded message to be passed to the contract - Msg RawContractMessage `protobuf:"bytes,3,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred to the contract on execution - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` -} - -func (m *MsgExecuteContract) Reset() { *m = MsgExecuteContract{} } -func (m *MsgExecuteContract) String() string { return proto.CompactTextString(m) } -func (*MsgExecuteContract) ProtoMessage() {} -func (*MsgExecuteContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{6} -} - -func (m *MsgExecuteContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgExecuteContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgExecuteContract.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 *MsgExecuteContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgExecuteContract.Merge(m, src) -} - -func (m *MsgExecuteContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgExecuteContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgExecuteContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgExecuteContract proto.InternalMessageInfo - -// MsgExecuteContractResponse returns execution result data. -type MsgExecuteContractResponse struct { - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgExecuteContractResponse) Reset() { *m = MsgExecuteContractResponse{} } -func (m *MsgExecuteContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgExecuteContractResponse) ProtoMessage() {} -func (*MsgExecuteContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{7} -} - -func (m *MsgExecuteContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgExecuteContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgExecuteContractResponse.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 *MsgExecuteContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgExecuteContractResponse.Merge(m, src) -} - -func (m *MsgExecuteContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgExecuteContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgExecuteContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgExecuteContractResponse proto.InternalMessageInfo - -// MsgMigrateContract runs a code upgrade/ downgrade for a smart contract -type MsgMigrateContract struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,2,opt,name=contract,proto3" json:"contract,omitempty"` - // CodeID references the new WASM code - CodeID uint64 `protobuf:"varint,3,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Msg json encoded message to be passed to the contract on migration - Msg RawContractMessage `protobuf:"bytes,4,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *MsgMigrateContract) Reset() { *m = MsgMigrateContract{} } -func (m *MsgMigrateContract) String() string { return proto.CompactTextString(m) } -func (*MsgMigrateContract) ProtoMessage() {} -func (*MsgMigrateContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{8} -} - -func (m *MsgMigrateContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgMigrateContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMigrateContract.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 *MsgMigrateContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMigrateContract.Merge(m, src) -} - -func (m *MsgMigrateContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgMigrateContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMigrateContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMigrateContract proto.InternalMessageInfo - -// MsgMigrateContractResponse returns contract migration result data. -type MsgMigrateContractResponse struct { - // Data contains same raw bytes returned as data from the wasm contract. - // (May be empty) - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgMigrateContractResponse) Reset() { *m = MsgMigrateContractResponse{} } -func (m *MsgMigrateContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgMigrateContractResponse) ProtoMessage() {} -func (*MsgMigrateContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{9} -} - -func (m *MsgMigrateContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgMigrateContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgMigrateContractResponse.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 *MsgMigrateContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgMigrateContractResponse.Merge(m, src) -} - -func (m *MsgMigrateContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgMigrateContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgMigrateContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgMigrateContractResponse proto.InternalMessageInfo - -// MsgUpdateAdmin sets a new admin for a smart contract -type MsgUpdateAdmin struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // NewAdmin address to be set - NewAdmin string `protobuf:"bytes,2,opt,name=new_admin,json=newAdmin,proto3" json:"new_admin,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,3,opt,name=contract,proto3" json:"contract,omitempty"` -} - -func (m *MsgUpdateAdmin) Reset() { *m = MsgUpdateAdmin{} } -func (m *MsgUpdateAdmin) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateAdmin) ProtoMessage() {} -func (*MsgUpdateAdmin) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{10} -} - -func (m *MsgUpdateAdmin) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateAdmin.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 *MsgUpdateAdmin) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateAdmin.Merge(m, src) -} - -func (m *MsgUpdateAdmin) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateAdmin) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateAdmin.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateAdmin proto.InternalMessageInfo - -// MsgUpdateAdminResponse returns empty data -type MsgUpdateAdminResponse struct{} - -func (m *MsgUpdateAdminResponse) Reset() { *m = MsgUpdateAdminResponse{} } -func (m *MsgUpdateAdminResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateAdminResponse) ProtoMessage() {} -func (*MsgUpdateAdminResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{11} -} - -func (m *MsgUpdateAdminResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateAdminResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateAdminResponse.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 *MsgUpdateAdminResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateAdminResponse.Merge(m, src) -} - -func (m *MsgUpdateAdminResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateAdminResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateAdminResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateAdminResponse proto.InternalMessageInfo - -// MsgClearAdmin removes any admin stored for a smart contract -type MsgClearAdmin struct { - // Sender is the actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,3,opt,name=contract,proto3" json:"contract,omitempty"` -} - -func (m *MsgClearAdmin) Reset() { *m = MsgClearAdmin{} } -func (m *MsgClearAdmin) String() string { return proto.CompactTextString(m) } -func (*MsgClearAdmin) ProtoMessage() {} -func (*MsgClearAdmin) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{12} -} - -func (m *MsgClearAdmin) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgClearAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClearAdmin.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 *MsgClearAdmin) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClearAdmin.Merge(m, src) -} - -func (m *MsgClearAdmin) XXX_Size() int { - return m.Size() -} - -func (m *MsgClearAdmin) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClearAdmin.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClearAdmin proto.InternalMessageInfo - -// MsgClearAdminResponse returns empty data -type MsgClearAdminResponse struct{} - -func (m *MsgClearAdminResponse) Reset() { *m = MsgClearAdminResponse{} } -func (m *MsgClearAdminResponse) String() string { return proto.CompactTextString(m) } -func (*MsgClearAdminResponse) ProtoMessage() {} -func (*MsgClearAdminResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{13} -} - -func (m *MsgClearAdminResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgClearAdminResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgClearAdminResponse.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 *MsgClearAdminResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgClearAdminResponse.Merge(m, src) -} - -func (m *MsgClearAdminResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgClearAdminResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgClearAdminResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgClearAdminResponse proto.InternalMessageInfo - -// MsgUpdateInstantiateConfig updates instantiate config for a smart contract -type MsgUpdateInstantiateConfig struct { - // Sender is the that actor that signed the messages - Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` - // CodeID references the stored WASM code - CodeID uint64 `protobuf:"varint,2,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // NewInstantiatePermission is the new access control - NewInstantiatePermission *AccessConfig `protobuf:"bytes,3,opt,name=new_instantiate_permission,json=newInstantiatePermission,proto3" json:"new_instantiate_permission,omitempty"` -} - -func (m *MsgUpdateInstantiateConfig) Reset() { *m = MsgUpdateInstantiateConfig{} } -func (m *MsgUpdateInstantiateConfig) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateInstantiateConfig) ProtoMessage() {} -func (*MsgUpdateInstantiateConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{14} -} - -func (m *MsgUpdateInstantiateConfig) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateInstantiateConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateInstantiateConfig.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 *MsgUpdateInstantiateConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateInstantiateConfig.Merge(m, src) -} - -func (m *MsgUpdateInstantiateConfig) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateInstantiateConfig) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateInstantiateConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateInstantiateConfig proto.InternalMessageInfo - -// MsgUpdateInstantiateConfigResponse returns empty data -type MsgUpdateInstantiateConfigResponse struct{} - -func (m *MsgUpdateInstantiateConfigResponse) Reset() { *m = MsgUpdateInstantiateConfigResponse{} } -func (m *MsgUpdateInstantiateConfigResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateInstantiateConfigResponse) ProtoMessage() {} -func (*MsgUpdateInstantiateConfigResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{15} -} - -func (m *MsgUpdateInstantiateConfigResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateInstantiateConfigResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateInstantiateConfigResponse.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 *MsgUpdateInstantiateConfigResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateInstantiateConfigResponse.Merge(m, src) -} - -func (m *MsgUpdateInstantiateConfigResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateInstantiateConfigResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateInstantiateConfigResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateInstantiateConfigResponse proto.InternalMessageInfo - -// MsgUpdateParams is the MsgUpdateParams request type. -// -// Since: 0.40 -type MsgUpdateParams struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // params defines the x/wasm parameters to update. - // - // NOTE: All parameters must be supplied. - Params Params `protobuf:"bytes,2,opt,name=params,proto3" json:"params"` -} - -func (m *MsgUpdateParams) Reset() { *m = MsgUpdateParams{} } -func (m *MsgUpdateParams) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParams) ProtoMessage() {} -func (*MsgUpdateParams) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{16} -} - -func (m *MsgUpdateParams) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateParams) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParams.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 *MsgUpdateParams) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParams.Merge(m, src) -} - -func (m *MsgUpdateParams) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateParams) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParams proto.InternalMessageInfo - -// MsgUpdateParamsResponse defines the response structure for executing a -// MsgUpdateParams message. -// -// Since: 0.40 -type MsgUpdateParamsResponse struct{} - -func (m *MsgUpdateParamsResponse) Reset() { *m = MsgUpdateParamsResponse{} } -func (m *MsgUpdateParamsResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateParamsResponse) ProtoMessage() {} -func (*MsgUpdateParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{17} -} - -func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateParamsResponse.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 *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) -} - -func (m *MsgUpdateParamsResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateParamsResponse proto.InternalMessageInfo - -// MsgSudoContract is the MsgSudoContract request type. -// -// Since: 0.40 -type MsgSudoContract struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // Contract is the address of the smart contract - Contract string `protobuf:"bytes,2,opt,name=contract,proto3" json:"contract,omitempty"` - // Msg json encoded message to be passed to the contract as sudo - Msg RawContractMessage `protobuf:"bytes,3,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *MsgSudoContract) Reset() { *m = MsgSudoContract{} } -func (m *MsgSudoContract) String() string { return proto.CompactTextString(m) } -func (*MsgSudoContract) ProtoMessage() {} -func (*MsgSudoContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{18} -} - -func (m *MsgSudoContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgSudoContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSudoContract.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 *MsgSudoContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSudoContract.Merge(m, src) -} - -func (m *MsgSudoContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgSudoContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSudoContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSudoContract proto.InternalMessageInfo - -// MsgSudoContractResponse defines the response structure for executing a -// MsgSudoContract message. -// -// Since: 0.40 -type MsgSudoContractResponse struct { - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgSudoContractResponse) Reset() { *m = MsgSudoContractResponse{} } -func (m *MsgSudoContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgSudoContractResponse) ProtoMessage() {} -func (*MsgSudoContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{19} -} - -func (m *MsgSudoContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgSudoContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgSudoContractResponse.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 *MsgSudoContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgSudoContractResponse.Merge(m, src) -} - -func (m *MsgSudoContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgSudoContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgSudoContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgSudoContractResponse proto.InternalMessageInfo - -// MsgPinCodes is the MsgPinCodes request type. -// -// Since: 0.40 -type MsgPinCodes struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // CodeIDs references the new WASM codes - CodeIDs []uint64 `protobuf:"varint,2,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty" yaml:"code_ids"` -} - -func (m *MsgPinCodes) Reset() { *m = MsgPinCodes{} } -func (m *MsgPinCodes) String() string { return proto.CompactTextString(m) } -func (*MsgPinCodes) ProtoMessage() {} -func (*MsgPinCodes) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{20} -} - -func (m *MsgPinCodes) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgPinCodes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPinCodes.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 *MsgPinCodes) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPinCodes.Merge(m, src) -} - -func (m *MsgPinCodes) XXX_Size() int { - return m.Size() -} - -func (m *MsgPinCodes) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPinCodes.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPinCodes proto.InternalMessageInfo - -// MsgPinCodesResponse defines the response structure for executing a -// MsgPinCodes message. -// -// Since: 0.40 -type MsgPinCodesResponse struct{} - -func (m *MsgPinCodesResponse) Reset() { *m = MsgPinCodesResponse{} } -func (m *MsgPinCodesResponse) String() string { return proto.CompactTextString(m) } -func (*MsgPinCodesResponse) ProtoMessage() {} -func (*MsgPinCodesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{21} -} - -func (m *MsgPinCodesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgPinCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgPinCodesResponse.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 *MsgPinCodesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgPinCodesResponse.Merge(m, src) -} - -func (m *MsgPinCodesResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgPinCodesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgPinCodesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgPinCodesResponse proto.InternalMessageInfo - -// MsgUnpinCodes is the MsgUnpinCodes request type. -// -// Since: 0.40 -type MsgUnpinCodes struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // CodeIDs references the WASM codes - CodeIDs []uint64 `protobuf:"varint,2,rep,packed,name=code_ids,json=codeIds,proto3" json:"code_ids,omitempty" yaml:"code_ids"` -} - -func (m *MsgUnpinCodes) Reset() { *m = MsgUnpinCodes{} } -func (m *MsgUnpinCodes) String() string { return proto.CompactTextString(m) } -func (*MsgUnpinCodes) ProtoMessage() {} -func (*MsgUnpinCodes) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{22} -} - -func (m *MsgUnpinCodes) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUnpinCodes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUnpinCodes.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 *MsgUnpinCodes) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUnpinCodes.Merge(m, src) -} - -func (m *MsgUnpinCodes) XXX_Size() int { - return m.Size() -} - -func (m *MsgUnpinCodes) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUnpinCodes.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUnpinCodes proto.InternalMessageInfo - -// MsgUnpinCodesResponse defines the response structure for executing a -// MsgUnpinCodes message. -// -// Since: 0.40 -type MsgUnpinCodesResponse struct{} - -func (m *MsgUnpinCodesResponse) Reset() { *m = MsgUnpinCodesResponse{} } -func (m *MsgUnpinCodesResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUnpinCodesResponse) ProtoMessage() {} -func (*MsgUnpinCodesResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{23} -} - -func (m *MsgUnpinCodesResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUnpinCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUnpinCodesResponse.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 *MsgUnpinCodesResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUnpinCodesResponse.Merge(m, src) -} - -func (m *MsgUnpinCodesResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUnpinCodesResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUnpinCodesResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUnpinCodesResponse proto.InternalMessageInfo - -// MsgStoreAndInstantiateContract is the MsgStoreAndInstantiateContract -// request type. -// -// Since: 0.40 -type MsgStoreAndInstantiateContract struct { - // Authority is the address of the governance account. - Authority string `protobuf:"bytes,1,opt,name=authority,proto3" json:"authority,omitempty"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `protobuf:"bytes,3,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` - // InstantiatePermission to apply on contract creation, optional - InstantiatePermission *AccessConfig `protobuf:"bytes,4,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission,omitempty"` - // UnpinCode code on upload, optional. As default the uploaded contract is - // pinned to cache. - UnpinCode bool `protobuf:"varint,5,opt,name=unpin_code,json=unpinCode,proto3" json:"unpin_code,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,6,opt,name=admin,proto3" json:"admin,omitempty"` - // Label is optional metadata to be stored with a constract instance. - Label string `protobuf:"bytes,7,opt,name=label,proto3" json:"label,omitempty"` - // Msg json encoded message to be passed to the contract on instantiation - Msg RawContractMessage `protobuf:"bytes,8,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` - // Funds coins that are transferred from the authority account to the contract - // on instantiation - Funds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,9,rep,name=funds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"funds"` - // Source is the URL where the code is hosted - Source string `protobuf:"bytes,10,opt,name=source,proto3" json:"source,omitempty"` - // Builder is the docker image used to build the code deterministically, used - // for smart contract verification - Builder string `protobuf:"bytes,11,opt,name=builder,proto3" json:"builder,omitempty"` - // CodeHash is the SHA256 sum of the code outputted by builder, used for smart - // contract verification - CodeHash []byte `protobuf:"bytes,12,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` -} - -func (m *MsgStoreAndInstantiateContract) Reset() { *m = MsgStoreAndInstantiateContract{} } -func (m *MsgStoreAndInstantiateContract) String() string { return proto.CompactTextString(m) } -func (*MsgStoreAndInstantiateContract) ProtoMessage() {} -func (*MsgStoreAndInstantiateContract) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{24} -} - -func (m *MsgStoreAndInstantiateContract) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgStoreAndInstantiateContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgStoreAndInstantiateContract.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 *MsgStoreAndInstantiateContract) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgStoreAndInstantiateContract.Merge(m, src) -} - -func (m *MsgStoreAndInstantiateContract) XXX_Size() int { - return m.Size() -} - -func (m *MsgStoreAndInstantiateContract) XXX_DiscardUnknown() { - xxx_messageInfo_MsgStoreAndInstantiateContract.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgStoreAndInstantiateContract proto.InternalMessageInfo - -// MsgStoreAndInstantiateContractResponse defines the response structure -// for executing a MsgStoreAndInstantiateContract message. -// -// Since: 0.40 -type MsgStoreAndInstantiateContractResponse struct { - // Address is the bech32 address of the new contract instance. - Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` - // Data contains bytes to returned from the contract - Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data,omitempty"` -} - -func (m *MsgStoreAndInstantiateContractResponse) Reset() { - *m = MsgStoreAndInstantiateContractResponse{} -} -func (m *MsgStoreAndInstantiateContractResponse) String() string { return proto.CompactTextString(m) } -func (*MsgStoreAndInstantiateContractResponse) ProtoMessage() {} -func (*MsgStoreAndInstantiateContractResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_4f74d82755520264, []int{25} -} - -func (m *MsgStoreAndInstantiateContractResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgStoreAndInstantiateContractResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgStoreAndInstantiateContractResponse.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 *MsgStoreAndInstantiateContractResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgStoreAndInstantiateContractResponse.Merge(m, src) -} - -func (m *MsgStoreAndInstantiateContractResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgStoreAndInstantiateContractResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgStoreAndInstantiateContractResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgStoreAndInstantiateContractResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgStoreCode)(nil), "cosmwasm.wasm.v1.MsgStoreCode") - proto.RegisterType((*MsgStoreCodeResponse)(nil), "cosmwasm.wasm.v1.MsgStoreCodeResponse") - proto.RegisterType((*MsgInstantiateContract)(nil), "cosmwasm.wasm.v1.MsgInstantiateContract") - proto.RegisterType((*MsgInstantiateContractResponse)(nil), "cosmwasm.wasm.v1.MsgInstantiateContractResponse") - proto.RegisterType((*MsgInstantiateContract2)(nil), "cosmwasm.wasm.v1.MsgInstantiateContract2") - proto.RegisterType((*MsgInstantiateContract2Response)(nil), "cosmwasm.wasm.v1.MsgInstantiateContract2Response") - proto.RegisterType((*MsgExecuteContract)(nil), "cosmwasm.wasm.v1.MsgExecuteContract") - proto.RegisterType((*MsgExecuteContractResponse)(nil), "cosmwasm.wasm.v1.MsgExecuteContractResponse") - proto.RegisterType((*MsgMigrateContract)(nil), "cosmwasm.wasm.v1.MsgMigrateContract") - proto.RegisterType((*MsgMigrateContractResponse)(nil), "cosmwasm.wasm.v1.MsgMigrateContractResponse") - proto.RegisterType((*MsgUpdateAdmin)(nil), "cosmwasm.wasm.v1.MsgUpdateAdmin") - proto.RegisterType((*MsgUpdateAdminResponse)(nil), "cosmwasm.wasm.v1.MsgUpdateAdminResponse") - proto.RegisterType((*MsgClearAdmin)(nil), "cosmwasm.wasm.v1.MsgClearAdmin") - proto.RegisterType((*MsgClearAdminResponse)(nil), "cosmwasm.wasm.v1.MsgClearAdminResponse") - proto.RegisterType((*MsgUpdateInstantiateConfig)(nil), "cosmwasm.wasm.v1.MsgUpdateInstantiateConfig") - proto.RegisterType((*MsgUpdateInstantiateConfigResponse)(nil), "cosmwasm.wasm.v1.MsgUpdateInstantiateConfigResponse") - proto.RegisterType((*MsgUpdateParams)(nil), "cosmwasm.wasm.v1.MsgUpdateParams") - proto.RegisterType((*MsgUpdateParamsResponse)(nil), "cosmwasm.wasm.v1.MsgUpdateParamsResponse") - proto.RegisterType((*MsgSudoContract)(nil), "cosmwasm.wasm.v1.MsgSudoContract") - proto.RegisterType((*MsgSudoContractResponse)(nil), "cosmwasm.wasm.v1.MsgSudoContractResponse") - proto.RegisterType((*MsgPinCodes)(nil), "cosmwasm.wasm.v1.MsgPinCodes") - proto.RegisterType((*MsgPinCodesResponse)(nil), "cosmwasm.wasm.v1.MsgPinCodesResponse") - proto.RegisterType((*MsgUnpinCodes)(nil), "cosmwasm.wasm.v1.MsgUnpinCodes") - proto.RegisterType((*MsgUnpinCodesResponse)(nil), "cosmwasm.wasm.v1.MsgUnpinCodesResponse") - proto.RegisterType((*MsgStoreAndInstantiateContract)(nil), "cosmwasm.wasm.v1.MsgStoreAndInstantiateContract") - proto.RegisterType((*MsgStoreAndInstantiateContractResponse)(nil), "cosmwasm.wasm.v1.MsgStoreAndInstantiateContractResponse") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/tx.proto", fileDescriptor_4f74d82755520264) } - -var fileDescriptor_4f74d82755520264 = []byte{ - // 1447 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x58, 0xcf, 0x6f, 0x1b, 0xc5, - 0x17, 0xcf, 0xc6, 0xbf, 0x5f, 0xfc, 0x6d, 0xd3, 0xad, 0x9b, 0x6c, 0xb6, 0xad, 0x9d, 0x6e, 0x7f, - 0xb9, 0xfd, 0x36, 0x76, 0x63, 0xa0, 0x82, 0x70, 0x8a, 0x03, 0x12, 0x29, 0x32, 0x44, 0x1b, 0xb5, - 0x15, 0xa8, 0x92, 0xb5, 0xf6, 0x4e, 0x36, 0xab, 0xc6, 0xbb, 0x66, 0x67, 0xdd, 0x24, 0x07, 0x2e, - 0x20, 0x21, 0xc1, 0x89, 0x7f, 0x02, 0x09, 0xb8, 0xd0, 0x03, 0x48, 0x1c, 0x7b, 0xac, 0xc4, 0xa5, - 0xe2, 0xc4, 0x29, 0x40, 0x8a, 0x54, 0x6e, 0x48, 0x1c, 0x39, 0xa1, 0x99, 0xd9, 0x5d, 0x8f, 0xd7, - 0xbb, 0x8e, 0x93, 0x50, 0x71, 0xe0, 0xe2, 0xec, 0xcc, 0xfb, 0x31, 0xef, 0xf3, 0x79, 0x6f, 0x66, - 0xde, 0x04, 0xe6, 0xda, 0x36, 0xee, 0x6c, 0x6b, 0xb8, 0x53, 0xa5, 0x3f, 0x0f, 0x17, 0xab, 0xee, - 0x4e, 0xa5, 0xeb, 0xd8, 0xae, 0x2d, 0x4e, 0xfb, 0xa2, 0x0a, 0xfd, 0x79, 0xb8, 0x28, 0x17, 0xc9, - 0x8c, 0x8d, 0xab, 0x2d, 0x0d, 0xa3, 0xea, 0xc3, 0xc5, 0x16, 0x72, 0xb5, 0xc5, 0x6a, 0xdb, 0x36, - 0x2d, 0x66, 0x21, 0xcf, 0x7a, 0xf2, 0x0e, 0x36, 0x88, 0xa7, 0x0e, 0x36, 0x3c, 0x41, 0xc1, 0xb0, - 0x0d, 0x9b, 0x7e, 0x56, 0xc9, 0x97, 0x37, 0x7b, 0x6e, 0x78, 0xed, 0xdd, 0x2e, 0xc2, 0x9e, 0x74, - 0x8e, 0x39, 0x6b, 0x32, 0x33, 0x36, 0xf0, 0x44, 0xa7, 0xb4, 0x8e, 0x69, 0xd9, 0x55, 0xfa, 0xcb, - 0xa6, 0x94, 0xdf, 0x04, 0xc8, 0x37, 0xb0, 0xb1, 0xee, 0xda, 0x0e, 0x5a, 0xb1, 0x75, 0x24, 0xce, - 0x40, 0x1a, 0x23, 0x4b, 0x47, 0x8e, 0x24, 0xcc, 0x0b, 0xe5, 0x9c, 0xea, 0x8d, 0xc4, 0x5b, 0x70, - 0x82, 0xac, 0xd6, 0x6c, 0xed, 0xba, 0xa8, 0xd9, 0xb6, 0x75, 0x24, 0x4d, 0xce, 0x0b, 0xe5, 0x7c, - 0x7d, 0x7a, 0x7f, 0xaf, 0x94, 0xbf, 0xb7, 0xbc, 0xde, 0xa8, 0xef, 0xba, 0xd4, 0x83, 0x9a, 0x27, - 0x7a, 0xfe, 0x48, 0xbc, 0x03, 0x33, 0xa6, 0x85, 0x5d, 0xcd, 0x72, 0x4d, 0xcd, 0x45, 0xcd, 0x2e, - 0x72, 0x3a, 0x26, 0xc6, 0xa6, 0x6d, 0x49, 0xa9, 0x79, 0xa1, 0x3c, 0x55, 0x2b, 0x56, 0xc2, 0x74, - 0x55, 0x96, 0xdb, 0x6d, 0x84, 0xf1, 0x8a, 0x6d, 0x6d, 0x98, 0x86, 0x7a, 0x86, 0xb3, 0x5e, 0x0b, - 0x8c, 0x97, 0x2e, 0x7c, 0xf4, 0xfc, 0xd1, 0x75, 0x2f, 0xb6, 0xcf, 0x9e, 0x3f, 0xba, 0x7e, 0x8a, - 0x52, 0xc1, 0x23, 0xb9, 0x9d, 0xcc, 0x26, 0xa6, 0x93, 0xb7, 0x93, 0xd9, 0xe4, 0x74, 0x4a, 0xb9, - 0x07, 0x05, 0x5e, 0xa6, 0x22, 0xdc, 0xb5, 0x2d, 0x8c, 0xc4, 0x8b, 0x90, 0x21, 0x58, 0x9a, 0xa6, - 0x4e, 0xe1, 0x26, 0xeb, 0xb0, 0xbf, 0x57, 0x4a, 0x13, 0x95, 0xd5, 0x37, 0xd4, 0x34, 0x11, 0xad, - 0xea, 0xa2, 0x0c, 0xd9, 0xf6, 0x26, 0x6a, 0x3f, 0xc0, 0xbd, 0x0e, 0x03, 0xad, 0x06, 0x63, 0xe5, - 0xf1, 0x24, 0xcc, 0x34, 0xb0, 0xb1, 0xda, 0x0f, 0x72, 0xc5, 0xb6, 0x5c, 0x47, 0x6b, 0xbb, 0xb1, - 0x4c, 0x16, 0x20, 0xa5, 0xe9, 0x1d, 0xd3, 0xa2, 0xbe, 0x72, 0x2a, 0x1b, 0xf0, 0x91, 0x24, 0x62, - 0x23, 0x29, 0x40, 0x6a, 0x4b, 0x6b, 0xa1, 0x2d, 0x29, 0xc9, 0x4c, 0xe9, 0x40, 0x2c, 0x43, 0xa2, - 0x83, 0x0d, 0xca, 0x67, 0xbe, 0x3e, 0xf3, 0xd7, 0x5e, 0x49, 0x54, 0xb5, 0x6d, 0x3f, 0x8c, 0x06, - 0xc2, 0x58, 0x33, 0x90, 0x4a, 0x54, 0xc4, 0x0d, 0x48, 0x6d, 0xf4, 0x2c, 0x1d, 0x4b, 0xe9, 0xf9, - 0x44, 0x79, 0xaa, 0x36, 0x57, 0xf1, 0xca, 0x83, 0x14, 0x66, 0xc5, 0x2b, 0xcc, 0xca, 0x8a, 0x6d, - 0x5a, 0xf5, 0x57, 0x9e, 0xec, 0x95, 0x26, 0xbe, 0xfe, 0xb9, 0x54, 0x36, 0x4c, 0x77, 0xb3, 0xd7, - 0xaa, 0xb4, 0xed, 0x8e, 0x57, 0x4b, 0xde, 0x9f, 0x05, 0xac, 0x3f, 0xf0, 0xea, 0x8e, 0x18, 0xe0, - 0x2f, 0x9f, 0x3f, 0xba, 0x2e, 0xa8, 0xcc, 0xfd, 0xd2, 0xff, 0x43, 0xd9, 0x39, 0xeb, 0x67, 0x27, - 0x82, 0x27, 0xe5, 0x1d, 0x28, 0x46, 0x4b, 0x82, 0x2c, 0x49, 0x90, 0xd1, 0x74, 0xdd, 0x41, 0x18, - 0x7b, 0x54, 0xfa, 0x43, 0x51, 0x84, 0xa4, 0xae, 0xb9, 0x9a, 0x97, 0x16, 0xfa, 0xad, 0xfc, 0x31, - 0x09, 0xb3, 0xd1, 0x0e, 0x6b, 0xff, 0xe1, 0x9c, 0x10, 0xaa, 0xb0, 0xb6, 0xe5, 0x4a, 0x19, 0x46, - 0x15, 0xf9, 0x16, 0x67, 0x21, 0xb3, 0x61, 0xee, 0x34, 0x49, 0xa4, 0xd9, 0x79, 0xa1, 0x9c, 0x55, - 0xd3, 0x1b, 0xe6, 0x4e, 0x03, 0x1b, 0x4b, 0x37, 0x42, 0x09, 0x3c, 0x37, 0x22, 0x81, 0x35, 0xe5, - 0x5d, 0x28, 0xc5, 0x88, 0x8e, 0x98, 0xc2, 0x8f, 0x27, 0x41, 0x6c, 0x60, 0xe3, 0xcd, 0x1d, 0xd4, - 0xee, 0x8d, 0xb1, 0xa3, 0xc8, 0x06, 0xf5, 0x74, 0xbc, 0x04, 0x06, 0x63, 0x3f, 0x11, 0x89, 0x43, - 0x24, 0x22, 0xf5, 0x62, 0x37, 0xc7, 0xd5, 0x10, 0xb7, 0xb3, 0x3e, 0xb7, 0x21, 0xb8, 0xca, 0x4d, - 0x90, 0x87, 0x67, 0x03, 0x46, 0x7d, 0xde, 0x04, 0x8e, 0xb7, 0xc7, 0x02, 0xe5, 0xad, 0x61, 0x1a, - 0x8e, 0x76, 0x4c, 0xde, 0xc6, 0xaa, 0x7d, 0x8f, 0xdc, 0xe4, 0x81, 0xe4, 0xc6, 0x83, 0x0e, 0xc5, - 0xea, 0x81, 0x0e, 0xcd, 0x8e, 0x04, 0xfd, 0x89, 0x00, 0x27, 0x1a, 0xd8, 0xb8, 0xd3, 0xd5, 0x35, - 0x17, 0x2d, 0xd3, 0x8d, 0x1b, 0x07, 0xf8, 0x2c, 0xe4, 0x2c, 0xb4, 0xdd, 0xe4, 0xb7, 0x7a, 0xd6, - 0x42, 0xdb, 0xcc, 0x88, 0x67, 0x23, 0x31, 0xc8, 0xc6, 0xd2, 0xc5, 0x50, 0xf8, 0xa7, 0xfd, 0xf0, - 0xb9, 0x55, 0x15, 0x89, 0x5e, 0x05, 0xdc, 0x8c, 0x1f, 0xb6, 0x62, 0xc0, 0xff, 0x1a, 0xd8, 0x58, - 0xd9, 0x42, 0x9a, 0x33, 0x3a, 0xc0, 0x51, 0x31, 0x28, 0xa1, 0x18, 0x44, 0x3f, 0x86, 0xbe, 0x5f, - 0x65, 0x16, 0xce, 0x0c, 0x4c, 0x04, 0x11, 0xfc, 0x2e, 0x50, 0x5e, 0x59, 0x70, 0x83, 0x3b, 0x75, - 0xc3, 0x34, 0x62, 0xe3, 0xe1, 0xaa, 0x60, 0x32, 0xb6, 0x0a, 0xee, 0x83, 0x4c, 0x58, 0x8d, 0xb9, - 0xe6, 0x13, 0x63, 0x5d, 0xf3, 0x92, 0x85, 0xb6, 0x57, 0x23, 0x6f, 0xfa, 0x6a, 0x08, 0x76, 0x69, - 0x90, 0xfa, 0x21, 0x2c, 0xca, 0x25, 0x50, 0xe2, 0xa5, 0x01, 0x21, 0xdf, 0x08, 0x70, 0x32, 0x50, - 0x5b, 0xd3, 0x1c, 0xad, 0x83, 0xc5, 0x5b, 0x90, 0xd3, 0x7a, 0xee, 0xa6, 0xed, 0x98, 0xee, 0x2e, - 0x23, 0xa2, 0x2e, 0xfd, 0xf8, 0xed, 0x42, 0xc1, 0x3b, 0x08, 0x96, 0xd9, 0x89, 0xb5, 0xee, 0x3a, - 0xa6, 0x65, 0xa8, 0x7d, 0x55, 0xf1, 0x75, 0x48, 0x77, 0xa9, 0x07, 0x4a, 0xd2, 0x54, 0x4d, 0x1a, - 0x06, 0xcb, 0x56, 0xa8, 0xe7, 0xc8, 0xc9, 0xc1, 0x4e, 0x03, 0xcf, 0x84, 0xed, 0x8c, 0xbe, 0x33, - 0x02, 0xb1, 0x30, 0x08, 0x91, 0xd9, 0x2a, 0x73, 0xf4, 0x5a, 0xe3, 0xa7, 0x02, 0x30, 0xdf, 0x33, - 0x30, 0xeb, 0x3d, 0xdd, 0x0e, 0x36, 0xfd, 0x51, 0xc1, 0xfc, 0x23, 0x87, 0xe9, 0x48, 0x54, 0x7c, - 0x98, 0xca, 0x02, 0x45, 0xc5, 0x4f, 0x8d, 0xdc, 0xec, 0x5f, 0x08, 0x30, 0xd5, 0xc0, 0xc6, 0x9a, - 0x69, 0x91, 0x22, 0x3c, 0x7a, 0xca, 0x5e, 0x23, 0x28, 0x69, 0x61, 0x93, 0xa4, 0x25, 0xca, 0xc9, - 0x7a, 0x71, 0x7f, 0xaf, 0x94, 0x61, 0x95, 0x8d, 0xff, 0xdc, 0x2b, 0x9d, 0xdc, 0xd5, 0x3a, 0x5b, - 0x4b, 0x8a, 0xaf, 0xa4, 0xa8, 0x19, 0x56, 0xed, 0x98, 0x9d, 0x05, 0x83, 0xd0, 0xa6, 0x7d, 0x68, - 0x7e, 0x5c, 0xca, 0x19, 0x38, 0xcd, 0x0d, 0x83, 0x44, 0x7d, 0x25, 0xd0, 0x93, 0xe0, 0x8e, 0xd5, - 0xfd, 0x17, 0x01, 0x5c, 0x1e, 0x06, 0x10, 0x9c, 0x25, 0xfd, 0xc8, 0xbc, 0xb3, 0xa4, 0x3f, 0x11, - 0x80, 0xf8, 0x21, 0x49, 0x3b, 0x36, 0xda, 0x4d, 0x2f, 0x5b, 0x7a, 0x54, 0xef, 0x7b, 0x54, 0x54, - 0xc3, 0xaf, 0x8c, 0xc4, 0x31, 0x5f, 0x19, 0xc9, 0x63, 0xbc, 0x32, 0xc4, 0xf3, 0x00, 0x3d, 0x82, - 0x9f, 0x85, 0x92, 0xa2, 0x2d, 0x52, 0xae, 0xe7, 0x33, 0xd2, 0xef, 0x1a, 0xd3, 0x7c, 0xd7, 0x18, - 0x34, 0x84, 0x99, 0x88, 0x86, 0x30, 0x7b, 0x88, 0x3e, 0x24, 0xf7, 0x62, 0x1b, 0x42, 0x72, 0xe6, - 0xdb, 0x3d, 0xa7, 0x8d, 0x24, 0xf0, 0xce, 0x7c, 0x3a, 0x22, 0xad, 0x5a, 0xab, 0x67, 0x6e, 0x91, - 0xcb, 0x60, 0x8a, 0xb5, 0x6a, 0xde, 0x90, 0x5c, 0x9f, 0xb4, 0x9c, 0x36, 0x35, 0xbc, 0x29, 0xe5, - 0xbd, 0x97, 0x90, 0xad, 0xa3, 0xb7, 0x34, 0xbc, 0xb9, 0x74, 0x6b, 0xb8, 0xaa, 0x2e, 0x0e, 0x3c, - 0xca, 0xa2, 0x4b, 0x45, 0xb9, 0x0b, 0x57, 0x46, 0x6b, 0x1c, 0xad, 0x87, 0xac, 0x7d, 0x07, 0x90, - 0x68, 0x60, 0x43, 0x5c, 0x87, 0x5c, 0xff, 0x75, 0x1b, 0x51, 0x07, 0xfc, 0xbb, 0x50, 0xbe, 0x32, - 0x5a, 0x1e, 0x84, 0xf2, 0x01, 0x9c, 0x8e, 0x2a, 0xfb, 0x72, 0xa4, 0x79, 0x84, 0xa6, 0x7c, 0x73, - 0x5c, 0xcd, 0x60, 0x49, 0x17, 0x0a, 0x91, 0x4f, 0x9a, 0x6b, 0xe3, 0x7a, 0xaa, 0xc9, 0x8b, 0x63, - 0xab, 0x06, 0xab, 0x22, 0x38, 0x19, 0xee, 0xc2, 0x2f, 0x45, 0x7a, 0x09, 0x69, 0xc9, 0x37, 0xc6, - 0xd1, 0xe2, 0x97, 0x09, 0x37, 0xad, 0xd1, 0xcb, 0x84, 0xb4, 0x62, 0x96, 0x89, 0x6b, 0x1f, 0xdf, - 0x83, 0x29, 0xbe, 0x4d, 0x9c, 0x8f, 0x34, 0xe6, 0x34, 0xe4, 0xf2, 0x41, 0x1a, 0x81, 0xeb, 0xbb, - 0x00, 0x5c, 0x7f, 0x57, 0x8a, 0xb4, 0xeb, 0x2b, 0xc8, 0x57, 0x0f, 0x50, 0x08, 0xfc, 0x7e, 0x08, - 0xb3, 0x71, 0x4d, 0xdb, 0x8d, 0x11, 0xc1, 0x0d, 0x69, 0xcb, 0x2f, 0x1f, 0x46, 0x3b, 0x58, 0xfe, - 0x3e, 0xe4, 0x07, 0x5a, 0xa4, 0x0b, 0x23, 0xbc, 0x30, 0x15, 0xf9, 0xda, 0x81, 0x2a, 0xbc, 0xf7, - 0x81, 0x9e, 0x25, 0xda, 0x3b, 0xaf, 0x12, 0xe3, 0x3d, 0xb2, 0x7f, 0x58, 0x83, 0x6c, 0xd0, 0x27, - 0x9c, 0x8f, 0x34, 0xf3, 0xc5, 0xf2, 0xe5, 0x91, 0x62, 0x3e, 0xc9, 0xdc, 0xd5, 0x1d, 0x9d, 0xe4, - 0xbe, 0x42, 0x4c, 0x92, 0x87, 0x6f, 0x54, 0xf1, 0x53, 0x01, 0xce, 0x8e, 0xba, 0x4e, 0x6f, 0xc6, - 0x1f, 0x4b, 0xd1, 0x16, 0xf2, 0xab, 0x87, 0xb5, 0xf0, 0x63, 0xa9, 0xbf, 0xfd, 0xe4, 0xd7, 0xe2, - 0xc4, 0x93, 0xfd, 0xa2, 0xf0, 0x74, 0xbf, 0x28, 0xfc, 0xb2, 0x5f, 0x14, 0x3e, 0x7f, 0x56, 0x9c, - 0x78, 0xfa, 0xac, 0x38, 0xf1, 0xd3, 0xb3, 0xe2, 0xc4, 0xfb, 0x0b, 0xdc, 0x55, 0xe3, 0x22, 0xa7, - 0x6b, 0x21, 0x77, 0xdb, 0x76, 0x1e, 0xd0, 0xef, 0x85, 0xb6, 0xed, 0xa0, 0xea, 0x0e, 0xfb, 0xaf, - 0x24, 0xbd, 0x75, 0x5a, 0x69, 0xfa, 0x5f, 0xc6, 0x97, 0xfe, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x9a, - 0xd3, 0x93, 0x78, 0x2f, 0x15, 0x00, 0x00, -} - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ context.Context - _ 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 { - // StoreCode to submit Wasm code to the system - StoreCode(ctx context.Context, in *MsgStoreCode, opts ...grpc.CallOption) (*MsgStoreCodeResponse, error) - // InstantiateContract creates a new smart contract instance for the given - // code id. - InstantiateContract(ctx context.Context, in *MsgInstantiateContract, opts ...grpc.CallOption) (*MsgInstantiateContractResponse, error) - // InstantiateContract2 creates a new smart contract instance for the given - // code id with a predictable address - InstantiateContract2(ctx context.Context, in *MsgInstantiateContract2, opts ...grpc.CallOption) (*MsgInstantiateContract2Response, error) - // Execute submits the given message data to a smart contract - ExecuteContract(ctx context.Context, in *MsgExecuteContract, opts ...grpc.CallOption) (*MsgExecuteContractResponse, error) - // Migrate runs a code upgrade/ downgrade for a smart contract - MigrateContract(ctx context.Context, in *MsgMigrateContract, opts ...grpc.CallOption) (*MsgMigrateContractResponse, error) - // UpdateAdmin sets a new admin for a smart contract - UpdateAdmin(ctx context.Context, in *MsgUpdateAdmin, opts ...grpc.CallOption) (*MsgUpdateAdminResponse, error) - // ClearAdmin removes any admin stored for a smart contract - ClearAdmin(ctx context.Context, in *MsgClearAdmin, opts ...grpc.CallOption) (*MsgClearAdminResponse, error) - // UpdateInstantiateConfig updates instantiate config for a smart contract - UpdateInstantiateConfig(ctx context.Context, in *MsgUpdateInstantiateConfig, opts ...grpc.CallOption) (*MsgUpdateInstantiateConfigResponse, error) - // UpdateParams defines a governance operation for updating the x/wasm - // module parameters. The authority is defined in the keeper. - // - // Since: 0.40 - UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) - // SudoContract defines a governance operation for calling sudo - // on a contract. The authority is defined in the keeper. - // - // Since: 0.40 - SudoContract(ctx context.Context, in *MsgSudoContract, opts ...grpc.CallOption) (*MsgSudoContractResponse, error) - // PinCodes defines a governance operation for pinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - PinCodes(ctx context.Context, in *MsgPinCodes, opts ...grpc.CallOption) (*MsgPinCodesResponse, error) - // UnpinCodes defines a governance operation for unpinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - UnpinCodes(ctx context.Context, in *MsgUnpinCodes, opts ...grpc.CallOption) (*MsgUnpinCodesResponse, error) - // StoreAndInstantiateContract defines a governance operation for storing - // and instantiating the contract. The authority is defined in the keeper. - // - // Since: 0.40 - StoreAndInstantiateContract(ctx context.Context, in *MsgStoreAndInstantiateContract, opts ...grpc.CallOption) (*MsgStoreAndInstantiateContractResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) StoreCode(ctx context.Context, in *MsgStoreCode, opts ...grpc.CallOption) (*MsgStoreCodeResponse, error) { - out := new(MsgStoreCodeResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/StoreCode", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) InstantiateContract(ctx context.Context, in *MsgInstantiateContract, opts ...grpc.CallOption) (*MsgInstantiateContractResponse, error) { - out := new(MsgInstantiateContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/InstantiateContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) InstantiateContract2(ctx context.Context, in *MsgInstantiateContract2, opts ...grpc.CallOption) (*MsgInstantiateContract2Response, error) { - out := new(MsgInstantiateContract2Response) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/InstantiateContract2", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ExecuteContract(ctx context.Context, in *MsgExecuteContract, opts ...grpc.CallOption) (*MsgExecuteContractResponse, error) { - out := new(MsgExecuteContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/ExecuteContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) MigrateContract(ctx context.Context, in *MsgMigrateContract, opts ...grpc.CallOption) (*MsgMigrateContractResponse, error) { - out := new(MsgMigrateContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/MigrateContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateAdmin(ctx context.Context, in *MsgUpdateAdmin, opts ...grpc.CallOption) (*MsgUpdateAdminResponse, error) { - out := new(MsgUpdateAdminResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/UpdateAdmin", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) ClearAdmin(ctx context.Context, in *MsgClearAdmin, opts ...grpc.CallOption) (*MsgClearAdminResponse, error) { - out := new(MsgClearAdminResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/ClearAdmin", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateInstantiateConfig(ctx context.Context, in *MsgUpdateInstantiateConfig, opts ...grpc.CallOption) (*MsgUpdateInstantiateConfigResponse, error) { - out := new(MsgUpdateInstantiateConfigResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/UpdateInstantiateConfig", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateParams(ctx context.Context, in *MsgUpdateParams, opts ...grpc.CallOption) (*MsgUpdateParamsResponse, error) { - out := new(MsgUpdateParamsResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/UpdateParams", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) SudoContract(ctx context.Context, in *MsgSudoContract, opts ...grpc.CallOption) (*MsgSudoContractResponse, error) { - out := new(MsgSudoContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/SudoContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) PinCodes(ctx context.Context, in *MsgPinCodes, opts ...grpc.CallOption) (*MsgPinCodesResponse, error) { - out := new(MsgPinCodesResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/PinCodes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UnpinCodes(ctx context.Context, in *MsgUnpinCodes, opts ...grpc.CallOption) (*MsgUnpinCodesResponse, error) { - out := new(MsgUnpinCodesResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/UnpinCodes", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) StoreAndInstantiateContract(ctx context.Context, in *MsgStoreAndInstantiateContract, opts ...grpc.CallOption) (*MsgStoreAndInstantiateContractResponse, error) { - out := new(MsgStoreAndInstantiateContractResponse) - err := c.cc.Invoke(ctx, "/cosmwasm.wasm.v1.Msg/StoreAndInstantiateContract", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - // StoreCode to submit Wasm code to the system - StoreCode(context.Context, *MsgStoreCode) (*MsgStoreCodeResponse, error) - // InstantiateContract creates a new smart contract instance for the given - // code id. - InstantiateContract(context.Context, *MsgInstantiateContract) (*MsgInstantiateContractResponse, error) - // InstantiateContract2 creates a new smart contract instance for the given - // code id with a predictable address - InstantiateContract2(context.Context, *MsgInstantiateContract2) (*MsgInstantiateContract2Response, error) - // Execute submits the given message data to a smart contract - ExecuteContract(context.Context, *MsgExecuteContract) (*MsgExecuteContractResponse, error) - // Migrate runs a code upgrade/ downgrade for a smart contract - MigrateContract(context.Context, *MsgMigrateContract) (*MsgMigrateContractResponse, error) - // UpdateAdmin sets a new admin for a smart contract - UpdateAdmin(context.Context, *MsgUpdateAdmin) (*MsgUpdateAdminResponse, error) - // ClearAdmin removes any admin stored for a smart contract - ClearAdmin(context.Context, *MsgClearAdmin) (*MsgClearAdminResponse, error) - // UpdateInstantiateConfig updates instantiate config for a smart contract - UpdateInstantiateConfig(context.Context, *MsgUpdateInstantiateConfig) (*MsgUpdateInstantiateConfigResponse, error) - // UpdateParams defines a governance operation for updating the x/wasm - // module parameters. The authority is defined in the keeper. - // - // Since: 0.40 - UpdateParams(context.Context, *MsgUpdateParams) (*MsgUpdateParamsResponse, error) - // SudoContract defines a governance operation for calling sudo - // on a contract. The authority is defined in the keeper. - // - // Since: 0.40 - SudoContract(context.Context, *MsgSudoContract) (*MsgSudoContractResponse, error) - // PinCodes defines a governance operation for pinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - PinCodes(context.Context, *MsgPinCodes) (*MsgPinCodesResponse, error) - // UnpinCodes defines a governance operation for unpinning a set of - // code ids in the wasmvm cache. The authority is defined in the keeper. - // - // Since: 0.40 - UnpinCodes(context.Context, *MsgUnpinCodes) (*MsgUnpinCodesResponse, error) - // StoreAndInstantiateContract defines a governance operation for storing - // and instantiating the contract. The authority is defined in the keeper. - // - // Since: 0.40 - StoreAndInstantiateContract(context.Context, *MsgStoreAndInstantiateContract) (*MsgStoreAndInstantiateContractResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct{} - -func (*UnimplementedMsgServer) StoreCode(ctx context.Context, req *MsgStoreCode) (*MsgStoreCodeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method StoreCode not implemented") -} - -func (*UnimplementedMsgServer) InstantiateContract(ctx context.Context, req *MsgInstantiateContract) (*MsgInstantiateContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method InstantiateContract not implemented") -} - -func (*UnimplementedMsgServer) InstantiateContract2(ctx context.Context, req *MsgInstantiateContract2) (*MsgInstantiateContract2Response, error) { - return nil, status.Errorf(codes.Unimplemented, "method InstantiateContract2 not implemented") -} - -func (*UnimplementedMsgServer) ExecuteContract(ctx context.Context, req *MsgExecuteContract) (*MsgExecuteContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ExecuteContract not implemented") -} - -func (*UnimplementedMsgServer) MigrateContract(ctx context.Context, req *MsgMigrateContract) (*MsgMigrateContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MigrateContract not implemented") -} - -func (*UnimplementedMsgServer) UpdateAdmin(ctx context.Context, req *MsgUpdateAdmin) (*MsgUpdateAdminResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateAdmin not implemented") -} - -func (*UnimplementedMsgServer) ClearAdmin(ctx context.Context, req *MsgClearAdmin) (*MsgClearAdminResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClearAdmin not implemented") -} - -func (*UnimplementedMsgServer) UpdateInstantiateConfig(ctx context.Context, req *MsgUpdateInstantiateConfig) (*MsgUpdateInstantiateConfigResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateInstantiateConfig not implemented") -} - -func (*UnimplementedMsgServer) UpdateParams(ctx context.Context, req *MsgUpdateParams) (*MsgUpdateParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateParams not implemented") -} - -func (*UnimplementedMsgServer) SudoContract(ctx context.Context, req *MsgSudoContract) (*MsgSudoContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SudoContract not implemented") -} - -func (*UnimplementedMsgServer) PinCodes(ctx context.Context, req *MsgPinCodes) (*MsgPinCodesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method PinCodes not implemented") -} - -func (*UnimplementedMsgServer) UnpinCodes(ctx context.Context, req *MsgUnpinCodes) (*MsgUnpinCodesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UnpinCodes not implemented") -} - -func (*UnimplementedMsgServer) StoreAndInstantiateContract(ctx context.Context, req *MsgStoreAndInstantiateContract) (*MsgStoreAndInstantiateContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method StoreAndInstantiateContract not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_StoreCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgStoreCode) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).StoreCode(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/StoreCode", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).StoreCode(ctx, req.(*MsgStoreCode)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_InstantiateContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgInstantiateContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).InstantiateContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/InstantiateContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).InstantiateContract(ctx, req.(*MsgInstantiateContract)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_InstantiateContract2_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgInstantiateContract2) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).InstantiateContract2(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/InstantiateContract2", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).InstantiateContract2(ctx, req.(*MsgInstantiateContract2)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ExecuteContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgExecuteContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ExecuteContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/ExecuteContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ExecuteContract(ctx, req.(*MsgExecuteContract)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_MigrateContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgMigrateContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).MigrateContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/MigrateContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).MigrateContract(ctx, req.(*MsgMigrateContract)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateAdmin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateAdmin) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateAdmin(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/UpdateAdmin", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateAdmin(ctx, req.(*MsgUpdateAdmin)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_ClearAdmin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgClearAdmin) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).ClearAdmin(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/ClearAdmin", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).ClearAdmin(ctx, req.(*MsgClearAdmin)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateInstantiateConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateInstantiateConfig) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateInstantiateConfig(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/UpdateInstantiateConfig", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateInstantiateConfig(ctx, req.(*MsgUpdateInstantiateConfig)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateParams_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateParams(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/UpdateParams", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_SudoContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgSudoContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).SudoContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/SudoContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).SudoContract(ctx, req.(*MsgSudoContract)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_PinCodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgPinCodes) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).PinCodes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/PinCodes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).PinCodes(ctx, req.(*MsgPinCodes)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UnpinCodes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUnpinCodes) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UnpinCodes(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/UnpinCodes", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UnpinCodes(ctx, req.(*MsgUnpinCodes)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_StoreAndInstantiateContract_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgStoreAndInstantiateContract) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).StoreAndInstantiateContract(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/cosmwasm.wasm.v1.Msg/StoreAndInstantiateContract", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).StoreAndInstantiateContract(ctx, req.(*MsgStoreAndInstantiateContract)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmwasm.wasm.v1.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "StoreCode", - Handler: _Msg_StoreCode_Handler, - }, - { - MethodName: "InstantiateContract", - Handler: _Msg_InstantiateContract_Handler, - }, - { - MethodName: "InstantiateContract2", - Handler: _Msg_InstantiateContract2_Handler, - }, - { - MethodName: "ExecuteContract", - Handler: _Msg_ExecuteContract_Handler, - }, - { - MethodName: "MigrateContract", - Handler: _Msg_MigrateContract_Handler, - }, - { - MethodName: "UpdateAdmin", - Handler: _Msg_UpdateAdmin_Handler, - }, - { - MethodName: "ClearAdmin", - Handler: _Msg_ClearAdmin_Handler, - }, - { - MethodName: "UpdateInstantiateConfig", - Handler: _Msg_UpdateInstantiateConfig_Handler, - }, - { - MethodName: "UpdateParams", - Handler: _Msg_UpdateParams_Handler, - }, - { - MethodName: "SudoContract", - Handler: _Msg_SudoContract_Handler, - }, - { - MethodName: "PinCodes", - Handler: _Msg_PinCodes_Handler, - }, - { - MethodName: "UnpinCodes", - Handler: _Msg_UnpinCodes_Handler, - }, - { - MethodName: "StoreAndInstantiateContract", - Handler: _Msg_StoreAndInstantiateContract_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmwasm/wasm/v1/tx.proto", -} - -func (m *MsgStoreCode) 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 *MsgStoreCode) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgStoreCode) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.InstantiatePermission != nil { - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - if len(m.WASMByteCode) > 0 { - i -= len(m.WASMByteCode) - copy(dAtA[i:], m.WASMByteCode) - i = encodeVarintTx(dAtA, i, uint64(len(m.WASMByteCode))) - 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 *MsgStoreCodeResponse) 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 *MsgStoreCodeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgStoreCodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Checksum) > 0 { - i -= len(m.Checksum) - copy(dAtA[i:], m.Checksum) - i = encodeVarintTx(dAtA, i, uint64(len(m.Checksum))) - i-- - dAtA[i] = 0x12 - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgInstantiateContract) 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 *MsgInstantiateContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgInstantiateContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x2a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintTx(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x22 - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintTx(dAtA, i, uint64(len(m.Admin))) - 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 *MsgInstantiateContractResponse) 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 *MsgInstantiateContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgInstantiateContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintTx(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgInstantiateContract2) 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 *MsgInstantiateContract2) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgInstantiateContract2) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.FixMsg { - i-- - if m.FixMsg { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x40 - } - if len(m.Salt) > 0 { - i -= len(m.Salt) - copy(dAtA[i:], m.Salt) - i = encodeVarintTx(dAtA, i, uint64(len(m.Salt))) - i-- - dAtA[i] = 0x3a - } - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x32 - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x2a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintTx(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x22 - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintTx(dAtA, i, uint64(len(m.Admin))) - 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 *MsgInstantiateContract2Response) 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 *MsgInstantiateContract2Response) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgInstantiateContract2Response) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintTx(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgExecuteContract) 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 *MsgExecuteContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgExecuteContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x1a - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - 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 *MsgExecuteContractResponse) 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 *MsgExecuteContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgExecuteContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgMigrateContract) 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 *MsgMigrateContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMigrateContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x22 - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x18 - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - 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 *MsgMigrateContractResponse) 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 *MsgMigrateContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgMigrateContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateAdmin) 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 *MsgUpdateAdmin) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateAdmin) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x1a - } - if len(m.NewAdmin) > 0 { - i -= len(m.NewAdmin) - copy(dAtA[i:], m.NewAdmin) - i = encodeVarintTx(dAtA, i, uint64(len(m.NewAdmin))) - 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 *MsgUpdateAdminResponse) 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 *MsgUpdateAdminResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateAdminResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgClearAdmin) 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 *MsgClearAdmin) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClearAdmin) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x1a - } - 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 *MsgClearAdminResponse) 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 *MsgClearAdminResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgClearAdminResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUpdateInstantiateConfig) 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 *MsgUpdateInstantiateConfig) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateInstantiateConfig) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.NewInstantiatePermission != nil { - { - size, err := m.NewInstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if m.CodeID != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x10 - } - if len(m.Sender) > 0 { - i -= len(m.Sender) - copy(dAtA[i:], m.Sender) - i = encodeVarintTx(dAtA, i, uint64(len(m.Sender))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateInstantiateConfigResponse) 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 *MsgUpdateInstantiateConfigResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateInstantiateConfigResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParams) 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 *MsgUpdateParams) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParams) 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 = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateParamsResponse) 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 *MsgUpdateParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgSudoContract) 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 *MsgSudoContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSudoContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x1a - } - if len(m.Contract) > 0 { - i -= len(m.Contract) - copy(dAtA[i:], m.Contract) - i = encodeVarintTx(dAtA, i, uint64(len(m.Contract))) - i-- - dAtA[i] = 0x12 - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgSudoContractResponse) 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 *MsgSudoContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgSudoContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgPinCodes) 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 *MsgPinCodes) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPinCodes) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeIDs) > 0 { - dAtA5 := make([]byte, len(m.CodeIDs)*10) - var j4 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA5[j4] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j4++ - } - dAtA5[j4] = uint8(num) - j4++ - } - i -= j4 - copy(dAtA[i:], dAtA5[:j4]) - i = encodeVarintTx(dAtA, i, uint64(j4)) - i-- - dAtA[i] = 0x12 - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgPinCodesResponse) 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 *MsgPinCodesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgPinCodesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgUnpinCodes) 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 *MsgUnpinCodes) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUnpinCodes) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeIDs) > 0 { - dAtA7 := make([]byte, len(m.CodeIDs)*10) - var j6 int - for _, num := range m.CodeIDs { - for num >= 1<<7 { - dAtA7[j6] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j6++ - } - dAtA7[j6] = uint8(num) - j6++ - } - i -= j6 - copy(dAtA[i:], dAtA7[:j6]) - i = encodeVarintTx(dAtA, i, uint64(j6)) - i-- - dAtA[i] = 0x12 - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUnpinCodesResponse) 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 *MsgUnpinCodesResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUnpinCodesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgStoreAndInstantiateContract) 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 *MsgStoreAndInstantiateContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgStoreAndInstantiateContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.CodeHash) > 0 { - i -= len(m.CodeHash) - copy(dAtA[i:], m.CodeHash) - i = encodeVarintTx(dAtA, i, uint64(len(m.CodeHash))) - i-- - dAtA[i] = 0x62 - } - if len(m.Builder) > 0 { - i -= len(m.Builder) - copy(dAtA[i:], m.Builder) - i = encodeVarintTx(dAtA, i, uint64(len(m.Builder))) - i-- - dAtA[i] = 0x5a - } - if len(m.Source) > 0 { - i -= len(m.Source) - copy(dAtA[i:], m.Source) - i = encodeVarintTx(dAtA, i, uint64(len(m.Source))) - i-- - dAtA[i] = 0x52 - } - if len(m.Funds) > 0 { - for iNdEx := len(m.Funds) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Funds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - } - } - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTx(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x42 - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintTx(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x3a - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintTx(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x32 - } - if m.UnpinCode { - i-- - if m.UnpinCode { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x28 - } - if m.InstantiatePermission != nil { - { - size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTx(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - if len(m.WASMByteCode) > 0 { - i -= len(m.WASMByteCode) - copy(dAtA[i:], m.WASMByteCode) - i = encodeVarintTx(dAtA, i, uint64(len(m.WASMByteCode))) - i-- - dAtA[i] = 0x1a - } - if len(m.Authority) > 0 { - i -= len(m.Authority) - copy(dAtA[i:], m.Authority) - i = encodeVarintTx(dAtA, i, uint64(len(m.Authority))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgStoreAndInstantiateContractResponse) 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 *MsgStoreAndInstantiateContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgStoreAndInstantiateContractResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Data) > 0 { - i -= len(m.Data) - copy(dAtA[i:], m.Data) - i = encodeVarintTx(dAtA, i, uint64(len(m.Data))) - i-- - dAtA[i] = 0x12 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintTx(dAtA, i, uint64(len(m.Address))) - 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 *MsgStoreCode) 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.WASMByteCode) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.InstantiatePermission != nil { - l = m.InstantiatePermission.Size() - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgStoreCodeResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - l = len(m.Checksum) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgInstantiateContract) 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.Admin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgInstantiateContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgInstantiateContract2) 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.Admin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - l = len(m.Salt) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.FixMsg { - n += 2 - } - return n -} - -func (m *MsgInstantiateContract2Response) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgExecuteContract) 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.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - return n -} - -func (m *MsgExecuteContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgMigrateContract) 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.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgMigrateContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgUpdateAdmin) 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.NewAdmin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgUpdateAdminResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgClearAdmin) 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.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgClearAdminResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUpdateInstantiateConfig) 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.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) - } - if m.NewInstantiatePermission != nil { - l = m.NewInstantiatePermission.Size() - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgUpdateInstantiateConfigResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUpdateParams) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = m.Params.Size() - n += 1 + l + sovTx(uint64(l)) - return n -} - -func (m *MsgUpdateParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgSudoContract) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgSudoContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgPinCodes) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovTx(uint64(e)) - } - n += 1 + sovTx(uint64(l)) + l - } - return n -} - -func (m *MsgPinCodesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgUnpinCodes) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.CodeIDs) > 0 { - l = 0 - for _, e := range m.CodeIDs { - l += sovTx(uint64(e)) - } - n += 1 + sovTx(uint64(l)) + l - } - return n -} - -func (m *MsgUnpinCodesResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgStoreAndInstantiateContract) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Authority) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.WASMByteCode) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.InstantiatePermission != nil { - l = m.InstantiatePermission.Size() - n += 1 + l + sovTx(uint64(l)) - } - if m.UnpinCode { - n += 2 - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } - } - l = len(m.Source) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Builder) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.CodeHash) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgStoreAndInstantiateContractResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Data) - if l > 0 { - 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 *MsgStoreCode) 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: MsgStoreCode: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreCode: 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 WASMByteCode", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) - if m.WASMByteCode == nil { - m.WASMByteCode = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", 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.InstantiatePermission == nil { - m.InstantiatePermission = &AccessConfig{} - } - if err := m.InstantiatePermission.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 *MsgStoreCodeResponse) 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: MsgStoreCodeResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Checksum", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Checksum = append(m.Checksum[:0], dAtA[iNdEx:postIndex]...) - if m.Checksum == nil { - m.Checksum = []byte{} - } - 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 *MsgInstantiateContract) 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: MsgInstantiateContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContract: 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 Admin", 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.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", 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.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", 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.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-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 *MsgInstantiateContractResponse) 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: MsgInstantiateContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 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.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - 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 *MsgInstantiateContract2) 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: MsgInstantiateContract2: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContract2: 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 Admin", 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.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", 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.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", 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.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Salt", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Salt = append(m.Salt[:0], dAtA[iNdEx:postIndex]...) - if m.Salt == nil { - m.Salt = []byte{} - } - iNdEx = postIndex - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field FixMsg", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.FixMsg = bool(v != 0) - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgInstantiateContract2Response) 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: MsgInstantiateContract2Response: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContract2Response: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 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.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - 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 *MsgExecuteContract) 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: MsgExecuteContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgExecuteContract: 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 Contract", 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.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", 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.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-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 *MsgExecuteContractResponse) 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: MsgExecuteContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgExecuteContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - 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 *MsgMigrateContract) 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: MsgMigrateContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMigrateContract: 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 Contract", 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.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - 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 *MsgMigrateContractResponse) 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: MsgMigrateContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMigrateContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - 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 *MsgUpdateAdmin) 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: MsgUpdateAdmin: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateAdmin: 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 NewAdmin", 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.NewAdmin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", 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.Contract = 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 *MsgUpdateAdminResponse) 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: MsgUpdateAdminResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateAdminResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgClearAdmin) 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: MsgClearAdmin: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClearAdmin: 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 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", 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.Contract = 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 *MsgClearAdminResponse) 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: MsgClearAdminResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClearAdminResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateInstantiateConfig) 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: MsgUpdateInstantiateConfig: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateInstantiateConfig: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewInstantiatePermission", 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.NewInstantiatePermission == nil { - m.NewInstantiatePermission = &AccessConfig{} - } - if err := m.NewInstantiatePermission.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 *MsgUpdateInstantiateConfigResponse) 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: MsgUpdateInstantiateConfigResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateInstantiateConfigResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateParams) 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: MsgUpdateParams: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParams: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", 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.Authority = 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 err := m.Params.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 *MsgUpdateParamsResponse) 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: MsgUpdateParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgSudoContract) 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: MsgSudoContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSudoContract: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", 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.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", 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.Contract = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - 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 *MsgSudoContractResponse) 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: MsgSudoContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgSudoContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - 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 *MsgPinCodes) 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: MsgPinCodes: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPinCodes: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", 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.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgPinCodesResponse) 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: MsgPinCodesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgPinCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUnpinCodes) 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: MsgUnpinCodes: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUnpinCodes: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", 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.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.CodeIDs) == 0 { - m.CodeIDs = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.CodeIDs = append(m.CodeIDs, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field CodeIDs", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUnpinCodesResponse) 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: MsgUnpinCodesResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUnpinCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgStoreAndInstantiateContract) 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: MsgStoreAndInstantiateContract: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreAndInstantiateContract: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Authority", 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.Authority = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) - if m.WASMByteCode == nil { - m.WASMByteCode = []byte{} - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", 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.InstantiatePermission == nil { - m.InstantiatePermission = &AccessConfig{} - } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field UnpinCode", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.UnpinCode = bool(v != 0) - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", 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.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", 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.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Funds", 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.Funds = append(m.Funds, types.Coin{}) - if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Source", 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.Source = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 11: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Builder", 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.Builder = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) - if m.CodeHash == nil { - m.CodeHash = []byte{} - } - 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 *MsgStoreAndInstantiateContractResponse) 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: MsgStoreAndInstantiateContractResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreAndInstantiateContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 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.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - 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/wasm/types/tx_test.go b/x/wasm/types/tx_test.go deleted file mode 100644 index 355beae..0000000 --- a/x/wasm/types/tx_test.go +++ /dev/null @@ -1,1139 +0,0 @@ -package types - -import ( - "bytes" - "strings" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -const firstCodeID = 1 - -func TestStoreCodeValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, ContractAddrLen)).String() - sdk.GetConfig().SetAddressVerifier(VerifyAddressLen()) - cases := map[string]struct { - msg MsgStoreCode - valid bool - }{ - "empty": { - msg: MsgStoreCode{}, - valid: false, - }, - "correct minimal": { - msg: MsgStoreCode{ - Sender: goodAddress, - WASMByteCode: []byte("foo"), - }, - valid: true, - }, - "missing code": { - msg: MsgStoreCode{ - Sender: goodAddress, - }, - valid: false, - }, - "bad sender minimal": { - msg: MsgStoreCode{ - Sender: badAddress, - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "correct maximal": { - msg: MsgStoreCode{ - Sender: goodAddress, - WASMByteCode: []byte("foo"), - }, - valid: true, - }, - "invalid InstantiatePermission": { - msg: MsgStoreCode{ - Sender: goodAddress, - WASMByteCode: []byte("foo"), - InstantiatePermission: &AccessConfig{Permission: AccessTypeOnlyAddress, Address: badAddress}, - }, - valid: false, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestInstantiateContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - sdk.GetConfig().SetAddressVerifier(VerifyAddressLen()) - - cases := map[string]struct { - msg MsgInstantiateContract - valid bool - }{ - "empty": { - msg: MsgInstantiateContract{}, - valid: false, - }, - "correct minimal": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("{}"), - }, - valid: true, - }, - "missing code": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - Label: "foo", - Msg: []byte("{}"), - }, - valid: false, - }, - "missing label": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - Msg: []byte("{}"), - }, - valid: false, - }, - "label too long": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - Label: strings.Repeat("food", 33), - }, - valid: false, - }, - "bad sender minimal": { - msg: MsgInstantiateContract{ - Sender: badAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("{}"), - }, - valid: false, - }, - "correct maximal": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(200)}}, - }, - valid: true, - }, - "negative funds": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - // we cannot use sdk.NewCoin() constructors as they panic on creating invalid data (before we can test) - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(-200)}}, - }, - valid: false, - }, - "non json init msg": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("invalid-json"), - }, - valid: false, - }, - "empty init msg": { - msg: MsgInstantiateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - }, - valid: false, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestInstantiateContract2Validation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - sdk.GetConfig().SetAddressVerifier(VerifyAddressLen()) - - cases := map[string]struct { - msg MsgInstantiateContract2 - valid bool - }{ - "empty": { - msg: MsgInstantiateContract2{}, - valid: false, - }, - "correct minimal": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("{}"), - Salt: []byte{0}, - }, - valid: true, - }, - "missing code": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - Label: "foo", - Msg: []byte("{}"), - Salt: []byte{0}, - }, - valid: false, - }, - "missing label": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - Msg: []byte("{}"), - Salt: []byte{0}, - }, - valid: false, - }, - "label too long": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - Label: strings.Repeat("food", 33), - Salt: []byte{0}, - }, - valid: false, - }, - "bad sender minimal": { - msg: MsgInstantiateContract2{ - Sender: badAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("{}"), - Salt: []byte{0}, - }, - valid: false, - }, - "correct maximal": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: strings.Repeat("a", MaxLabelSize), - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(200)}}, - Salt: bytes.Repeat([]byte{0}, MaxSaltSize), - FixMsg: true, - }, - valid: true, - }, - "negative funds": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - // we cannot use sdk.NewCoin() constructors as they panic on creating invalid data (before we can test) - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(-200)}}, - Salt: []byte{0}, - }, - valid: false, - }, - "non json init msg": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte("invalid-json"), - Salt: []byte{0}, - }, - valid: false, - }, - "empty init msg": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Salt: []byte{0}, - }, - valid: false, - }, - "empty salt": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "salt too long": { - msg: MsgInstantiateContract2{ - Sender: goodAddress, - CodeID: firstCodeID, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - Salt: bytes.Repeat([]byte{0}, 65), - }, - valid: false, - }, - } - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestExecuteContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - - cases := map[string]struct { - msg MsgExecuteContract - valid bool - }{ - "empty": { - msg: MsgExecuteContract{}, - valid: false, - }, - "correct minimal": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte("{}"), - }, - valid: true, - }, - "correct all": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(200)}}, - }, - valid: true, - }, - "bad sender": { - msg: MsgExecuteContract{ - Sender: badAddress, - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "empty sender": { - msg: MsgExecuteContract{ - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "bad contract": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: badAddress, - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "empty contract": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Msg: []byte(`{"some": "data"}`), - }, - valid: false, - }, - "negative funds": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(-1)}}, - }, - valid: false, - }, - "duplicate funds": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(1)}, sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(1)}}, - }, - valid: false, - }, - "non json msg": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - Msg: []byte("invalid-json"), - }, - valid: false, - }, - "empty msg": { - msg: MsgExecuteContract{ - Sender: goodAddress, - Contract: goodAddress, - }, - valid: false, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} - -func TestMsgUpdateAdministrator(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - otherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x1}, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgUpdateAdmin - expErr bool - }{ - "all good": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - NewAdmin: otherGoodAddress, - Contract: anotherGoodAddress, - }, - }, - "new admin required": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad sender": { - src: MsgUpdateAdmin{ - Sender: badAddress, - NewAdmin: otherGoodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad new admin": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - NewAdmin: badAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad contract addr": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - NewAdmin: otherGoodAddress, - Contract: badAddress, - }, - expErr: true, - }, - "new admin same as old admin": { - src: MsgUpdateAdmin{ - Sender: goodAddress, - NewAdmin: goodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgClearAdministrator(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgClearAdmin - expErr bool - }{ - "all good": { - src: MsgClearAdmin{ - Sender: goodAddress, - Contract: anotherGoodAddress, - }, - }, - "bad sender": { - src: MsgClearAdmin{ - Sender: badAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad contract addr": { - src: MsgClearAdmin{ - Sender: goodAddress, - Contract: badAddress, - }, - expErr: true, - }, - "contract missing": { - src: MsgClearAdmin{ - Sender: goodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgMigrateContract(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgMigrateContract - expErr bool - }{ - "all good": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: anotherGoodAddress, - CodeID: firstCodeID, - Msg: []byte("{}"), - }, - }, - "bad sender": { - src: MsgMigrateContract{ - Sender: badAddress, - Contract: anotherGoodAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - "empty sender": { - src: MsgMigrateContract{ - Contract: anotherGoodAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - "empty code": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - "bad contract addr": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: badAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - "empty contract addr": { - src: MsgMigrateContract{ - Sender: goodAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - "non json migrateMsg": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: anotherGoodAddress, - CodeID: firstCodeID, - Msg: []byte("invalid json"), - }, - expErr: true, - }, - "empty migrateMsg": { - src: MsgMigrateContract{ - Sender: goodAddress, - Contract: anotherGoodAddress, - CodeID: firstCodeID, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgJsonSignBytes(t *testing.T) { - const myInnerMsg = `{"foo":"bar"}` - specs := map[string]struct { - src legacytx.LegacyMsg - exp string - }{ - "MsgInstantiateContract": { - src: &MsgInstantiateContract{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"wasm/MsgInstantiateContract", - "value": {"msg": {"foo":"bar"}, "funds":[]} -}`, - }, - "MsgExecuteContract": { - src: &MsgExecuteContract{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"wasm/MsgExecuteContract", - "value": {"msg": {"foo":"bar"}, "funds":[]} -}`, - }, - "MsgMigrateContract": { - src: &MsgMigrateContract{Msg: RawContractMessage(myInnerMsg)}, - exp: ` -{ - "type":"wasm/MsgMigrateContract", - "value": {"msg": {"foo":"bar"}} -}`, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - bz := spec.src.GetSignBytes() - assert.JSONEq(t, spec.exp, string(bz), "raw: %s", string(bz)) - }) - } -} - -func TestMsgUpdateInstantiateConfig(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgUpdateInstantiateConfig - expErr bool - }{ - "all good": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - CodeID: 1, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{anotherGoodAddress}}, - }, - }, - "retained AccessTypeOnlyAddress": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - CodeID: 1, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeOnlyAddress, Address: anotherGoodAddress}, - }, - expErr: true, - }, - "bad sender": { - src: MsgUpdateInstantiateConfig{ - Sender: badAddress, - CodeID: 1, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{anotherGoodAddress}}, - }, - expErr: true, - }, - "invalid NewInstantiatePermission": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - CodeID: 1, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{badAddress}}, - }, - expErr: true, - }, - "missing code id": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - NewInstantiatePermission: &AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{anotherGoodAddress}}, - }, - expErr: true, - }, - "missing NewInstantiatePermission": { - src: MsgUpdateInstantiateConfig{ - Sender: goodAddress, - CodeID: 1, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgUpdateParamsValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - - specs := map[string]struct { - src MsgUpdateParams - expErr bool - }{ - "all good": { - src: MsgUpdateParams{ - Authority: goodAddress, - Params: DefaultParams(), - }, - }, - "bad authority": { - src: MsgUpdateParams{ - Authority: badAddress, - Params: DefaultParams(), - }, - expErr: true, - }, - "empty authority": { - src: MsgUpdateParams{ - Params: DefaultParams(), - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgPinCodesValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - - specs := map[string]struct { - src MsgPinCodes - expErr bool - }{ - "all good": { - src: MsgPinCodes{ - Authority: goodAddress, - CodeIDs: []uint64{1}, - }, - }, - "bad authority": { - src: MsgPinCodes{ - Authority: badAddress, - CodeIDs: []uint64{1}, - }, - expErr: true, - }, - "empty authority": { - src: MsgPinCodes{ - CodeIDs: []uint64{1}, - }, - expErr: true, - }, - "empty code ids": { - src: MsgPinCodes{ - Authority: goodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgUnpinCodesValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - - specs := map[string]struct { - src MsgUnpinCodes - expErr bool - }{ - "all good": { - src: MsgUnpinCodes{ - Authority: goodAddress, - CodeIDs: []uint64{1}, - }, - }, - "bad authority": { - src: MsgUnpinCodes{ - Authority: badAddress, - CodeIDs: []uint64{1}, - }, - expErr: true, - }, - "empty authority": { - src: MsgUnpinCodes{ - CodeIDs: []uint64{1}, - }, - expErr: true, - }, - "empty code ids": { - src: MsgUnpinCodes{ - Authority: goodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgSudoContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - anotherGoodAddress := sdk.AccAddress(bytes.Repeat([]byte{0x2}, 20)).String() - - specs := map[string]struct { - src MsgSudoContract - expErr bool - }{ - "all good": { - src: MsgSudoContract{ - Authority: goodAddress, - Contract: anotherGoodAddress, - Msg: []byte("{}"), - }, - }, - "bad authority": { - src: MsgSudoContract{ - Authority: badAddress, - Contract: anotherGoodAddress, - Msg: []byte("{}"), - }, - expErr: true, - }, - "empty authority": { - src: MsgSudoContract{ - Contract: anotherGoodAddress, - Msg: []byte("{}"), - }, - expErr: true, - }, - "bad contract addr": { - src: MsgSudoContract{ - Authority: goodAddress, - Contract: badAddress, - Msg: []byte("{}"), - }, - expErr: true, - }, - "empty contract addr": { - src: MsgSudoContract{ - Authority: goodAddress, - Msg: []byte("{}"), - }, - expErr: true, - }, - "non json sudoMsg": { - src: MsgSudoContract{ - Authority: goodAddress, - Contract: anotherGoodAddress, - Msg: []byte("invalid json"), - }, - expErr: true, - }, - "empty sudoMsg": { - src: MsgSudoContract{ - Authority: goodAddress, - Contract: anotherGoodAddress, - }, - expErr: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgStoreAndInstantiateContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHexUnsafe("012345") - require.NoError(t, err) - badAddress := bad.String() - // proper address size - goodAddress := sdk.AccAddress(make([]byte, 20)).String() - sdk.GetConfig().SetAddressVerifier(VerifyAddressLen()) - - cases := map[string]struct { - msg MsgStoreAndInstantiateContract - valid bool - }{ - "empty": { - msg: MsgStoreAndInstantiateContract{}, - valid: false, - }, - "correct minimal": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - }, - valid: true, - }, - "missing byte code": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - }, - valid: false, - }, - "missing label": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "label too long": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: strings.Repeat("food", 33), - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "bad sender minimal": { - msg: MsgStoreAndInstantiateContract{ - Authority: badAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "bad admin": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - Admin: badAddress, - }, - valid: false, - }, - "correct maximal": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(200)}}, - WASMByteCode: []byte("foo"), - InstantiatePermission: &AllowEverybody, - UnpinCode: true, - Admin: goodAddress, - Source: "http://source.com", - Builder: "builder", - CodeHash: []byte("{}"), - }, - valid: true, - }, - "invalid source": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - Admin: goodAddress, - Source: "source", - }, - valid: false, - }, - "empty builder": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - Admin: goodAddress, - Source: "http://source.com", - }, - valid: false, - }, - "empty code hash": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("{}"), - WASMByteCode: []byte("foo"), - Admin: goodAddress, - Source: "http://source.com", - Builder: "builder", - }, - valid: false, - }, - "negative funds": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte(`{"some": "data"}`), - // we cannot use sdk.NewCoin() constructors as they panic on creating invalid data (before we can test) - Funds: sdk.Coins{sdk.Coin{Denom: "foobar", Amount: sdk.NewInt(-200)}}, - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "non json init msg": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - Msg: []byte("invalid-json"), - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "empty init msg": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - Label: "foo", - WASMByteCode: []byte("foo"), - }, - valid: false, - }, - "invalid InstantiatePermission": { - msg: MsgStoreAndInstantiateContract{ - Authority: goodAddress, - WASMByteCode: []byte("foo"), - Label: "foo", - Msg: []byte(`{"some": "data"}`), - InstantiatePermission: &AccessConfig{Permission: AccessTypeOnlyAddress, Address: badAddress}, - }, - valid: false, - }, - } - - for name, tc := range cases { - t.Run(name, func(t *testing.T) { - err := tc.msg.ValidateBasic() - if tc.valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - } - }) - } -} diff --git a/x/wasm/types/types.go b/x/wasm/types/types.go deleted file mode 100644 index ffec304..0000000 --- a/x/wasm/types/types.go +++ /dev/null @@ -1,437 +0,0 @@ -package types - -import ( - "fmt" - "reflect" - - errorsmod "cosmossdk.io/errors" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/gogoproto/proto" -) - -const ( - defaultMemoryCacheSize uint32 = 100 // in MiB - defaultSmartQueryGasLimit uint64 = 3_000_000 - defaultContractDebugMode = false - - // ContractAddrLen defines a valid address length for contracts - ContractAddrLen = 32 - // SDKAddrLen defines a valid address length that was used in sdk address generation - SDKAddrLen = 20 -) - -func (m Model) ValidateBasic() error { - if len(m.Key) == 0 { - return errorsmod.Wrap(ErrEmpty, "key") - } - return nil -} - -func (c CodeInfo) ValidateBasic() error { - if len(c.CodeHash) == 0 { - return errorsmod.Wrap(ErrEmpty, "code hash") - } - if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { - return errorsmod.Wrap(err, "creator") - } - if err := c.InstantiateConfig.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "instantiate config") - } - return nil -} - -// NewCodeInfo fills a new CodeInfo struct -func NewCodeInfo(codeHash []byte, creator sdk.AccAddress, instantiatePermission AccessConfig) CodeInfo { - return CodeInfo{ - CodeHash: codeHash, - Creator: creator.String(), - InstantiateConfig: instantiatePermission, - } -} - -var AllCodeHistoryTypes = []ContractCodeHistoryOperationType{ContractCodeHistoryOperationTypeGenesis, ContractCodeHistoryOperationTypeInit, ContractCodeHistoryOperationTypeMigrate} - -// NewContractInfo creates a new instance of a given WASM contract info -func NewContractInfo(codeID uint64, creator, admin sdk.AccAddress, label string, createdAt *AbsoluteTxPosition) ContractInfo { - var adminAddr string - if !admin.Empty() { - adminAddr = admin.String() - } - return ContractInfo{ - CodeID: codeID, - Creator: creator.String(), - Admin: adminAddr, - Label: label, - Created: createdAt, - } -} - -// validatable is an optional interface that can be implemented by an ContractInfoExtension to enable validation -type validatable interface { - ValidateBasic() error -} - -// ValidateBasic does syntax checks on the data. If an extension is set and has the `ValidateBasic() error` method, then -// the method is called as well. It is recommend to implement `ValidateBasic` so that the data is verified in the setter -// but also in the genesis import process. -func (c *ContractInfo) ValidateBasic() error { - if c.CodeID == 0 { - return errorsmod.Wrap(ErrEmpty, "code id") - } - if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { - return errorsmod.Wrap(err, "creator") - } - if len(c.Admin) != 0 { - if _, err := sdk.AccAddressFromBech32(c.Admin); err != nil { - return errorsmod.Wrap(err, "admin") - } - } - if err := ValidateLabel(c.Label); err != nil { - return errorsmod.Wrap(err, "label") - } - if c.Extension == nil { - return nil - } - - e, ok := c.Extension.GetCachedValue().(validatable) - if !ok { - return nil - } - if err := e.ValidateBasic(); err != nil { - return errorsmod.Wrap(err, "extension") - } - return nil -} - -// SetExtension set new extension data. Calls `ValidateBasic() error` on non nil values when method is implemented by -// the extension. -func (c *ContractInfo) SetExtension(ext ContractInfoExtension) error { - if ext == nil { - c.Extension = nil - return nil - } - if e, ok := ext.(validatable); ok { - if err := e.ValidateBasic(); err != nil { - return err - } - } - codecAny, err := codectypes.NewAnyWithValue(ext) - if err != nil { - return errorsmod.Wrap(sdkerrors.ErrPackAny, err.Error()) - } - - c.Extension = codecAny - return nil -} - -// ReadExtension copies the extension value to the pointer passed as argument so that there is no need to cast -// For example with a custom extension of type `MyContractDetails` it will look as following: -// -// var d MyContractDetails -// if err := info.ReadExtension(&d); err != nil { -// return nil, errorsmod.Wrap(err, "extension") -// } -func (c *ContractInfo) ReadExtension(e ContractInfoExtension) error { - rv := reflect.ValueOf(e) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return errorsmod.Wrap(sdkerrors.ErrInvalidType, "not a pointer") - } - if c.Extension == nil { - return nil - } - - cached := c.Extension.GetCachedValue() - elem := reflect.ValueOf(cached).Elem() - if !elem.Type().AssignableTo(rv.Elem().Type()) { - return errorsmod.Wrapf(sdkerrors.ErrInvalidType, "extension is of type %s but argument of %s", elem.Type(), rv.Elem().Type()) - } - rv.Elem().Set(elem) - return nil -} - -func (c ContractInfo) InitialHistory(initMsg []byte) ContractCodeHistoryEntry { - return ContractCodeHistoryEntry{ - Operation: ContractCodeHistoryOperationTypeInit, - CodeID: c.CodeID, - Updated: c.Created, - Msg: initMsg, - } -} - -func (c *ContractInfo) AddMigration(ctx sdk.Context, codeID uint64, msg []byte) ContractCodeHistoryEntry { - h := ContractCodeHistoryEntry{ - Operation: ContractCodeHistoryOperationTypeMigrate, - CodeID: codeID, - Updated: NewAbsoluteTxPosition(ctx), - Msg: msg, - } - c.CodeID = codeID - return h -} - -// AdminAddr convert into sdk.AccAddress or nil when not set -func (c *ContractInfo) AdminAddr() sdk.AccAddress { - if c.Admin == "" { - return nil - } - admin, err := sdk.AccAddressFromBech32(c.Admin) - if err != nil { // should never happen - panic(err.Error()) - } - return admin -} - -// ContractInfoExtension defines the extension point for custom data to be stored with a contract info -type ContractInfoExtension interface { - proto.Message - String() string -} - -var _ codectypes.UnpackInterfacesMessage = &ContractInfo{} - -// UnpackInterfaces implements codectypes.UnpackInterfaces -func (c *ContractInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - var details ContractInfoExtension - if err := unpacker.UnpackAny(c.Extension, &details); err != nil { - return err - } - return codectypes.UnpackInterfaces(details, unpacker) -} - -// NewAbsoluteTxPosition gets a block position from the context -func NewAbsoluteTxPosition(ctx sdk.Context) *AbsoluteTxPosition { - // we must safely handle nil gas meters - var index uint64 - meter := ctx.BlockGasMeter() - if meter != nil { - index = meter.GasConsumed() - } - height := ctx.BlockHeight() - if height < 0 { - panic(fmt.Sprintf("unsupported height: %d", height)) - } - return &AbsoluteTxPosition{ - BlockHeight: uint64(height), - TxIndex: index, - } -} - -// LessThan can be used to sort -func (a *AbsoluteTxPosition) LessThan(b *AbsoluteTxPosition) bool { - if a == nil { - return true - } - if b == nil { - return false - } - return a.BlockHeight < b.BlockHeight || (a.BlockHeight == b.BlockHeight && a.TxIndex < b.TxIndex) -} - -// AbsoluteTxPositionLen number of elements in byte representation -const AbsoluteTxPositionLen = 16 - -// Bytes encodes the object into a 16 byte representation with big endian block height and tx index. -func (a *AbsoluteTxPosition) Bytes() []byte { - if a == nil { - panic("object must not be nil") - } - r := make([]byte, AbsoluteTxPositionLen) - copy(r[0:], sdk.Uint64ToBigEndian(a.BlockHeight)) - copy(r[8:], sdk.Uint64ToBigEndian(a.TxIndex)) - return r -} - -// ValidateBasic syntax checks -func (c ContractCodeHistoryEntry) ValidateBasic() error { - var found bool - for _, v := range AllCodeHistoryTypes { - if c.Operation == v { - found = true - break - } - } - if !found { - return ErrInvalid.Wrap("operation") - } - if c.CodeID == 0 { - return ErrEmpty.Wrap("code id") - } - if c.Updated == nil { - return ErrEmpty.Wrap("updated") - } - return errorsmod.Wrap(c.Msg.ValidateBasic(), "msg") -} - -// NewEnv initializes the environment for a contract instance -func NewEnv(ctx sdk.Context, contractAddr sdk.AccAddress) wasmvmtypes.Env { - // safety checks before casting below - if ctx.BlockHeight() < 0 { - panic("Block height must never be negative") - } - nano := ctx.BlockTime().UnixNano() - if nano < 1 { - panic("Block (unix) time must never be empty or negative ") - } - - env := wasmvmtypes.Env{ - Block: wasmvmtypes.BlockInfo{ - Height: uint64(ctx.BlockHeight()), - Time: uint64(nano), - ChainID: ctx.ChainID(), - }, - Contract: wasmvmtypes.ContractInfo{ - Address: contractAddr.String(), - }, - } - if txCounter, ok := TXCounter(ctx); ok { - env.Transaction = &wasmvmtypes.TransactionInfo{Index: txCounter} - } - return env -} - -// NewInfo initializes the MessageInfo for a contract instance -func NewInfo(creator sdk.AccAddress, deposit sdk.Coins) wasmvmtypes.MessageInfo { - return wasmvmtypes.MessageInfo{ - Sender: creator.String(), - Funds: NewWasmCoins(deposit), - } -} - -// NewWasmCoins translates between Cosmos SDK coins and Wasm coins -func NewWasmCoins(cosmosCoins sdk.Coins) (wasmCoins []wasmvmtypes.Coin) { - for _, coin := range cosmosCoins { - wasmCoin := wasmvmtypes.Coin{ - Denom: coin.Denom, - Amount: coin.Amount.String(), - } - wasmCoins = append(wasmCoins, wasmCoin) - } - return wasmCoins -} - -// WasmConfig is the extra config required for wasm -type WasmConfig struct { - // SimulationGasLimit is the max gas to be used in a tx simulation call. - // When not set the consensus max block gas is used instead - SimulationGasLimit *uint64 `mapstructure:"simulation_gas_limit"` - // SmartQueryGasLimit is the max gas to be used in a smart query contract call - SmartQueryGasLimit uint64 `mapstructure:"query_gas_limit"` - // MemoryCacheSize in MiB not bytes - MemoryCacheSize uint32 `mapstructure:"memory_cache_size"` - // ContractDebugMode log what contract print - ContractDebugMode bool -} - -// DefaultWasmConfig returns the default settings for WasmConfig -func DefaultWasmConfig() WasmConfig { - return WasmConfig{ - SmartQueryGasLimit: defaultSmartQueryGasLimit, - MemoryCacheSize: defaultMemoryCacheSize, - ContractDebugMode: defaultContractDebugMode, - } -} - -// DefaultConfigTemplate toml snippet with default values for app.toml -func DefaultConfigTemplate() string { - return ConfigTemplate(DefaultWasmConfig()) -} - -// ConfigTemplate toml snippet for app.toml -func ConfigTemplate(c WasmConfig) string { - simGasLimit := `# simulation_gas_limit =` - if c.SimulationGasLimit != nil { - simGasLimit = fmt.Sprintf(`simulation_gas_limit = %d`, *c.SimulationGasLimit) - } - - return fmt.Sprintf(` -[wasm] -# Smart query gas limit is the max gas to be used in a smart query contract call -query_gas_limit = %d - -# in-memory cache for Wasm contracts. Set to 0 to disable. -# The value is in MiB not bytes -memory_cache_size = %d - -# Simulation gas limit is the max gas to be used in a tx simulation call. -# When not set the consensus max block gas is used instead -%s -`, c.SmartQueryGasLimit, c.MemoryCacheSize, simGasLimit) -} - -// VerifyAddressLen ensures that the address matches the expected length -func VerifyAddressLen() func(addr []byte) error { - return func(addr []byte) error { - if len(addr) != ContractAddrLen && len(addr) != SDKAddrLen { - return sdkerrors.ErrInvalidAddress - } - return nil - } -} - -// IsSubset will return true if the caller is the same as the superset, -// or if the caller is more restrictive than the superset. -func (a AccessType) IsSubset(superSet AccessType) bool { - switch superSet { - case AccessTypeEverybody: - // Everything is a subset of this - return a != AccessTypeUnspecified - case AccessTypeNobody: - // Only an exact match is a subset of this - return a == AccessTypeNobody - case AccessTypeOnlyAddress, AccessTypeAnyOfAddresses: - // Nobody or address(es) - return a == AccessTypeNobody || a == AccessTypeOnlyAddress || a == AccessTypeAnyOfAddresses - default: - return false - } -} - -// IsSubset will return true if the caller is the same as the superset, -// or if the caller is more restrictive than the superset. -func (a AccessConfig) IsSubset(superSet AccessConfig) bool { - switch superSet.Permission { - case AccessTypeOnlyAddress: - // An exact match or nobody - return a.Permission == AccessTypeNobody || (a.Permission == AccessTypeOnlyAddress && a.Address == superSet.Address) || - (a.Permission == AccessTypeAnyOfAddresses && isSubset([]string{superSet.Address}, a.Addresses)) - case AccessTypeAnyOfAddresses: - // An exact match or nobody - return a.Permission == AccessTypeNobody || (a.Permission == AccessTypeOnlyAddress && isSubset(superSet.Addresses, []string{a.Address})) || - a.Permission == AccessTypeAnyOfAddresses && isSubset(superSet.Addresses, a.Addresses) - case AccessTypeUnspecified: - return false - default: - return a.Permission.IsSubset(superSet.Permission) - } -} - -// return true when all elements in sub are also part of super -func isSubset(super, sub []string) bool { - if len(sub) == 0 { - return true - } - var matches int - for _, o := range sub { - for _, s := range super { - if o == s { - matches++ - break - } - } - } - return matches == len(sub) -} - -// AllAuthorizedAddresses returns the list of authorized addresses. Can be empty. -func (a AccessConfig) AllAuthorizedAddresses() []string { - switch a.Permission { - case AccessTypeAnyOfAddresses: - return a.Addresses - case AccessTypeOnlyAddress: - return []string{a.Address} - } - return []string{} -} diff --git a/x/wasm/types/types.pb.go b/x/wasm/types/types.pb.go deleted file mode 100644 index 2336b67..0000000 --- a/x/wasm/types/types.pb.go +++ /dev/null @@ -1,2548 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmwasm/wasm/v1/types.proto - -package types - -import ( - bytes "bytes" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - github_com_cometbft_cometbft_libs_bytes "github.com/cometbft/cometbft/libs/bytes" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - _ "github.com/cosmos/cosmos-sdk/types/tx/amino" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/cosmos/gogoproto/proto" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = proto.Marshal - _ = fmt.Errorf - _ = 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 - -// AccessType permission types -type AccessType int32 - -const ( - // AccessTypeUnspecified placeholder for empty value - AccessTypeUnspecified AccessType = 0 - // AccessTypeNobody forbidden - AccessTypeNobody AccessType = 1 - // AccessTypeOnlyAddress restricted to a single address - // Deprecated: use AccessTypeAnyOfAddresses instead - AccessTypeOnlyAddress AccessType = 2 - // AccessTypeEverybody unrestricted - AccessTypeEverybody AccessType = 3 - // AccessTypeAnyOfAddresses allow any of the addresses - AccessTypeAnyOfAddresses AccessType = 4 -) - -var AccessType_name = map[int32]string{ - 0: "ACCESS_TYPE_UNSPECIFIED", - 1: "ACCESS_TYPE_NOBODY", - 2: "ACCESS_TYPE_ONLY_ADDRESS", - 3: "ACCESS_TYPE_EVERYBODY", - 4: "ACCESS_TYPE_ANY_OF_ADDRESSES", -} - -var AccessType_value = map[string]int32{ - "ACCESS_TYPE_UNSPECIFIED": 0, - "ACCESS_TYPE_NOBODY": 1, - "ACCESS_TYPE_ONLY_ADDRESS": 2, - "ACCESS_TYPE_EVERYBODY": 3, - "ACCESS_TYPE_ANY_OF_ADDRESSES": 4, -} - -func (AccessType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{0} -} - -// ContractCodeHistoryOperationType actions that caused a code change -type ContractCodeHistoryOperationType int32 - -const ( - // ContractCodeHistoryOperationTypeUnspecified placeholder for empty value - ContractCodeHistoryOperationTypeUnspecified ContractCodeHistoryOperationType = 0 - // ContractCodeHistoryOperationTypeInit on chain contract instantiation - ContractCodeHistoryOperationTypeInit ContractCodeHistoryOperationType = 1 - // ContractCodeHistoryOperationTypeMigrate code migration - ContractCodeHistoryOperationTypeMigrate ContractCodeHistoryOperationType = 2 - // ContractCodeHistoryOperationTypeGenesis based on genesis data - ContractCodeHistoryOperationTypeGenesis ContractCodeHistoryOperationType = 3 -) - -var ContractCodeHistoryOperationType_name = map[int32]string{ - 0: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED", - 1: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT", - 2: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE", - 3: "CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS", -} - -var ContractCodeHistoryOperationType_value = map[string]int32{ - "CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED": 0, - "CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT": 1, - "CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE": 2, - "CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS": 3, -} - -func (x ContractCodeHistoryOperationType) String() string { - return proto.EnumName(ContractCodeHistoryOperationType_name, int32(x)) -} - -func (ContractCodeHistoryOperationType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{1} -} - -// AccessTypeParam -type AccessTypeParam struct { - Value AccessType `protobuf:"varint,1,opt,name=value,proto3,enum=cosmwasm.wasm.v1.AccessType" json:"value,omitempty" yaml:"value"` -} - -func (m *AccessTypeParam) Reset() { *m = AccessTypeParam{} } -func (m *AccessTypeParam) String() string { return proto.CompactTextString(m) } -func (*AccessTypeParam) ProtoMessage() {} -func (*AccessTypeParam) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{0} -} - -func (m *AccessTypeParam) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AccessTypeParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccessTypeParam.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 *AccessTypeParam) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccessTypeParam.Merge(m, src) -} - -func (m *AccessTypeParam) XXX_Size() int { - return m.Size() -} - -func (m *AccessTypeParam) XXX_DiscardUnknown() { - xxx_messageInfo_AccessTypeParam.DiscardUnknown(m) -} - -var xxx_messageInfo_AccessTypeParam proto.InternalMessageInfo - -// AccessConfig access control type. -type AccessConfig struct { - Permission AccessType `protobuf:"varint,1,opt,name=permission,proto3,enum=cosmwasm.wasm.v1.AccessType" json:"permission,omitempty" yaml:"permission"` - // Address - // Deprecated: replaced by addresses - Address string `protobuf:"bytes,2,opt,name=address,proto3" json:"address,omitempty" yaml:"address"` - Addresses []string `protobuf:"bytes,3,rep,name=addresses,proto3" json:"addresses,omitempty" yaml:"addresses"` -} - -func (m *AccessConfig) Reset() { *m = AccessConfig{} } -func (m *AccessConfig) String() string { return proto.CompactTextString(m) } -func (*AccessConfig) ProtoMessage() {} -func (*AccessConfig) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{1} -} - -func (m *AccessConfig) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AccessConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AccessConfig.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 *AccessConfig) XXX_Merge(src proto.Message) { - xxx_messageInfo_AccessConfig.Merge(m, src) -} - -func (m *AccessConfig) XXX_Size() int { - return m.Size() -} - -func (m *AccessConfig) XXX_DiscardUnknown() { - xxx_messageInfo_AccessConfig.DiscardUnknown(m) -} - -var xxx_messageInfo_AccessConfig proto.InternalMessageInfo - -// Params defines the set of wasm parameters. -type Params struct { - CodeUploadAccess AccessConfig `protobuf:"bytes,1,opt,name=code_upload_access,json=codeUploadAccess,proto3" json:"code_upload_access" yaml:"code_upload_access"` - InstantiateDefaultPermission AccessType `protobuf:"varint,2,opt,name=instantiate_default_permission,json=instantiateDefaultPermission,proto3,enum=cosmwasm.wasm.v1.AccessType" json:"instantiate_default_permission,omitempty" yaml:"instantiate_default_permission"` -} - -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} -func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{2} -} - -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 - -// CodeInfo is data for the uploaded contract WASM code -type CodeInfo struct { - // CodeHash is the unique identifier created by wasmvm - CodeHash []byte `protobuf:"bytes,1,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` - // Creator address who initially stored the code - Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"` - // InstantiateConfig access control to apply on contract creation, optional - InstantiateConfig AccessConfig `protobuf:"bytes,5,opt,name=instantiate_config,json=instantiateConfig,proto3" json:"instantiate_config"` -} - -func (m *CodeInfo) Reset() { *m = CodeInfo{} } -func (m *CodeInfo) String() string { return proto.CompactTextString(m) } -func (*CodeInfo) ProtoMessage() {} -func (*CodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{3} -} - -func (m *CodeInfo) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *CodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CodeInfo.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 *CodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_CodeInfo.Merge(m, src) -} - -func (m *CodeInfo) XXX_Size() int { - return m.Size() -} - -func (m *CodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_CodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_CodeInfo proto.InternalMessageInfo - -// ContractInfo stores a WASM contract instance -type ContractInfo struct { - // CodeID is the reference to the stored Wasm code - CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Creator address who initially instantiated the contract - Creator string `protobuf:"bytes,2,opt,name=creator,proto3" json:"creator,omitempty"` - // Admin is an optional address that can execute migrations - Admin string `protobuf:"bytes,3,opt,name=admin,proto3" json:"admin,omitempty"` - // Label is optional metadata to be stored with a contract instance. - Label string `protobuf:"bytes,4,opt,name=label,proto3" json:"label,omitempty"` - // Created Tx position when the contract was instantiated. - Created *AbsoluteTxPosition `protobuf:"bytes,5,opt,name=created,proto3" json:"created,omitempty"` - IBCPortID string `protobuf:"bytes,6,opt,name=ibc_port_id,json=ibcPortId,proto3" json:"ibc_port_id,omitempty"` - // Extension is an extension point to store custom metadata within the - // persistence model. - Extension *types.Any `protobuf:"bytes,7,opt,name=extension,proto3" json:"extension,omitempty"` -} - -func (m *ContractInfo) Reset() { *m = ContractInfo{} } -func (m *ContractInfo) String() string { return proto.CompactTextString(m) } -func (*ContractInfo) ProtoMessage() {} -func (*ContractInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{4} -} - -func (m *ContractInfo) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractInfo.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 *ContractInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractInfo.Merge(m, src) -} - -func (m *ContractInfo) XXX_Size() int { - return m.Size() -} - -func (m *ContractInfo) XXX_DiscardUnknown() { - xxx_messageInfo_ContractInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractInfo proto.InternalMessageInfo - -// ContractCodeHistoryEntry metadata to a contract. -type ContractCodeHistoryEntry struct { - Operation ContractCodeHistoryOperationType `protobuf:"varint,1,opt,name=operation,proto3,enum=cosmwasm.wasm.v1.ContractCodeHistoryOperationType" json:"operation,omitempty"` - // CodeID is the reference to the stored WASM code - CodeID uint64 `protobuf:"varint,2,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` - // Updated Tx position when the operation was executed. - Updated *AbsoluteTxPosition `protobuf:"bytes,3,opt,name=updated,proto3" json:"updated,omitempty"` - Msg RawContractMessage `protobuf:"bytes,4,opt,name=msg,proto3,casttype=RawContractMessage" json:"msg,omitempty"` -} - -func (m *ContractCodeHistoryEntry) Reset() { *m = ContractCodeHistoryEntry{} } -func (m *ContractCodeHistoryEntry) String() string { return proto.CompactTextString(m) } -func (*ContractCodeHistoryEntry) ProtoMessage() {} -func (*ContractCodeHistoryEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{5} -} - -func (m *ContractCodeHistoryEntry) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *ContractCodeHistoryEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_ContractCodeHistoryEntry.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 *ContractCodeHistoryEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_ContractCodeHistoryEntry.Merge(m, src) -} - -func (m *ContractCodeHistoryEntry) XXX_Size() int { - return m.Size() -} - -func (m *ContractCodeHistoryEntry) XXX_DiscardUnknown() { - xxx_messageInfo_ContractCodeHistoryEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_ContractCodeHistoryEntry proto.InternalMessageInfo - -// AbsoluteTxPosition is a unique transaction position that allows for global -// ordering of transactions. -type AbsoluteTxPosition struct { - // BlockHeight is the block the contract was created at - BlockHeight uint64 `protobuf:"varint,1,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` - // TxIndex is a monotonic counter within the block (actual transaction index, - // or gas consumed) - TxIndex uint64 `protobuf:"varint,2,opt,name=tx_index,json=txIndex,proto3" json:"tx_index,omitempty"` -} - -func (m *AbsoluteTxPosition) Reset() { *m = AbsoluteTxPosition{} } -func (m *AbsoluteTxPosition) String() string { return proto.CompactTextString(m) } -func (*AbsoluteTxPosition) ProtoMessage() {} -func (*AbsoluteTxPosition) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{6} -} - -func (m *AbsoluteTxPosition) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *AbsoluteTxPosition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_AbsoluteTxPosition.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 *AbsoluteTxPosition) XXX_Merge(src proto.Message) { - xxx_messageInfo_AbsoluteTxPosition.Merge(m, src) -} - -func (m *AbsoluteTxPosition) XXX_Size() int { - return m.Size() -} - -func (m *AbsoluteTxPosition) XXX_DiscardUnknown() { - xxx_messageInfo_AbsoluteTxPosition.DiscardUnknown(m) -} - -var xxx_messageInfo_AbsoluteTxPosition proto.InternalMessageInfo - -// Model is a struct that holds a KV pair -type Model struct { - // hex-encode key to read it better (this is often ascii) - Key github_com_cometbft_cometbft_libs_bytes.HexBytes `protobuf:"bytes,1,opt,name=key,proto3,casttype=github.com/cometbft/cometbft/libs/bytes.HexBytes" json:"key,omitempty"` - // base64-encode raw value - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` -} - -func (m *Model) Reset() { *m = Model{} } -func (m *Model) String() string { return proto.CompactTextString(m) } -func (*Model) ProtoMessage() {} -func (*Model) Descriptor() ([]byte, []int) { - return fileDescriptor_e6155d98fa173e02, []int{7} -} - -func (m *Model) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Model) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Model.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 *Model) XXX_Merge(src proto.Message) { - xxx_messageInfo_Model.Merge(m, src) -} - -func (m *Model) XXX_Size() int { - return m.Size() -} - -func (m *Model) XXX_DiscardUnknown() { - xxx_messageInfo_Model.DiscardUnknown(m) -} - -var xxx_messageInfo_Model proto.InternalMessageInfo - -func init() { - proto.RegisterEnum("cosmwasm.wasm.v1.AccessType", AccessType_name, AccessType_value) - proto.RegisterEnum("cosmwasm.wasm.v1.ContractCodeHistoryOperationType", ContractCodeHistoryOperationType_name, ContractCodeHistoryOperationType_value) - proto.RegisterType((*AccessTypeParam)(nil), "cosmwasm.wasm.v1.AccessTypeParam") - proto.RegisterType((*AccessConfig)(nil), "cosmwasm.wasm.v1.AccessConfig") - proto.RegisterType((*Params)(nil), "cosmwasm.wasm.v1.Params") - proto.RegisterType((*CodeInfo)(nil), "cosmwasm.wasm.v1.CodeInfo") - proto.RegisterType((*ContractInfo)(nil), "cosmwasm.wasm.v1.ContractInfo") - proto.RegisterType((*ContractCodeHistoryEntry)(nil), "cosmwasm.wasm.v1.ContractCodeHistoryEntry") - proto.RegisterType((*AbsoluteTxPosition)(nil), "cosmwasm.wasm.v1.AbsoluteTxPosition") - proto.RegisterType((*Model)(nil), "cosmwasm.wasm.v1.Model") -} - -func init() { proto.RegisterFile("cosmwasm/wasm/v1/types.proto", fileDescriptor_e6155d98fa173e02) } - -var fileDescriptor_e6155d98fa173e02 = []byte{ - // 1205 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x56, 0xcd, 0x8f, 0xdb, 0x44, - 0x14, 0x8f, 0x93, 0xec, 0x47, 0xa6, 0x4b, 0x71, 0x87, 0x2d, 0xcd, 0x86, 0x55, 0x12, 0x4c, 0x29, - 0xdb, 0x6d, 0x37, 0x69, 0x17, 0x04, 0x52, 0x0f, 0x95, 0xf2, 0xe1, 0x76, 0x5d, 0xb1, 0x71, 0x34, - 0x49, 0x81, 0x45, 0x2a, 0x96, 0x63, 0x4f, 0xb2, 0x56, 0x13, 0x4f, 0xe4, 0x99, 0x6c, 0xe3, 0xff, - 0x00, 0x45, 0x42, 0xe2, 0xc0, 0x81, 0x4b, 0x24, 0x24, 0x10, 0x94, 0x1b, 0x07, 0xfe, 0x88, 0x0a, - 0x24, 0xd4, 0x23, 0xa7, 0x08, 0xb6, 0x07, 0x38, 0xe7, 0x58, 0x2e, 0xc8, 0x33, 0x49, 0x6d, 0xfa, - 0xb5, 0xe1, 0x62, 0xcd, 0xbc, 0xf7, 0x7e, 0xbf, 0xf7, 0xde, 0x6f, 0x66, 0x9e, 0x0c, 0x36, 0x2d, - 0x42, 0x7b, 0xf7, 0x4c, 0xda, 0x2b, 0xf2, 0xcf, 0xd1, 0xd5, 0x22, 0xf3, 0xfb, 0x98, 0x16, 0xfa, - 0x1e, 0x61, 0x04, 0xca, 0x73, 0x6f, 0x81, 0x7f, 0x8e, 0xae, 0x66, 0x36, 0x02, 0x0b, 0xa1, 0x06, - 0xf7, 0x17, 0xc5, 0x46, 0x04, 0x67, 0xd6, 0x3b, 0xa4, 0x43, 0x84, 0x3d, 0x58, 0xcd, 0xac, 0x1b, - 0x1d, 0x42, 0x3a, 0x5d, 0x5c, 0xe4, 0xbb, 0xd6, 0xa0, 0x5d, 0x34, 0x5d, 0x7f, 0xe6, 0x3a, 0x63, - 0xf6, 0x1c, 0x97, 0x14, 0xf9, 0x57, 0x98, 0x94, 0x3b, 0xe0, 0xd5, 0x92, 0x65, 0x61, 0x4a, 0x9b, - 0x7e, 0x1f, 0xd7, 0x4d, 0xcf, 0xec, 0xc1, 0x2a, 0x58, 0x3a, 0x32, 0xbb, 0x03, 0x9c, 0x96, 0xf2, - 0xd2, 0xd6, 0xe9, 0xdd, 0xcd, 0xc2, 0xd3, 0x35, 0x15, 0x42, 0x44, 0x59, 0x9e, 0x4e, 0x72, 0x6b, - 0xbe, 0xd9, 0xeb, 0x5e, 0x53, 0x38, 0x48, 0x41, 0x02, 0x7c, 0x2d, 0xf9, 0xf5, 0x37, 0x39, 0x49, - 0xf9, 0x55, 0x02, 0x6b, 0x22, 0xba, 0x42, 0xdc, 0xb6, 0xd3, 0x81, 0x0d, 0x00, 0xfa, 0xd8, 0xeb, - 0x39, 0x94, 0x3a, 0xc4, 0x5d, 0x28, 0xc3, 0xd9, 0xe9, 0x24, 0x77, 0x46, 0x64, 0x08, 0x91, 0x0a, - 0x8a, 0xd0, 0xc0, 0xcb, 0x60, 0xc5, 0xb4, 0x6d, 0x0f, 0x53, 0x9a, 0x8e, 0xe7, 0xa5, 0xad, 0x54, - 0x19, 0x4e, 0x27, 0xb9, 0xd3, 0x02, 0x33, 0x73, 0x28, 0x68, 0x1e, 0x02, 0x77, 0x41, 0x6a, 0xb6, - 0xc4, 0x34, 0x9d, 0xc8, 0x27, 0xb6, 0x52, 0xe5, 0xf5, 0xe9, 0x24, 0x27, 0xff, 0x27, 0x1e, 0x53, - 0x05, 0x85, 0x61, 0xb3, 0x6e, 0xbe, 0x8a, 0x83, 0x65, 0xae, 0x11, 0x85, 0x0c, 0x40, 0x8b, 0xd8, - 0xd8, 0x18, 0xf4, 0xbb, 0xc4, 0xb4, 0x0d, 0x93, 0xd7, 0xcb, 0xfb, 0x39, 0xb5, 0x9b, 0x7d, 0x51, - 0x3f, 0x42, 0x83, 0xf2, 0x85, 0x07, 0x93, 0x5c, 0x6c, 0x3a, 0xc9, 0x6d, 0x88, 0x8c, 0xcf, 0xf2, - 0x28, 0xf7, 0xff, 0xfa, 0x69, 0x5b, 0x42, 0x72, 0xe0, 0xb9, 0xcd, 0x1d, 0x02, 0x0f, 0xbf, 0x90, - 0x40, 0xd6, 0x71, 0x29, 0x33, 0x5d, 0xe6, 0x98, 0x0c, 0x1b, 0x36, 0x6e, 0x9b, 0x83, 0x2e, 0x33, - 0x22, 0x92, 0xc6, 0x17, 0x90, 0xf4, 0xe2, 0x74, 0x92, 0x7b, 0x5b, 0x24, 0x7f, 0x39, 0x9b, 0x82, - 0x36, 0x23, 0x01, 0x55, 0xe1, 0xaf, 0x3f, 0x71, 0x73, 0x59, 0x62, 0xca, 0x0f, 0x12, 0x58, 0xad, - 0x10, 0x1b, 0x6b, 0x6e, 0x9b, 0xc0, 0x37, 0x40, 0x8a, 0x37, 0x74, 0x68, 0xd2, 0x43, 0xae, 0xc7, - 0x1a, 0x5a, 0x0d, 0x0c, 0x7b, 0x26, 0x3d, 0x84, 0x69, 0xb0, 0x62, 0x79, 0xd8, 0x64, 0xc4, 0x13, - 0x07, 0x85, 0xe6, 0x5b, 0xf8, 0x09, 0x80, 0xd1, 0x52, 0x2c, 0xae, 0x54, 0x7a, 0x69, 0x21, 0x3d, - 0x53, 0x81, 0x9e, 0x42, 0xb2, 0x33, 0x11, 0x12, 0xe1, 0xbd, 0x95, 0x5c, 0x4d, 0xc8, 0xc9, 0x5b, - 0xc9, 0xd5, 0xa4, 0xbc, 0xa4, 0xfc, 0x16, 0x07, 0x6b, 0x15, 0xe2, 0x32, 0xcf, 0xb4, 0x18, 0xaf, - 0xf6, 0x2d, 0xb0, 0xc2, 0xab, 0x75, 0x6c, 0x5e, 0x6b, 0xb2, 0x0c, 0x8e, 0x27, 0xb9, 0x65, 0xde, - 0x4c, 0x15, 0x2d, 0x07, 0x2e, 0xcd, 0x7e, 0x49, 0xd5, 0xeb, 0x60, 0xc9, 0xb4, 0x7b, 0x8e, 0x9b, - 0x4e, 0x70, 0xbb, 0xd8, 0x04, 0xd6, 0xae, 0xd9, 0xc2, 0xdd, 0x74, 0x52, 0x58, 0xf9, 0x06, 0x5e, - 0x9f, 0xb1, 0x60, 0x7b, 0xd6, 0xd6, 0xf9, 0xe7, 0xb4, 0xd5, 0xa2, 0xa4, 0x3b, 0x60, 0xb8, 0x39, - 0xac, 0x13, 0xea, 0x30, 0x87, 0xb8, 0x68, 0x0e, 0x82, 0x3b, 0xe0, 0x94, 0xd3, 0xb2, 0x8c, 0x3e, - 0xf1, 0x58, 0x50, 0xee, 0x32, 0xbf, 0xe8, 0xaf, 0x1c, 0x4f, 0x72, 0x29, 0xad, 0x5c, 0xa9, 0x13, - 0x8f, 0x69, 0x55, 0x94, 0x72, 0x5a, 0x16, 0x5f, 0xda, 0xf0, 0x33, 0x90, 0xc2, 0x43, 0x86, 0x5d, - 0x7e, 0x29, 0x56, 0x78, 0xc2, 0xf5, 0x82, 0x18, 0x0d, 0x85, 0xf9, 0x68, 0x28, 0x94, 0x5c, 0xbf, - 0xbc, 0xfd, 0xcb, 0xcf, 0x3b, 0x17, 0x9e, 0xa9, 0x24, 0xaa, 0x92, 0x3a, 0xe7, 0x41, 0x21, 0xe5, - 0xb5, 0xe4, 0xdf, 0xc1, 0x8b, 0xf8, 0x47, 0x02, 0xe9, 0x79, 0x68, 0xa0, 0xda, 0x9e, 0x43, 0x19, - 0xf1, 0x7c, 0xd5, 0x65, 0x9e, 0x0f, 0xeb, 0x20, 0x45, 0xfa, 0xd8, 0x33, 0x59, 0xf8, 0xd4, 0x77, - 0x0b, 0x2f, 0xcc, 0x14, 0x81, 0xeb, 0x73, 0x54, 0x70, 0x5b, 0x51, 0x48, 0x12, 0x3d, 0xae, 0xf8, - 0x0b, 0x8f, 0xeb, 0x3a, 0x58, 0x19, 0xf4, 0x6d, 0x2e, 0x74, 0xe2, 0xff, 0x08, 0x3d, 0x03, 0xc1, - 0x2d, 0x90, 0xe8, 0xd1, 0x0e, 0x3f, 0xbc, 0xb5, 0xf2, 0xeb, 0x8f, 0x27, 0x39, 0x88, 0xcc, 0x7b, - 0xf3, 0x2a, 0xf7, 0x31, 0xa5, 0x66, 0x07, 0xa3, 0x20, 0x44, 0x41, 0x00, 0x3e, 0x4b, 0x04, 0xdf, - 0x04, 0x6b, 0xad, 0x2e, 0xb1, 0xee, 0x1a, 0x87, 0xd8, 0xe9, 0x1c, 0x32, 0x71, 0xb1, 0xd0, 0x29, - 0x6e, 0xdb, 0xe3, 0x26, 0xb8, 0x01, 0x56, 0xd9, 0xd0, 0x70, 0x5c, 0x1b, 0x0f, 0x45, 0x23, 0x68, - 0x85, 0x0d, 0xb5, 0x60, 0xab, 0x60, 0xb0, 0xb4, 0x4f, 0x6c, 0xdc, 0x85, 0x37, 0x40, 0xe2, 0x2e, - 0xf6, 0xc5, 0x13, 0x2a, 0xbf, 0xf7, 0x78, 0x92, 0xbb, 0xd2, 0x71, 0xd8, 0xe1, 0xa0, 0x55, 0xb0, - 0x48, 0xaf, 0x68, 0x91, 0x1e, 0x66, 0xad, 0x36, 0x0b, 0x17, 0x5d, 0xa7, 0x45, 0x8b, 0x2d, 0x9f, - 0x61, 0x5a, 0xd8, 0xc3, 0xc3, 0x72, 0xb0, 0x40, 0x01, 0x41, 0x70, 0x1b, 0xc5, 0x38, 0x8f, 0xf3, - 0xc7, 0x28, 0x36, 0xdb, 0x3f, 0xc6, 0x01, 0x08, 0x27, 0x02, 0x7c, 0x1f, 0x9c, 0x2b, 0x55, 0x2a, - 0x6a, 0xa3, 0x61, 0x34, 0x0f, 0xea, 0xaa, 0x71, 0xbb, 0xd6, 0xa8, 0xab, 0x15, 0xed, 0x86, 0xa6, - 0x56, 0xe5, 0x58, 0x66, 0x63, 0x34, 0xce, 0x9f, 0x0d, 0x83, 0x6f, 0xbb, 0xb4, 0x8f, 0x2d, 0xa7, - 0xed, 0x60, 0x1b, 0x5e, 0x06, 0x30, 0x8a, 0xab, 0xe9, 0x65, 0xbd, 0x7a, 0x20, 0x4b, 0x99, 0xf5, - 0xd1, 0x38, 0x2f, 0x87, 0x90, 0x1a, 0x69, 0x11, 0xdb, 0x87, 0x1f, 0x80, 0x74, 0x34, 0x5a, 0xaf, - 0x7d, 0x78, 0x60, 0x94, 0xaa, 0x55, 0xa4, 0x36, 0x1a, 0x72, 0xfc, 0xe9, 0x34, 0xba, 0xdb, 0xf5, - 0x4b, 0x4f, 0x46, 0xf6, 0xd9, 0x28, 0x50, 0xfd, 0x48, 0x45, 0x07, 0x3c, 0x53, 0x22, 0x73, 0x6e, - 0x34, 0xce, 0xbf, 0x16, 0xa2, 0xd4, 0x23, 0xec, 0xf9, 0x3c, 0xd9, 0x75, 0xb0, 0x19, 0xc5, 0x94, - 0x6a, 0x07, 0x86, 0x7e, 0x63, 0x9e, 0x4e, 0x6d, 0xc8, 0xc9, 0xcc, 0xe6, 0x68, 0x9c, 0x4f, 0x87, - 0xd0, 0x92, 0xeb, 0xeb, 0xed, 0xd2, 0x7c, 0xe4, 0x67, 0x56, 0x3f, 0xff, 0x36, 0x1b, 0xbb, 0xff, - 0x5d, 0x36, 0xb6, 0xfd, 0x7d, 0x02, 0xe4, 0x4f, 0xba, 0xa5, 0x10, 0x83, 0x2b, 0x15, 0xbd, 0xd6, - 0x44, 0xa5, 0x4a, 0xd3, 0xa8, 0xe8, 0x55, 0xd5, 0xd8, 0xd3, 0x1a, 0x4d, 0x1d, 0x1d, 0x18, 0x7a, - 0x5d, 0x45, 0xa5, 0xa6, 0xa6, 0xd7, 0x9e, 0x27, 0x6d, 0x71, 0x34, 0xce, 0x5f, 0x3a, 0x89, 0x3b, - 0x2a, 0xf8, 0xc7, 0xe0, 0xe2, 0x42, 0x69, 0xb4, 0x9a, 0xd6, 0x94, 0xa5, 0xcc, 0xd6, 0x68, 0x9c, - 0x3f, 0x7f, 0x12, 0xbf, 0xe6, 0x3a, 0x0c, 0xde, 0x01, 0x97, 0x17, 0x22, 0xde, 0xd7, 0x6e, 0xa2, - 0x52, 0x53, 0x95, 0xe3, 0x99, 0x4b, 0xa3, 0x71, 0xfe, 0x9d, 0x93, 0xb8, 0xf7, 0x9d, 0x8e, 0x67, - 0x32, 0xbc, 0x30, 0xfd, 0x4d, 0xb5, 0xa6, 0x36, 0xb4, 0x86, 0x9c, 0x58, 0x8c, 0xfe, 0x26, 0x76, - 0x31, 0x75, 0x68, 0x26, 0x19, 0x1c, 0x56, 0x59, 0x7f, 0xf0, 0x67, 0x36, 0x76, 0xff, 0x38, 0x2b, - 0x3d, 0x38, 0xce, 0x4a, 0x0f, 0x8f, 0xb3, 0xd2, 0x1f, 0xc7, 0x59, 0xe9, 0xcb, 0x47, 0xd9, 0xd8, - 0xc3, 0x47, 0xd9, 0xd8, 0xef, 0x8f, 0xb2, 0xb1, 0x4f, 0x77, 0x22, 0x6f, 0x88, 0x61, 0xaf, 0xef, - 0x62, 0x76, 0x8f, 0x78, 0x77, 0xf9, 0x7a, 0xc7, 0x22, 0x1e, 0x2e, 0x0e, 0xc5, 0x7f, 0x19, 0xff, - 0x29, 0x6b, 0x2d, 0xf3, 0x49, 0xf9, 0xee, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xef, 0xa9, 0x45, - 0x98, 0xb5, 0x09, 0x00, 0x00, -} - -func (this *AccessTypeParam) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*AccessTypeParam) - if !ok { - that2, ok := that.(AccessTypeParam) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Value != that1.Value { - return false - } - return true -} - -func (this *AccessConfig) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*AccessConfig) - if !ok { - that2, ok := that.(AccessConfig) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Permission != that1.Permission { - return false - } - if this.Address != that1.Address { - return false - } - if len(this.Addresses) != len(that1.Addresses) { - return false - } - for i := range this.Addresses { - if this.Addresses[i] != that1.Addresses[i] { - return false - } - } - return true -} - -func (this *Params) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Params) - if !ok { - that2, ok := that.(Params) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !this.CodeUploadAccess.Equal(&that1.CodeUploadAccess) { - return false - } - if this.InstantiateDefaultPermission != that1.InstantiateDefaultPermission { - return false - } - return true -} - -func (this *CodeInfo) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*CodeInfo) - if !ok { - that2, ok := that.(CodeInfo) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !bytes.Equal(this.CodeHash, that1.CodeHash) { - return false - } - if this.Creator != that1.Creator { - return false - } - if !this.InstantiateConfig.Equal(&that1.InstantiateConfig) { - return false - } - return true -} - -func (this *ContractInfo) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ContractInfo) - if !ok { - that2, ok := that.(ContractInfo) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if this.Creator != that1.Creator { - return false - } - if this.Admin != that1.Admin { - return false - } - if this.Label != that1.Label { - return false - } - if !this.Created.Equal(that1.Created) { - return false - } - if this.IBCPortID != that1.IBCPortID { - return false - } - if !this.Extension.Equal(that1.Extension) { - return false - } - return true -} - -func (this *ContractCodeHistoryEntry) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*ContractCodeHistoryEntry) - if !ok { - that2, ok := that.(ContractCodeHistoryEntry) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.Operation != that1.Operation { - return false - } - if this.CodeID != that1.CodeID { - return false - } - if !this.Updated.Equal(that1.Updated) { - return false - } - if !bytes.Equal(this.Msg, that1.Msg) { - return false - } - return true -} - -func (this *AbsoluteTxPosition) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*AbsoluteTxPosition) - if !ok { - that2, ok := that.(AbsoluteTxPosition) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if this.BlockHeight != that1.BlockHeight { - return false - } - if this.TxIndex != that1.TxIndex { - return false - } - return true -} - -func (this *Model) Equal(that interface{}) bool { - if that == nil { - return this == nil - } - - that1, ok := that.(*Model) - if !ok { - that2, ok := that.(Model) - if ok { - that1 = &that2 - } else { - return false - } - } - if that1 == nil { - return this == nil - } else if this == nil { - return false - } - if !bytes.Equal(this.Key, that1.Key) { - return false - } - if !bytes.Equal(this.Value, that1.Value) { - return false - } - return true -} - -func (m *AccessTypeParam) 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 *AccessTypeParam) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccessTypeParam) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Value != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.Value)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *AccessConfig) 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 *AccessConfig) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AccessConfig) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Addresses) > 0 { - for iNdEx := len(m.Addresses) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Addresses[iNdEx]) - copy(dAtA[i:], m.Addresses[iNdEx]) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Addresses[iNdEx]))) - i-- - dAtA[i] = 0x1a - } - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0x12 - } - if m.Permission != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.Permission)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -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.InstantiateDefaultPermission != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.InstantiateDefaultPermission)) - i-- - dAtA[i] = 0x10 - } - { - size, err := m.CodeUploadAccess.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *CodeInfo) 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 *CodeInfo) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *CodeInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.InstantiateConfig.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0x12 - } - if len(m.CodeHash) > 0 { - i -= len(m.CodeHash) - copy(dAtA[i:], m.CodeHash) - i = encodeVarintTypes(dAtA, i, uint64(len(m.CodeHash))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *ContractInfo) 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 *ContractInfo) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Extension != nil { - { - size, err := m.Extension.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x3a - } - if len(m.IBCPortID) > 0 { - i -= len(m.IBCPortID) - copy(dAtA[i:], m.IBCPortID) - i = encodeVarintTypes(dAtA, i, uint64(len(m.IBCPortID))) - i-- - dAtA[i] = 0x32 - } - if m.Created != nil { - { - size, err := m.Created.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x2a - } - if len(m.Label) > 0 { - i -= len(m.Label) - copy(dAtA[i:], m.Label) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Label))) - i-- - dAtA[i] = 0x22 - } - if len(m.Admin) > 0 { - i -= len(m.Admin) - copy(dAtA[i:], m.Admin) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Admin))) - i-- - dAtA[i] = 0x1a - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0x12 - } - if m.CodeID != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *ContractCodeHistoryEntry) 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 *ContractCodeHistoryEntry) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *ContractCodeHistoryEntry) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Msg) > 0 { - i -= len(m.Msg) - copy(dAtA[i:], m.Msg) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Msg))) - i-- - dAtA[i] = 0x22 - } - if m.Updated != nil { - { - size, err := m.Updated.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - if m.CodeID != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.CodeID)) - i-- - dAtA[i] = 0x10 - } - if m.Operation != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.Operation)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *AbsoluteTxPosition) 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 *AbsoluteTxPosition) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AbsoluteTxPosition) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.TxIndex != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.TxIndex)) - i-- - dAtA[i] = 0x10 - } - if m.BlockHeight != 0 { - i = encodeVarintTypes(dAtA, i, uint64(m.BlockHeight)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *Model) 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 *Model) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Model) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Value) > 0 { - i -= len(m.Value) - copy(dAtA[i:], m.Value) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Value))) - i-- - dAtA[i] = 0x12 - } - if len(m.Key) > 0 { - i -= len(m.Key) - copy(dAtA[i:], m.Key) - i = encodeVarintTypes(dAtA, i, uint64(len(m.Key))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { - offset -= sovTypes(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *AccessTypeParam) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Value != 0 { - n += 1 + sovTypes(uint64(m.Value)) - } - return n -} - -func (m *AccessConfig) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Permission != 0 { - n += 1 + sovTypes(uint64(m.Permission)) - } - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - if len(m.Addresses) > 0 { - for _, s := range m.Addresses { - l = len(s) - n += 1 + l + sovTypes(uint64(l)) - } - } - return n -} - -func (m *Params) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.CodeUploadAccess.Size() - n += 1 + l + sovTypes(uint64(l)) - if m.InstantiateDefaultPermission != 0 { - n += 1 + sovTypes(uint64(m.InstantiateDefaultPermission)) - } - return n -} - -func (m *CodeInfo) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.CodeHash) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = m.InstantiateConfig.Size() - n += 1 + l + sovTypes(uint64(l)) - return n -} - -func (m *ContractInfo) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovTypes(uint64(m.CodeID)) - } - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - if m.Created != nil { - l = m.Created.Size() - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.IBCPortID) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - if m.Extension != nil { - l = m.Extension.Size() - n += 1 + l + sovTypes(uint64(l)) - } - return n -} - -func (m *ContractCodeHistoryEntry) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Operation != 0 { - n += 1 + sovTypes(uint64(m.Operation)) - } - if m.CodeID != 0 { - n += 1 + sovTypes(uint64(m.CodeID)) - } - if m.Updated != nil { - l = m.Updated.Size() - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - return n -} - -func (m *AbsoluteTxPosition) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.BlockHeight != 0 { - n += 1 + sovTypes(uint64(m.BlockHeight)) - } - if m.TxIndex != 0 { - n += 1 + sovTypes(uint64(m.TxIndex)) - } - return n -} - -func (m *Model) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Key) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - l = len(m.Value) - if l > 0 { - n += 1 + l + sovTypes(uint64(l)) - } - return n -} - -func sovTypes(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozTypes(x uint64) (n int) { - return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *AccessTypeParam) 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 ErrIntOverflowTypes - } - 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: AccessTypeParam: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccessTypeParam: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - m.Value = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Value |= AccessType(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AccessConfig) 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 ErrIntOverflowTypes - } - 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: AccessConfig: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AccessConfig: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Permission", wireType) - } - m.Permission = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Permission |= AccessType(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - 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 ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Addresses", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - 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 ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Addresses = append(m.Addresses, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -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 ErrIntOverflowTypes - } - 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 != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeUploadAccess", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.CodeUploadAccess.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiateDefaultPermission", wireType) - } - m.InstantiateDefaultPermission = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.InstantiateDefaultPermission |= AccessType(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *CodeInfo) 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 ErrIntOverflowTypes - } - 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: CodeInfo: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CodeInfo: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) - if m.CodeHash == nil { - m.CodeHash = []byte{} - } - iNdEx = postIndex - case 2: - 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 ErrIntOverflowTypes - } - 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 ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiateConfig", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.InstantiateConfig.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ContractInfo) 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 ErrIntOverflowTypes - } - 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: ContractInfo: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractInfo: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - 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 ErrIntOverflowTypes - } - 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 ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - 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 ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Admin = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - 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 ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Label = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Created", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Created == nil { - m.Created = &AbsoluteTxPosition{} - } - if err := m.Created.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IBCPortID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - 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 ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IBCPortID = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Extension", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Extension == nil { - m.Extension = &types.Any{} - } - if err := m.Extension.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *ContractCodeHistoryEntry) 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 ErrIntOverflowTypes - } - 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: ContractCodeHistoryEntry: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ContractCodeHistoryEntry: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Operation", wireType) - } - m.Operation = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Operation |= ContractCodeHistoryOperationType(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) - } - m.CodeID = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Updated", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Updated == nil { - m.Updated = &AbsoluteTxPosition{} - } - if err := m.Updated.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) - if m.Msg == nil { - m.Msg = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *AbsoluteTxPosition) 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 ErrIntOverflowTypes - } - 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: AbsoluteTxPosition: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AbsoluteTxPosition: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field BlockHeight", wireType) - } - m.BlockHeight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.BlockHeight |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TxIndex", wireType) - } - m.TxIndex = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TxIndex |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *Model) 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 ErrIntOverflowTypes - } - 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: Model: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Model: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) - if m.Key == nil { - m.Key = []byte{} - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...) - if m.Value == nil { - m.Value = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTypes(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTypes - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipTypes(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, ErrIntOverflowTypes - } - 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, ErrIntOverflowTypes - } - 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, ErrIntOverflowTypes - } - 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, ErrInvalidLengthTypes - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTypes - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTypes - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/wasm/types/types_test.go b/x/wasm/types/types_test.go deleted file mode 100644 index 3221c00..0000000 --- a/x/wasm/types/types_test.go +++ /dev/null @@ -1,751 +0,0 @@ -package types - -import ( - "bytes" - "context" - "strings" - "testing" - "time" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - "github.com/cometbft/cometbft/libs/rand" - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestContractInfoValidateBasic(t *testing.T) { - specs := map[string]struct { - srcMutator func(*ContractInfo) - expError bool - }{ - "all good": {srcMutator: func(_ *ContractInfo) {}}, - "code id empty": { - srcMutator: func(c *ContractInfo) { c.CodeID = 0 }, - expError: true, - }, - "creator empty": { - srcMutator: func(c *ContractInfo) { c.Creator = "" }, - expError: true, - }, - "creator not an address": { - srcMutator: func(c *ContractInfo) { c.Creator = invalidAddress }, - expError: true, - }, - "admin empty": { - srcMutator: func(c *ContractInfo) { c.Admin = "" }, - expError: false, - }, - "admin not an address": { - srcMutator: func(c *ContractInfo) { c.Admin = invalidAddress }, - expError: true, - }, - "label empty": { - srcMutator: func(c *ContractInfo) { c.Label = "" }, - expError: true, - }, - "label exceeds limit": { - srcMutator: func(c *ContractInfo) { c.Label = strings.Repeat("a", MaxLabelSize+1) }, - expError: true, - }, - "invalid extension": { - srcMutator: func(c *ContractInfo) { - // any protobuf type with ValidateBasic method - codecAny, err := codectypes.NewAnyWithValue(&v1beta1.TextProposal{}) - - require.NoError(t, err) - c.Extension = codecAny - }, - expError: true, - }, - "not validatable extension": { - srcMutator: func(c *ContractInfo) { - // any protobuf type with ValidateBasic method - codecAny, err := codectypes.NewAnyWithValue(&v1beta1.Proposal{}) - - require.NoError(t, err) - c.Extension = codecAny - }, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := ContractInfoFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestCodeInfoValidateBasic(t *testing.T) { - specs := map[string]struct { - srcMutator func(*CodeInfo) - expError bool - }{ - "all good": {srcMutator: func(_ *CodeInfo) {}}, - "code hash empty": { - srcMutator: func(c *CodeInfo) { c.CodeHash = []byte{} }, - expError: true, - }, - "code hash nil": { - srcMutator: func(c *CodeInfo) { c.CodeHash = nil }, - expError: true, - }, - "creator empty": { - srcMutator: func(c *CodeInfo) { c.Creator = "" }, - expError: true, - }, - "creator not an address": { - srcMutator: func(c *CodeInfo) { c.Creator = invalidAddress }, - expError: true, - }, - "Instantiate config invalid": { - srcMutator: func(c *CodeInfo) { c.InstantiateConfig = AccessConfig{} }, - expError: true, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - state := CodeInfoFixture(spec.srcMutator) - got := state.ValidateBasic() - if spec.expError { - require.Error(t, got) - return - } - require.NoError(t, got) - }) - } -} - -func TestContractInfoSetExtension(t *testing.T) { - anyTime := time.Now().UTC() - aNestedProtobufExt := func() ContractInfoExtension { - // using gov proposal here as a random protobuf types as it contains an Any type inside for nested unpacking - myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "bar"}, 1, anyTime, anyTime) - require.NoError(t, err) - myExtension.TotalDeposit = nil - return &myExtension - } - - specs := map[string]struct { - src ContractInfoExtension - expErr bool - expNil bool - }{ - "all good with any proto extension": { - src: aNestedProtobufExt(), - }, - "nil allowed": { - src: nil, - expNil: true, - }, - "validated and accepted": { - src: &v1beta1.TextProposal{Title: "bar", Description: "set"}, - }, - "validated and rejected": { - src: &v1beta1.TextProposal{Title: "bar"}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var c ContractInfo - gotErr := c.SetExtension(spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - if spec.expNil { - return - } - require.NotNil(t, c.Extension) - assert.NotNil(t, c.Extension.GetCachedValue()) - }) - } -} - -func TestContractInfoMarshalUnmarshal(t *testing.T) { - var myAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) - var myOtherAddr sdk.AccAddress = rand.Bytes(ContractAddrLen) - anyPos := AbsoluteTxPosition{BlockHeight: 1, TxIndex: 2} - - anyTime := time.Now().UTC() - // using gov proposal here as a random protobuf types as it contains an Any type inside for nested unpacking - myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "bar"}, 1, anyTime, anyTime) - require.NoError(t, err) - myExtension.TotalDeposit = nil - - src := NewContractInfo(1, myAddr, myOtherAddr, "bar", &anyPos) - err = src.SetExtension(&myExtension) - require.NoError(t, err) - - interfaceRegistry := codectypes.NewInterfaceRegistry() - marshaler := codec.NewProtoCodec(interfaceRegistry) - RegisterInterfaces(interfaceRegistry) - // register proposal as extension type - interfaceRegistry.RegisterImplementations( - (*ContractInfoExtension)(nil), - &v1beta1.Proposal{}, - ) - // register gov types for nested Anys - v1beta1.RegisterInterfaces(interfaceRegistry) - - // when encode - bz, err := marshaler.Marshal(&src) - require.NoError(t, err) - // and decode - var dest ContractInfo - err = marshaler.Unmarshal(bz, &dest) - // then - require.NoError(t, err) - assert.Equal(t, src, dest) - // and sanity check nested any - var destExt v1beta1.Proposal - require.NoError(t, dest.ReadExtension(&destExt)) - assert.Equal(t, destExt.GetTitle(), "bar") -} - -func TestContractInfoReadExtension(t *testing.T) { - anyTime := time.Now().UTC() - myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "foo"}, 1, anyTime, anyTime) - require.NoError(t, err) - type TestExtensionAsStruct struct { - ContractInfoExtension - } - - specs := map[string]struct { - setup func(*ContractInfo) - param func() ContractInfoExtension - expVal ContractInfoExtension - expErr bool - }{ - "all good": { - setup: func(i *ContractInfo) { - err = i.SetExtension(&myExtension) - require.NoError(t, err) - }, - param: func() ContractInfoExtension { - return &v1beta1.Proposal{} - }, - expVal: &myExtension, - }, - "no extension set": { - setup: func(i *ContractInfo) { - }, - param: func() ContractInfoExtension { - return &v1beta1.Proposal{} - }, - expVal: &v1beta1.Proposal{}, - }, - "nil argument value": { - setup: func(i *ContractInfo) { - err = i.SetExtension(&myExtension) - require.NoError(t, err) - }, - param: func() ContractInfoExtension { - return nil - }, - expErr: true, - }, - "non matching types": { - setup: func(i *ContractInfo) { - err = i.SetExtension(&myExtension) - require.NoError(t, err) - }, - param: func() ContractInfoExtension { - return &v1beta1.TextProposal{} - }, - expErr: true, - }, - "not a pointer argument": { - setup: func(i *ContractInfo) { - }, - param: func() ContractInfoExtension { - return TestExtensionAsStruct{} - }, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - var c ContractInfo - spec.setup(&c) - // when - - gotValue := spec.param() - gotErr := c.ReadExtension(gotValue) - - // then - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.expVal, gotValue) - }) - } -} - -func TestNewEnv(t *testing.T) { - myTime := time.Unix(0, 1619700924259075000) - t.Logf("++ unix: %d", myTime.UnixNano()) - var myContractAddr sdk.AccAddress = randBytes(ContractAddrLen) - specs := map[string]struct { - srcCtx sdk.Context - exp wasmvmtypes.Env - }{ - "all good with tx counter": { - srcCtx: WithTXCounter(sdk.Context{}.WithBlockHeight(1).WithBlockTime(myTime).WithChainID("testing").WithContext(context.Background()), 0), - exp: wasmvmtypes.Env{ - Block: wasmvmtypes.BlockInfo{ - Height: 1, - Time: 1619700924259075000, - ChainID: "testing", - }, - Contract: wasmvmtypes.ContractInfo{ - Address: myContractAddr.String(), - }, - Transaction: &wasmvmtypes.TransactionInfo{Index: 0}, - }, - }, - "without tx counter": { - srcCtx: sdk.Context{}.WithBlockHeight(1).WithBlockTime(myTime).WithChainID("testing").WithContext(context.Background()), - exp: wasmvmtypes.Env{ - Block: wasmvmtypes.BlockInfo{ - Height: 1, - Time: 1619700924259075000, - ChainID: "testing", - }, - Contract: wasmvmtypes.ContractInfo{ - Address: myContractAddr.String(), - }, - }, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - assert.Equal(t, spec.exp, NewEnv(spec.srcCtx, myContractAddr)) - }) - } -} - -func TestVerifyAddressLen(t *testing.T) { - specs := map[string]struct { - src []byte - expErr bool - }{ - "valid contract address": { - src: bytes.Repeat([]byte{1}, 32), - }, - "valid legacy address": { - src: bytes.Repeat([]byte{1}, 20), - }, - "address too short for legacy": { - src: bytes.Repeat([]byte{1}, 19), - expErr: true, - }, - "address too short for contract": { - src: bytes.Repeat([]byte{1}, 31), - expErr: true, - }, - "address too long for legacy": { - src: bytes.Repeat([]byte{1}, 21), - expErr: true, - }, - "address too long for contract": { - src: bytes.Repeat([]byte{1}, 33), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := VerifyAddressLen()(spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} - -func TestAccessConfigSubset(t *testing.T) { - // read - // <, <= is subset of - // !< is not subset of - specs := map[string]struct { - check AccessConfig - superSet AccessConfig - isSubSet bool - }{ - // nobody - "nobody <= nobody": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: true, - }, - "only !< nobody": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "foobar"}, - isSubSet: false, - }, - "anyOf !< nobody": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"foobar"}}, - isSubSet: false, - }, - "everybody !< nobody ": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: false, - }, - "unspecified !< nobody": { - superSet: AccessConfig{Permission: AccessTypeNobody}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - // only - "nobody < only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: true, - }, - "only <= only(same)": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - isSubSet: true, - }, - "only !< only(other)": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "other"}, - isSubSet: false, - }, - "anyOf(same) <= only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - isSubSet: true, - }, - "anyOf(other) !< only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"foobar"}}, - isSubSet: false, - }, - "anyOf(same, other) !< only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "foobar"}}, - isSubSet: false, - }, - "everybody !< only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: false, - }, - "unspecified !<= only": { - superSet: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - - // any of - "nobody < anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: true, - }, - "only(same) < anyOf(same)": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - isSubSet: true, - }, - "only(same) < anyOf(same, other)": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other"}}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "owner"}, - isSubSet: true, - }, - "only(other) !< anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "other"}, - isSubSet: false, - }, - "anyOf < anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - isSubSet: true, - }, - "anyOf(multiple) < anyOf(multiple)": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other"}}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other"}}, - isSubSet: true, - }, - "anyOf(multiple, other) !< anyOf(multiple)": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other", "foo"}}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other", "bar"}}, - isSubSet: false, - }, - "anyOf(multiple) !< anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner", "other"}}, - isSubSet: false, - }, - "everybody !< anyOf": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: false, - }, - "unspecified !< anyOf ": { - superSet: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"owner"}}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - // everybody - "nobody < everybody": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: true, - }, - "only < everybody": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "foobar"}, - isSubSet: true, - }, - "anyOf < everybody": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"foobar"}}, - isSubSet: true, - }, - "everybody <= everybody": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: true, - }, - "unspecified !< everybody ": { - superSet: AccessConfig{Permission: AccessTypeEverybody}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - // unspecified - "nobody !< unspecified": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeNobody}, - isSubSet: false, - }, - "only !< unspecified": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeOnlyAddress, Address: "foobar"}, - isSubSet: false, - }, - "anyOf !< unspecified": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: []string{"foobar"}}, - isSubSet: false, - }, - "everybody !< unspecified": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeEverybody}, - isSubSet: false, - }, - "unspecified !< unspecified ": { - superSet: AccessConfig{Permission: AccessTypeUnspecified}, - check: AccessConfig{Permission: AccessTypeUnspecified}, - isSubSet: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - subset := spec.check.IsSubset(spec.superSet) - require.Equal(t, spec.isSubSet, subset) - }) - } -} - -func TestAccessTypeSubset(t *testing.T) { - specs := map[string]struct { - check AccessType - superSet AccessType - isSubSet bool - }{ - // nobody - "nobody <= nobody": { - superSet: AccessTypeNobody, - check: AccessTypeNobody, - isSubSet: true, - }, - "only !< nobody": { - superSet: AccessTypeNobody, - check: AccessTypeOnlyAddress, - isSubSet: false, - }, - "any !< nobody": { - superSet: AccessTypeNobody, - check: AccessTypeAnyOfAddresses, - isSubSet: false, - }, - "everybody !< nobody": { - superSet: AccessTypeNobody, - check: AccessTypeEverybody, - isSubSet: false, - }, - "unspecified !< nobody": { - superSet: AccessTypeNobody, - check: AccessTypeUnspecified, - isSubSet: false, - }, - // only - "nobody < only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeNobody, - isSubSet: true, - }, - "only <= only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeOnlyAddress, - isSubSet: true, - }, - "anyOf !< only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeAnyOfAddresses, - isSubSet: true, - }, - "everybody !< only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeEverybody, - isSubSet: false, - }, - "unspecified !< only": { - superSet: AccessTypeOnlyAddress, - check: AccessTypeUnspecified, - isSubSet: false, - }, - // any of - "nobody < anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeNobody, - isSubSet: true, - }, - "only <= anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeOnlyAddress, - isSubSet: true, - }, - "anyOf <= anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeAnyOfAddresses, - isSubSet: true, - }, - "everybody !< anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeEverybody, - isSubSet: false, - }, - "unspecified !< anyOf": { - superSet: AccessTypeAnyOfAddresses, - check: AccessTypeUnspecified, - isSubSet: false, - }, - // everybody - "nobody < everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeNobody, - isSubSet: true, - }, - "only < everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeOnlyAddress, - isSubSet: true, - }, - "anyOf < everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeAnyOfAddresses, - isSubSet: true, - }, - "everybody <= everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeEverybody, - isSubSet: true, - }, - "unspecified !< everybody": { - superSet: AccessTypeEverybody, - check: AccessTypeUnspecified, - isSubSet: false, - }, - // unspecified - "nobody !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeNobody, - isSubSet: false, - }, - "only !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeOnlyAddress, - isSubSet: false, - }, - "anyOf !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeAnyOfAddresses, - isSubSet: false, - }, - "everybody !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeEverybody, - isSubSet: false, - }, - "unspecified !< unspecified": { - superSet: AccessTypeUnspecified, - check: AccessTypeUnspecified, - isSubSet: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - subset := spec.check.IsSubset(spec.superSet) - require.Equal(t, spec.isSubSet, subset) - }) - } -} - -func TestContractCodeHistoryEntryValidation(t *testing.T) { - specs := map[string]struct { - src ContractCodeHistoryEntry - expErr bool - }{ - "all good": { - src: ContractCodeHistoryEntryFixture(), - }, - "unknown operation": { - src: ContractCodeHistoryEntryFixture(func(entry *ContractCodeHistoryEntry) { - entry.Operation = 0 - }), - expErr: true, - }, - "empty code id": { - src: ContractCodeHistoryEntryFixture(func(entry *ContractCodeHistoryEntry) { - entry.CodeID = 0 - }), - expErr: true, - }, - "empty updated": { - src: ContractCodeHistoryEntryFixture(func(entry *ContractCodeHistoryEntry) { - entry.Updated = nil - }), - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - gotErr := spec.src.ValidateBasic() - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} diff --git a/x/wasm/types/validation.go b/x/wasm/types/validation.go deleted file mode 100644 index d3e678b..0000000 --- a/x/wasm/types/validation.go +++ /dev/null @@ -1,79 +0,0 @@ -package types - -import ( - "fmt" - "net/url" - - errorsmod "cosmossdk.io/errors" - "github.com/docker/distribution/reference" -) - -// MaxSaltSize is the longest salt that can be used when instantiating a contract -const MaxSaltSize = 64 - -var ( - // MaxLabelSize is the longest label that can be used when instantiating a contract - MaxLabelSize = 128 // extension point for chains to customize via compile flag. - - // MaxWasmSize is the largest a compiled contract code can be when storing code on chain - MaxWasmSize = 800 * 1024 // extension point for chains to customize via compile flag. - - // MaxProposalWasmSize is the largest a gov proposal compiled contract code can be when storing code on chain - MaxProposalWasmSize = 3 * 1024 * 1024 // extension point for chains to customize via compile flag. -) - -func validateWasmCode(s []byte, maxSize int) error { - if len(s) == 0 { - return errorsmod.Wrap(ErrEmpty, "is required") - } - if len(s) > maxSize { - return errorsmod.Wrapf(ErrLimit, "cannot be longer than %d bytes", maxSize) - } - return nil -} - -// ValidateLabel ensure label constraints -func ValidateLabel(label string) error { - if label == "" { - return errorsmod.Wrap(ErrEmpty, "is required") - } - if len(label) > MaxLabelSize { - return ErrLimit.Wrapf("cannot be longer than %d characters", MaxLabelSize) - } - return nil -} - -// ValidateSalt ensure salt constraints -func ValidateSalt(salt []byte) error { - switch n := len(salt); { - case n == 0: - return errorsmod.Wrap(ErrEmpty, "is required") - case n > MaxSaltSize: - return ErrLimit.Wrapf("cannot be longer than %d characters", MaxSaltSize) - } - return nil -} - -// ValidateVerificationInfo ensure source, builder and checksum constraints -func ValidateVerificationInfo(source, builder string, codeHash []byte) error { - // if any set require others to be set - if len(source) != 0 || len(builder) != 0 || codeHash != nil { - if source == "" { - return fmt.Errorf("source is required") - } - if _, err := url.ParseRequestURI(source); err != nil { - return fmt.Errorf("source: %s", err) - } - if builder == "" { - return fmt.Errorf("builder is required") - } - if _, err := reference.ParseDockerRef(builder); err != nil { - return fmt.Errorf("builder: %s", err) - } - if codeHash == nil { - return fmt.Errorf("code hash is required") - } - // code hash checksum match validation is done in the keeper, ungzipping consumes gas - } - return nil -} diff --git a/x/wasm/types/wasmer_engine.go b/x/wasm/types/wasmer_engine.go deleted file mode 100644 index 9b2efde..0000000 --- a/x/wasm/types/wasmer_engine.go +++ /dev/null @@ -1,277 +0,0 @@ -package types - -import ( - wasmvm "github.com/CosmWasm/wasmvm" - wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// DefaultMaxQueryStackSize maximum size of the stack of contract instances doing queries -const DefaultMaxQueryStackSize uint32 = 10 - -// WasmerEngine defines the WASM contract runtime engine. -type WasmerEngine interface { - // Create will compile the wasm code, and store the resulting pre-compile - // as well as the original code. Both can be referenced later via CodeID - // This must be done one time for given code, after which it can be - // instatitated many times, and each instance called many times. - // - // For example, the code for all ERC-20 contracts should be the same. - // This function stores the code for that contract only once, but it can - // be instantiated with custom inputs in the future. - Create(code wasmvm.WasmCode) (wasmvm.Checksum, error) - - // AnalyzeCode will statically analyze the code. - // Currently just reports if it exposes all IBC entry points. - AnalyzeCode(checksum wasmvm.Checksum) (*wasmvmtypes.AnalysisReport, error) - - // Instantiate will create a new contract based on the given codeID. - // We can set the initMsg (contract "genesis") here, and it then receives - // an account and address and can be invoked (Execute) many times. - // - // Storage should be set with a PrefixedKVStore that this code can safely access. - // - // Under the hood, we may recompile the wasm, use a cached native compile, or even use a cached instance - // for performance. - Instantiate( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - info wasmvmtypes.MessageInfo, - initMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // Execute calls a given contract. Since the only difference between contracts with the same CodeID is the - // data in their local storage, and their address in the outside world, we need no ContractID here. - // (That is a detail for the external, sdk-facing, side). - // - // The caller is responsible for passing the correct `store` (which must have been initialized exactly once), - // and setting the env with relevant info on this instance (address, balance, etc) - Execute( - code wasmvm.Checksum, - env wasmvmtypes.Env, - info wasmvmtypes.MessageInfo, - executeMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // Query allows a client to execute a contract-specific query. If the result is not empty, it should be - // valid json-encoded data to return to the client. - // The meaning of path and data can be determined by the code. Path is the suffix of the abci.QueryRequest.Path - Query( - code wasmvm.Checksum, - env wasmvmtypes.Env, - queryMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) ([]byte, uint64, error) - - // Migrate will migrate an existing contract to a new code binary. - // This takes storage of the data from the original contract and the CodeID of the new contract that should - // replace it. This allows it to run a migration step if needed, or return an error if unable to migrate - // the given data. - // - // MigrateMsg has some data on how to perform the migration. - Migrate( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - migrateMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // Sudo runs an existing contract in read/write mode (like Execute), but is never exposed to external callers - // (either transactions or government proposals), but can only be called by other native Go modules directly. - // - // This allows a contract to expose custom "super user" functions or priviledged operations that can be - // deeply integrated with native modules. - Sudo( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - sudoMsg []byte, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // Reply is called on the original dispatching contract after running a submessage - Reply( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - reply wasmvmtypes.Reply, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.Response, uint64, error) - - // GetCode will load the original wasm code for the given code id. - // This will only succeed if that code id was previously returned from - // a call to Create. - // - // This can be used so that the (short) code id (hash) is stored in the iavl tree - // and the larger binary blobs (wasm and pre-compiles) are all managed by the - // rust library - GetCode(code wasmvm.Checksum) (wasmvm.WasmCode, error) - - // Cleanup should be called when no longer using this to free resources on the rust-side - Cleanup() - - // IBCChannelOpen is available on IBC-enabled contracts and is a hook to call into - // during the handshake phase - IBCChannelOpen( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelOpenMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) - - // IBCChannelConnect is available on IBC-enabled contracts and is a hook to call into - // during the handshake phase - IBCChannelConnect( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelConnectMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - // IBCChannelClose is available on IBC-enabled contracts and is a hook to call into - // at the end of the channel lifetime - IBCChannelClose( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - channel wasmvmtypes.IBCChannelCloseMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - // IBCPacketReceive is available on IBC-enabled contracts and is called when an incoming - // packet is received on a channel belonging to this contract - IBCPacketReceive( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - packet wasmvmtypes.IBCPacketReceiveMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCReceiveResult, uint64, error) - - // IBCPacketAck is available on IBC-enabled contracts and is called when an - // the response for an outgoing packet (previously sent by this contract) - // is received - IBCPacketAck( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - ack wasmvmtypes.IBCPacketAckMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - // IBCPacketTimeout is available on IBC-enabled contracts and is called when an - // outgoing packet (previously sent by this contract) will probably never be executed. - // Usually handled like ack returning an error - IBCPacketTimeout( - checksum wasmvm.Checksum, - env wasmvmtypes.Env, - packet wasmvmtypes.IBCPacketTimeoutMsg, - store wasmvm.KVStore, - goapi wasmvm.GoAPI, - querier wasmvm.Querier, - gasMeter wasmvm.GasMeter, - gasLimit uint64, - deserCost wasmvmtypes.UFraction, - ) (*wasmvmtypes.IBCBasicResponse, uint64, error) - - // Pin pins a code to an in-memory cache, such that is - // always loaded quickly when executed. - // Pin is idempotent. - Pin(checksum wasmvm.Checksum) error - - // Unpin removes the guarantee of a contract to be pinned (see Pin). - // After calling this, the code may or may not remain in memory depending on - // the implementor's choice. - // Unpin is idempotent. - Unpin(checksum wasmvm.Checksum) error - - // GetMetrics some internal metrics for monitoring purposes. - GetMetrics() (*wasmvmtypes.Metrics, error) -} - -var _ wasmvm.KVStore = &StoreAdapter{} - -// StoreAdapter adapter to bridge SDK store impl to wasmvm -type StoreAdapter struct { - parent sdk.KVStore -} - -// NewStoreAdapter constructor -func NewStoreAdapter(s sdk.KVStore) *StoreAdapter { - if s == nil { - panic("store must not be nil") - } - return &StoreAdapter{parent: s} -} - -func (s StoreAdapter) Get(key []byte) []byte { - return s.parent.Get(key) -} - -func (s StoreAdapter) Set(key, value []byte) { - s.parent.Set(key, value) -} - -func (s StoreAdapter) Delete(key []byte) { - s.parent.Delete(key) -} - -func (s StoreAdapter) Iterator(start, end []byte) wasmvmtypes.Iterator { - return s.parent.Iterator(start, end) -} - -func (s StoreAdapter) ReverseIterator(start, end []byte) wasmvmtypes.Iterator { - return s.parent.ReverseIterator(start, end) -}