diff --git a/.circleci/config.yml b/.circleci/config.yml index 4707956..23d3c1e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,7 +3,7 @@ version: 2.1 executors: golang: docker: - - image: cimg/go:1.19 + - image: cimg/go:1.20.0 commands: make: @@ -61,7 +61,7 @@ jobs: lint: docker: - - image: golangci/golangci-lint:v1.46.2 + - image: golangci/golangci-lint:v1.51.1 steps: - checkout - run: @@ -124,7 +124,7 @@ jobs: - run: name: Run simulations command: | - make test-sim-multi-seed-short + make test-sim-multi-seed-short test-sim-import-export test-sim-deterministic - store_artifacts: path: /tmp @@ -174,7 +174,7 @@ jobs: fi - when: condition: - equal: [main, << pipeline.git.branch >>] + equal: [ main, << pipeline.git.branch >> ] steps: - run: name: Push application Docker image to docker hub diff --git a/.codecov.yml b/.codecov.yml new file mode 100644 index 0000000..02822ff --- /dev/null +++ b/.codecov.yml @@ -0,0 +1,57 @@ +# +# This codecov.yml is the default configuration for +# all repositories on Codecov. You may adjust the settings +# below in your own codecov.yml in your repository. +# +coverage: + precision: 2 + round: down + range: 70...100 + + status: + # Learn more at https://docs.codecov.io/docs/commit-status + project: + default: + threshold: 1% # allow this much decrease on project + app: + target: 70% + flags: + - app + modules: + target: 70% + flags: + - modules + client: + flags: + - client + changes: false + +comment: + layout: "reach, diff, files" + behavior: default # update if exists else create new + require_changes: true + +flags: + app: + paths: + - "app/" + modules: + paths: + - "x/" + - "!x/**/client/" # ignore client package + client: + paths: + - "x/**/client/" + +ignore: + - "cmd/" + - "contrib/" + - "docs/" + - "docker/" + - "scripts/" + - "*.md" + - "*.rst" + - "x/**/*.pb.go" + - "x/**/*.pb.gw.go" + - "x/**/test_common.go" + - "x/**/testdata/" diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 376c012..3d21b52 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -18,7 +18,7 @@ updates: - 0.14.0-beta4 - 0.14.0-beta5 - 0.14.0-rc1 - - dependency-name: github.com/tendermint/tendermint + - dependency-name: github.com/cometbft/cometbft versions: - 0.34.10 - 0.34.4 @@ -40,6 +40,6 @@ updates: - dependency-name: github.com/spf13/cobra versions: - 1.1.2 - - dependency-name: github.com/tendermint/tm-db + - dependency-name: github.com/cometbft/cometbft-db versions: - 0.6.4 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..d475c56 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,37 @@ +--- +on: [push, pull_request] +name: Build + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + name: build + steps: + - uses: actions/checkout@v3 + - name: Setup go + uses: actions/setup-go@v3 + with: + go-version: "1.20" + - run: go build ./... + + tidy: + runs-on: ubuntu-latest + name: tidy + steps: + - uses: actions/checkout@v3 + - name: Setup go + uses: actions/setup-go@v3 + with: + go-version: "1.20" + - run: | + go mod tidy + CHANGES_IN_REPO=$(git status --porcelain) + if [[ -n "$CHANGES_IN_REPO" ]]; then + echo "Repository is dirty. Showing 'git status' and 'git --no-pager diff' for debugging now:" + git status && git --no-pager diff + exit 1 + fi \ No newline at end of file diff --git a/.github/workflows/codacy.yml b/.github/workflows/codacy.yml new file mode 100644 index 0000000..99a8ec9 --- /dev/null +++ b/.github/workflows/codacy.yml @@ -0,0 +1,61 @@ +# 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@d43127fe38d20c527dc1951ae5aea23148bab738 + 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-analizer.yml index 67b8a1a..05a9cac 100644 --- a/.github/workflows/codeql-analizer.yml +++ b/.github/workflows/codeql-analizer.yml @@ -19,7 +19,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v3.1.0 + uses: actions/checkout@v3.5.0 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/codeql-cosmos.yml b/.github/workflows/codeql-cosmos.yml new file mode 100644 index 0000000..e9efe52 --- /dev/null +++ b/.github/workflows/codeql-cosmos.yml @@ -0,0 +1,40 @@ +name: "CodeQL for cosmos" + +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@v3 + 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 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..5943985 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,40 @@ +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@v3 + 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 diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 0000000..f5c89e3 --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,20 @@ +# 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/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..527164a --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,23 @@ +--- +name: Build Docker Image on PR + +on: + pull_request: + +jobs: + docker: + runs-on: ubuntu-latest + steps: + - name: Checkout + 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: Build without push + uses: docker/build-push-action@v4 + with: + context: . + platforms: linux/amd64 + push: false + build-args: arch=x86_64 \ No newline at end of file diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml new file mode 100644 index 0000000..953b51b --- /dev/null +++ b/.github/workflows/golangci-lint.yml @@ -0,0 +1,34 @@ +--- +name: golangci-lint +on: + push: + tags: + - v* + branches: + - release/v* + - main + pull_request: +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 }} + cancel-in-progress: true + +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v3 + with: + go-version: "1.20" + - uses: actions/checkout@v3 + + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + version: latest + args: --timeout 10m \ No newline at end of file diff --git a/.github/workflows/proto-buf-publisher.yml b/.github/workflows/proto-buf-publisher.yml index 82f9038..1b125a4 100644 --- a/.github/workflows/proto-buf-publisher.yml +++ b/.github/workflows/proto-buf-publisher.yml @@ -1,5 +1,5 @@ name: Proto Buf Publishing - Action -# Protobuf runs buf (https://buf.build/) push updated proto files to https://buf.build/terpnetwork/terp-core +# 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: @@ -16,8 +16,8 @@ jobs: push: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3.1.0 - - uses: bufbuild/buf-setup-action@v1.13.1 + - uses: actions/checkout@v3.5.0 + - uses: bufbuild/buf-setup-action@v1.16.0 # lint checks - uses: bufbuild/buf-lint-action@v1 @@ -35,4 +35,4 @@ jobs: - uses: bufbuild/buf-push-action@v1 with: input: "proto" - buf_token: ${{ secrets.BUF_TOKEN }} + buf_token: ${{ secrets.BUF_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..183d99e --- /dev/null +++ b/.github/workflows/tests.yml @@ -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/.gitpod.yml b/.gitpod.yml new file mode 100644 index 0000000..e5306c8 --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,9 @@ +# This configuration file was automatically generated by Gitpod. +# Please adjust to your needs (see https://www.gitpod.io/docs/config-gitpod-file) +# and commit this file to your remote git repository to share the goodness with others. + +tasks: + - init: go get && go build ./... && go test ./... && make + command: go run + + diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..3f31b03 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,66 @@ +run: + tests: true + # timeout for analysis, e.g. 30s, 5m, default is 1m + timeout: 5m + +linters: + disable-all: true + enable: + - bodyclose + - depguard + - dogsled + - errcheck + - exportloopref + - goconst + - gocritic + - gofumpt + - gosec + - gosimple + - govet + - ineffassign + - misspell + - nakedret + - nolintlint + - revive + - staticcheck + - stylecheck + - typecheck + - thelper + - unconvert + - unparam + - unused + +issues: + exclude-rules: + - text: "simtypes" + linters: + - staticcheck + - text: "Use of weak random number generator" + linters: + - gosec + - text: "ST1003:" + linters: + - stylecheck + # FIXME: Disabled until golangci-lint updates stylecheck with this fix: + # https://github.com/dominikh/go-tools/issues/389 + - text: "ST1016:" + linters: + - stylecheck + - path: "migrations" + text: "SA1019:" + linters: + - staticcheck + + max-issues-per-linter: 10000 + max-same-issues: 10000 + +linters-settings: + revive: + # When set to false, ignores files with "GENERATED" header, similar to golint + ignore-generated-header: true + + nolintlint: + allow-unused: false + allow-leading-space: true + require-explanation: false + require-specific: false \ No newline at end of file diff --git a/.mergify.yml b/.mergify.yml new file mode 100644 index 0000000..0f3a325 --- /dev/null +++ b/.mergify.yml @@ -0,0 +1,22 @@ +queue_rules: + - name: default + conditions: + - "#approved-reviews-by>0" + +pull_request_rules: + - name: backport patches to main branch + conditions: + - base=releases/v0.3x + - label=backport/main + actions: + backport: + branches: + - main + - name: backport patches to sdk45 release branch + conditions: + - base=main + - label=backport/v0.3x + actions: + backport: + branches: + - releases/v0.3x diff --git a/.sonarcloud.properties b/.sonarcloud.properties new file mode 100644 index 0000000..39468de --- /dev/null +++ b/.sonarcloud.properties @@ -0,0 +1,5 @@ +# 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 index adb43b0..ad4edda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,71 +1,83 @@ -# CHANGELOG - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to -[Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] -- Upgrade to WasmVM v1.2.0 -- Upgrade to cosmos-proto v1.0.0-beta.1 -- Upgrade to spf13/cobra v1.6.1 -- Upgrade to Tendermint v0.34.24 -- Upgrade to go-metrics v0.4.1 -- Upgrade to ics23 v0.9.0 -- Upgrade to btcutil v1.0.5 -- Upgrade to ledger-go v0.9.3 -- Upgrade to go-humanize v1.0.1-0.20200219035652-afde56e7acac -- x/terp module for supplychainid & supplychain db core concepts -- Provide full x/upgrade features - -## [v0.2.0](https://github.com/terpnetwork/terp-core/tree/v0.2.0) (2022-12-12) - -[Full Changelog](https://github.com/terpnetwork/terp-core/compare/v0.1.1...v0.2.0) - -- Provide source, builder and codehash information in store code proposal message -- Upgrade to Go v1.19 #1044 -- Upgrade to Cosmos-sdk to v0.45.11 -- Upgrade to IBC v4.2.0 with interchain-accounts v0.2.4 -- Preserve contract history/ created date on genesis import -- Authz module integration - more granularity for WasmExecuteMsg authorizations -- StoreAndInstantiate gov proposal -- Start developer guide for contributors -- Fixes missing instantiate-anyof-addresses flag declaration for gov / -- Upgrade to Cosmos-sdk to v45.9 /#1052 -- Add dependencies for protobuf and remove third_party forlder /#1030 -- Check wasmvm version on startup #1029 -- Allow AccessConfig to use a list of addresses instead of just a single address -- Make contract addresses predictable ("deterministic") -- Add query for the total supply of a coin #903 (larry0x) -- Upgrade go to v1.18 [#866]#866) (faddat) -- Upgrade to ibc-go v3.3.0 REQUIRES MIGRATION #1016 -- Upgrade to cosmos-sdk v0.45.8 #964 (faddat) -- Upgrade wasmvm to v1.1.1 #1012, see wasmvm v1.1.1 -- Add documentation how to add x/wasm to a new Cosmos SDK chain #876 -- Upgrade keyring / go-keychain dependencies (removes deprecate warning) #957 -- Make contract pinning an optional field in StoreCode proposals #972 -- Add gRPC query for WASM params #889 -- Expose Keepers in app.go? #881 -- Remove unused flagProposalType flag in gov proposals #849 -- Restrict code access config modifications #901 -- Prevent migration to a restricted code #900 -- Charge gas to unzip wasm code #898 - -### 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. -- Authz for wasm contracts can be granted via terpd tx wasm grant and executed via terpd tx authz exec command +# 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 was introduced which is an additional value for message type events +- 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 terpd tx wasm instantiate2 CLI command for predictable addresses on instantiation -- New cosmwasm_1_1 CosmWasm capability (former "feature") was introduced in cosmwasm/#1356 to support total supply queries -- Protobuf files are published to buf.build +- 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) -## [v0.1.1](https://github.com/terpnetwork/terp-core/tree/v0.1.1) (2022-10-15) +### Migration notes -[Full Changelog](https://github.com/terpnetwork/terp-core/compare/v0.27.0...v0.28.0) +- 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** @@ -74,17 +86,397 @@ 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)) -- Reset Terp-Core Testing Scripts. These are to be reimplemented in a future issue. -- Reset Fuzz Testing. These are to be reimplemented in a future issue. 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. +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.1.0 +## [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:** -This is a baseline... no CHANGELOG was maintained until this point +- 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 new file mode 100644 index 0000000..05cb53b --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,110 @@ +# 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 643a74c..7e48739 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ -# docker build . -t terpnetwork/terp-core:latest -# docker run --rm -it terpnetwork/terp-core:latest /bin/sh +# docker build . -t terpnetwork/terpd:latest +# docker run --rm -it terpnetwork/terpd:latest /bin/sh FROM golang:1.19-alpine3.15 AS go-builder ARG arch=x86_64 @@ -14,12 +14,11 @@ RUN apk add git WORKDIR /code COPY . /code/ - # See https://github.com/CosmWasm/wasmvm/releases -ADD https://github.com/CosmWasm/wasmvm/releases/download/v1.1.1/libwasmvm_muslc.aarch64.a /lib/libwasmvm_muslc.aarch64.a -ADD https://github.com/CosmWasm/wasmvm/releases/download/v1.1.1/libwasmvm_muslc.x86_64.a /lib/libwasmvm_muslc.x86_64.a -RUN sha256sum /lib/libwasmvm_muslc.aarch64.a | grep 9ecb037336bd56076573dc18c26631a9d2099a7f2b40dc04b6cae31ffb4c8f9a -RUN sha256sum /lib/libwasmvm_muslc.x86_64.a | grep 6e4de7ba9bad4ae9679c7f9ecf7e283dd0160e71567c6a7be6ae47c81ebe7f32 +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 # 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 diff --git a/EVENTS.md b/EVENTS.md new file mode 100644 index 0000000..371e1c4 --- /dev/null +++ b/EVENTS.md @@ -0,0 +1,420 @@ +# 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 new file mode 100644 index 0000000..5907e20 --- /dev/null +++ b/INTEGRATION.md @@ -0,0 +1,205 @@ + + +# 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/LICENSE b/LICENSE index ace7d24..9c55805 100644 --- a/LICENSE +++ b/LICENSE @@ -188,7 +188,7 @@ License: Apache2.0 same "printed page" as the copyright notice for easier identification within third-party archives. - + Copyright 2016 All in Bits, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -201,10 +201,3 @@ License: Apache2.0 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - -This project uses code from the following Apache-licensed projects: - -- wasmd: https://github.com/CosmWasm/wasmd -- bcna: https://github.com/BitCannaGlobal/bcna - -The Apache License, Version 2.0 applies to these components of the codebase. \ No newline at end of file diff --git a/Makefile b/Makefile index b830c1b..f6069ef 100644 --- a/Makefile +++ b/Makefile @@ -55,7 +55,7 @@ build_tags_comma_sep := $(subst $(empty),$(comma),$(build_tags)) # process linker flags -ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=terpnetwork \ +ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=terp \ -X github.com/cosmos/cosmos-sdk/version.AppName=terpd \ -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \ -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) \ @@ -80,11 +80,15 @@ all: install lint test build: go.sum ifeq ($(OS),Windows_NT) + $(error terpd server not supported. Use "make build-windows-client" for client) exit 1 else go build -mod=readonly $(BUILD_FLAGS) -o build/terpd ./cmd/terpd endif +build-windows-client: go.sum + GOOS=windows GOARCH=amd64 go build -mod=readonly $(BUILD_FLAGS) -o build/terpd.exe ./cmd/terpd + build-contract-tests-hooks: ifeq ($(OS),Windows_NT) go build -mod=readonly $(BUILD_FLAGS) -o build/contract_tests.exe ./cmd/contract_tests @@ -142,7 +146,12 @@ test-sim-import-export: runsim 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 10 TestFullAppSimulation + @$(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 ### @@ -155,32 +164,29 @@ format-tools: lint: format-tools golangci-lint run --tests=false - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "*_test.go" | xargs gofumpt -d -s - + find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "*_test.go" | xargs gofumpt -d format: format-tools find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs gofumpt -w -s - find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs misspell -w + 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 ############################################################################### ### Protobuf ### ############################################################################### -PROTO_BUILDER_IMAGE=tendermintdev/sdk-proto-gen:v0.7 -PROTO_FORMATTER_IMAGE=tendermintdev/docker-build-proto@sha256:aabcfe2fc19c31c0f198d4cd26393f5e5ca9502d7ea3feafbfe972448fee7cae +protoVer=0.11.6 +protoImageName=ghcr.io/cosmos/proto-builder:$(protoVer) +protoImage=$(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace $(protoImageName) proto-all: proto-format proto-lint proto-gen format proto-gen: @echo "Generating Protobuf files" - $(DOCKER) run --rm -v $(CURDIR):/workspace --workdir /workspace $(PROTO_BUILDER_IMAGE) sh ./scripts/protocgen.sh + @$(protoImage) sh ./scripts/protocgen.sh proto-format: @echo "Formatting Protobuf files" - $(DOCKER) run --rm -v $(CURDIR):/workspace \ - --workdir /workspace $(PROTO_FORMATTER_IMAGE) \ - find ./ -name *.proto -exec clang-format -i {} \; - + @$(protoImage) find ./ -name "*.proto" -exec clang-format -i {} \; proto-swagger-gen: @./scripts/protoc-swagger-gen.sh @@ -193,4 +199,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 \ + test-sim-import-export build-windows-client \ diff --git a/README.md b/README.md index eb9a95a..22d28e1 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,217 @@ + # Terp-Core -**Terp Core** is a [Cosmos](https://cosmos.network) zone (layer 1 proof-of-stake blockchain). +[![license](https://img.shields.io/github/license/terpnetwork/terp-core.svg)](https://github.com/terpnetwork/terp-core/blob/main/LICENSE) -[![golangci-lint](https://github.com/JackalLabs/canine-chain/actions/workflows/golangci.yml/badge.svg)](https://github.com/terpnetwork/terp-core/actions/workflows/golangci.yml) -[![Go Report Card](https://goreportcard.com/badge/github.com/terpnetwork/terp-core)](https://goreportcard.com/report/github.com/terpnetwork/terp-core) +This repository hosts `Terp-Core`, the Daemon binary logic of [Terp-Network](https://terp.network). -## Install +This code was forked from the `notional-labs/wasmd` repository as a basis for main-network development. -### Run a local, single-node chain +For critical security issues & disclosure, see [SECURITY.md](SECURITY.md). +## Compatibility with CosmWasm contracts -Requires [Go](https://golang.org/doc/install). +## Compatibility -```sh +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). + + +## 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: -./startnode.sh +| 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. + +```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 +``` + +## 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) + +## 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): + +`sed -i 's/permission": "Everybody"/permission": "Nobody"/' .../config/genesis.json` -### Test smart contracts +## Contributors -See [./scripts/wasm/README.md](./scripts/wasm/README.md). +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: -# Disclaimer +* 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) -TERP-CORE SOFTWARE IS PROVIDED “AS IS”, AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND. +Sorry if I forgot you from this list, just contact me or add yourself in a PR :) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..021b58b --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,13 @@ +# 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/UPGRADING.md b/UPGRADING.md new file mode 100644 index 0000000..21de9cd --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,277 @@ +# 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 new file mode 100644 index 0000000..c9aedd8 --- /dev/null +++ b/api_migration.md @@ -0,0 +1,36 @@ +# 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 e7c8f2d..2d26608 100644 --- a/app/ante.go +++ b/app/ante.go @@ -1,11 +1,13 @@ package app import ( + errorsmod "cosmossdk.io/errors" + 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/x/auth/ante" - ibcante "github.com/cosmos/ibc-go/v4/modules/core/ante" - "github.com/cosmos/ibc-go/v4/modules/core/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" @@ -18,49 +20,42 @@ type HandlerOptions struct { IBCKeeper *keeper.Keeper WasmConfig *wasmTypes.WasmConfig - TXCounterStoreKey sdk.StoreKey + TXCounterStoreKey storetypes.StoreKey } func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) { if options.AccountKeeper == nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "account keeper is required for AnteHandler") + return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "account keeper is required for AnteHandler") } if options.BankKeeper == nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "bank keeper is required for AnteHandler") + return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "bank keeper is required for AnteHandler") } if options.SignModeHandler == nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "sign mode handler is required for ante builder") + return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "sign mode handler is required for ante builder") } if options.WasmConfig == nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "wasm config is required for ante builder") + return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "wasm config is required for ante builder") } if options.TXCounterStoreKey == nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "tx counter key is required for ante builder") - } - - sigGasConsumer := options.SigGasConsumer - if sigGasConsumer == nil { - sigGasConsumer = ante.DefaultSigVerificationGasConsumer + return nil, errorsmod.Wrap(sdkerrors.ErrLogic, "tx counter key is required for ante builder") } anteDecorators := []sdk.AnteDecorator{ ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first wasmkeeper.NewLimitSimulationGasDecorator(options.WasmConfig.SimulationGasLimit), // after setup context to enforce limits early wasmkeeper.NewCountTXDecorator(options.TXCounterStoreKey), - ante.NewRejectExtensionOptionsDecorator(), - ante.NewMempoolFeeDecorator(), + ante.NewExtensionOptionsDecorator(options.ExtensionOptionChecker), ante.NewValidateBasicDecorator(), ante.NewTxTimeoutHeightDecorator(), ante.NewValidateMemoDecorator(options.AccountKeeper), ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper), - ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper), - // SetPubKeyDecorator must be called before all signature verification decorators - ante.NewSetPubKeyDecorator(options.AccountKeeper), + ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker), + ante.NewSetPubKeyDecorator(options.AccountKeeper), // SetPubKeyDecorator must be called before all signature verification decorators ante.NewValidateSigCountDecorator(options.AccountKeeper), - ante.NewSigGasConsumeDecorator(options.AccountKeeper, sigGasConsumer), + ante.NewSigGasConsumeDecorator(options.AccountKeeper, options.SigGasConsumer), ante.NewSigVerificationDecorator(options.AccountKeeper, options.SignModeHandler), ante.NewIncrementSequenceDecorator(options.AccountKeeper), - ibcante.NewAnteDecorator(options.IBCKeeper), + ibcante.NewRedundantRelayDecorator(options.IBCKeeper), } return sdk.ChainAnteDecorators(anteDecorators...), nil diff --git a/app/app.go b/app/app.go index 6d646c3..a9d5c9a 100644 --- a/app/app.go +++ b/app/app.go @@ -1,29 +1,43 @@ package app import ( + "encoding/json" "fmt" "io" - "net/http" "os" "path/filepath" "strings" + autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" + reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" + + dbm "github.com/cometbft/cometbft-db" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/log" + tmos "github.com/cometbft/cometbft/libs/os" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + nodeservice "github.com/cosmos/cosmos-sdk/client/grpc/node" "github.com/cosmos/cosmos-sdk/client/grpc/tmservice" - "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" + runtimeservices "github.com/cosmos/cosmos-sdk/runtime/services" + "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" - "github.com/cosmos/cosmos-sdk/simapp" + "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/module" + "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" "github.com/cosmos/cosmos-sdk/x/auth/ante" - authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + "github.com/cosmos/cosmos-sdk/x/auth/posthandler" authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -38,11 +52,13 @@ import ( "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/consensus" + consensusparamkeeper "github.com/cosmos/cosmos-sdk/x/consensus/keeper" + consensusparamtypes "github.com/cosmos/cosmos-sdk/x/consensus/types" "github.com/cosmos/cosmos-sdk/x/crisis" crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" distr "github.com/cosmos/cosmos-sdk/x/distribution" - distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client" distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/evidence" @@ -56,9 +72,16 @@ import ( "github.com/cosmos/cosmos-sdk/x/gov" govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" + "github.com/cosmos/cosmos-sdk/x/group" + groupkeeper "github.com/cosmos/cosmos-sdk/x/group/keeper" + groupmodule "github.com/cosmos/cosmos-sdk/x/group/module" "github.com/cosmos/cosmos-sdk/x/mint" mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + "github.com/cosmos/cosmos-sdk/x/nft" + nftkeeper "github.com/cosmos/cosmos-sdk/x/nft/keeper" + nftmodule "github.com/cosmos/cosmos-sdk/x/nft/module" "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" @@ -74,62 +97,52 @@ import ( 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" - ica "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts" - icacontroller "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/controller" - icacontrollerkeeper "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/controller/keeper" - icacontrollertypes "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/controller/types" - icahost "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/host" - icahostkeeper "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/host/keeper" - icahosttypes "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/host/types" - icatypes "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/types" - ibcfee "github.com/cosmos/ibc-go/v4/modules/apps/29-fee" - ibcfeekeeper "github.com/cosmos/ibc-go/v4/modules/apps/29-fee/keeper" - ibcfeetypes "github.com/cosmos/ibc-go/v4/modules/apps/29-fee/types" - transfer "github.com/cosmos/ibc-go/v4/modules/apps/transfer" - ibctransferkeeper "github.com/cosmos/ibc-go/v4/modules/apps/transfer/keeper" - ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - ibc "github.com/cosmos/ibc-go/v4/modules/core" - ibcclient "github.com/cosmos/ibc-go/v4/modules/core/02-client" - ibcclientclient "github.com/cosmos/ibc-go/v4/modules/core/02-client/client" - ibcclienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - porttypes "github.com/cosmos/ibc-go/v4/modules/core/05-port/types" - ibchost "github.com/cosmos/ibc-go/v4/modules/core/24-host" - ibckeeper "github.com/cosmos/ibc-go/v4/modules/core/keeper" - - // Note: please do your research before using this in production app, this is a demo and not an officially - // supported IBC team implementation. It has no known issues, but do your own research before using it. - intertx "github.com/cosmos/interchain-accounts/x/inter-tx" - intertxkeeper "github.com/cosmos/interchain-accounts/x/inter-tx/keeper" - intertxtypes "github.com/cosmos/interchain-accounts/x/inter-tx/types" - "github.com/gorilla/mux" - "github.com/rakyll/statik/fs" + ica "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts" + icacontroller "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller" + icacontrollerkeeper "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/keeper" + icacontrollertypes "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/controller/types" + icahost "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host" + icahostkeeper "github.com/cosmos/ibc-go/v7/modules/apps/27-interchain-accounts/host/keeper" + 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" + ibcfee "github.com/cosmos/ibc-go/v7/modules/apps/29-fee" + ibcfeekeeper "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/keeper" + ibcfeetypes "github.com/cosmos/ibc-go/v7/modules/apps/29-fee/types" + transfer "github.com/cosmos/ibc-go/v7/modules/apps/transfer" + ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper" + ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" + ibc "github.com/cosmos/ibc-go/v7/modules/core" + 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" + 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/spf13/cast" - abci "github.com/tendermint/tendermint/abci/types" - tmjson "github.com/tendermint/tendermint/libs/json" - "github.com/tendermint/tendermint/libs/log" - tmos "github.com/tendermint/tendermint/libs/os" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" - - store "github.com/cosmos/cosmos-sdk/store/types" - wasmappparams "github.com/terpnetwork/terp-core/app/params" + + govclient "github.com/cosmos/cosmos-sdk/x/gov/client" + "github.com/terpnetwork/terp-core/x/wasm" - wasmclient "github.com/terpnetwork/terp-core/x/wasm/client" wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" + wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" - //BCNA Module - - terpmodule "github.com/terpnetwork/terp-core/x/terp" - terpmodulekeeper "github.com/terpnetwork/terp-core/x/terp/keeper" - terpmoduletypes "github.com/terpnetwork/terp-core/x/terp/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" // unnamed import of statik for swagger UI support - _ "github.com/cosmos/cosmos-sdk/client/docs/statik" + _ "github.com/cosmos/cosmos-sdk/client/docs/statik" // statik for swagger UI support ) const ( - appName = "TerpApp" - v040UpgradeName = "v040" + appName = "TerpApp" + MockFeePort string = ibcmock.ModuleName + ibcfeetypes.ModuleName ) // We pull these out so we can set them with LDFLAGS in the Makefile @@ -142,12 +155,12 @@ var ( ProposalsEnabled = "true" // If set to non-empty string it must be comma-separated list of values that are all a subset // of "EnableAllProposals" (takes precedence over ProposalsEnabled) - // https://github.com/CosmWasm/wasmd/blob/02a54d33ff2c064f3539ae12d75d027d9c665f05/x/wasm/internal/types/proposal.go#L28-L34 + // https://github.com/terpnetwork/terp-core/blob/02a54d33ff2c064f3539ae12d75d027d9c665f05/x/wasm/internal/types/proposal.go#L28-L34 EnableSpecificProposals = "" ) // GetEnabledProposals parses the ProposalsEnabled / EnableSpecificProposals values to -// produce a list of enabled proposals to pass into terpd app. +// produce a list of enabled proposals to pass into wasmd app. func GetEnabledProposals() []wasm.ProposalType { if EnableSpecificProposals == "" { if ProposalsEnabled == "true" { @@ -190,38 +203,40 @@ var ( // and genesis verification. ModuleBasics = module.NewBasicManager( auth.AppModuleBasic{}, - genutil.AppModuleBasic{}, + genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), bank.AppModuleBasic{}, capability.AppModuleBasic{}, staking.AppModuleBasic{}, mint.AppModuleBasic{}, distr.AppModuleBasic{}, gov.NewAppModuleBasic( - append( - wasmclient.ProposalHandlers, //nolint:staticcheck + []govclient.ProposalHandler{ paramsclient.ProposalHandler, - distrclient.ProposalHandler, - upgradeclient.ProposalHandler, - upgradeclient.CancelProposalHandler, + upgradeclient.LegacyProposalHandler, + upgradeclient.LegacyCancelProposalHandler, ibcclientclient.UpdateClientProposalHandler, ibcclientclient.UpgradeProposalHandler, - )..., + }, ), params.AppModuleBasic{}, crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, feegrantmodule.AppModuleBasic{}, - authzmodule.AppModuleBasic{}, - ibc.AppModuleBasic{}, upgrade.AppModuleBasic{}, evidence.AppModuleBasic{}, - transfer.AppModuleBasic{}, + authzmodule.AppModuleBasic{}, + groupmodule.AppModuleBasic{}, vesting.AppModuleBasic{}, + nftmodule.AppModuleBasic{}, + consensus.AppModuleBasic{}, + // non sdk modules wasm.AppModuleBasic{}, - terpmodule.AppModuleBasic{}, + ibc.AppModuleBasic{}, + ibctm.AppModuleBasic{}, + transfer.AppModuleBasic{}, ica.AppModuleBasic{}, - intertx.AppModuleBasic{}, ibcfee.AppModuleBasic{}, + tokenfactory.AppModuleBasic{}, ) // module account permissions @@ -232,66 +247,70 @@ var ( stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, govtypes.ModuleName: {authtypes.Burner}, + nft.ModuleName: nil, ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, ibcfeetypes.ModuleName: nil, icatypes.ModuleName: nil, wasm.ModuleName: {authtypes.Burner}, + tokenfactorytypes.ModuleName: {authtypes.Minter, authtypes.Burner}, } ) var ( - _ simapp.App = (*TerpApp)(nil) + _ runtime.AppI = (*TerpApp)(nil) _ servertypes.Application = (*TerpApp)(nil) ) // TerpApp extended ABCI application type TerpApp struct { *baseapp.BaseApp - legacyAmino *codec.LegacyAmino //nolint:staticcheck + legacyAmino *codec.LegacyAmino appCodec codec.Codec + txConfig client.TxConfig interfaceRegistry types.InterfaceRegistry - invCheckPeriod uint - // keys to access the substores - keys map[string]*sdk.KVStoreKey - tkeys map[string]*sdk.TransientStoreKey - memKeys map[string]*sdk.MemoryStoreKey + keys map[string]*storetypes.KVStoreKey + tkeys map[string]*storetypes.TransientStoreKey + memKeys map[string]*storetypes.MemoryStoreKey // keepers - AccountKeeper authkeeper.AccountKeeper - BankKeeper bankkeeper.Keeper - CapabilityKeeper *capabilitykeeper.Keeper - StakingKeeper stakingkeeper.Keeper - SlashingKeeper slashingkeeper.Keeper - MintKeeper mintkeeper.Keeper - DistrKeeper distrkeeper.Keeper - GovKeeper govkeeper.Keeper - CrisisKeeper crisiskeeper.Keeper - UpgradeKeeper upgradekeeper.Keeper - ParamsKeeper paramskeeper.Keeper - EvidenceKeeper evidencekeeper.Keeper + AccountKeeper authkeeper.AccountKeeper + AuthzKeeper authzkeeper.Keeper + BankKeeper bankkeeper.BaseKeeper + + CapabilityKeeper *capabilitykeeper.Keeper + StakingKeeper *stakingkeeper.Keeper + SlashingKeeper slashingkeeper.Keeper + MintKeeper mintkeeper.Keeper + DistrKeeper distrkeeper.Keeper + GovKeeper govkeeper.Keeper + CrisisKeeper *crisiskeeper.Keeper + UpgradeKeeper *upgradekeeper.Keeper + ParamsKeeper paramskeeper.Keeper + EvidenceKeeper evidencekeeper.Keeper + FeeGrantKeeper feegrantkeeper.Keeper + GroupKeeper groupkeeper.Keeper + NFTKeeper nftkeeper.Keeper + ConsensusParamsKeeper consensusparamkeeper.Keeper + IBCKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly IBCFeeKeeper ibcfeekeeper.Keeper ICAControllerKeeper icacontrollerkeeper.Keeper + TokenFactoryKeeper tokenfactorykeeper.Keeper ICAHostKeeper icahostkeeper.Keeper - InterTxKeeper intertxkeeper.Keeper TransferKeeper ibctransferkeeper.Keeper - FeeGrantKeeper feegrantkeeper.Keeper - AuthzKeeper authzkeeper.Keeper WasmKeeper wasm.Keeper - TerpKeeper terpmodulekeeper.Keeper ScopedIBCKeeper capabilitykeeper.ScopedKeeper ScopedICAHostKeeper capabilitykeeper.ScopedKeeper ScopedICAControllerKeeper capabilitykeeper.ScopedKeeper - ScopedInterTxKeeper capabilitykeeper.ScopedKeeper ScopedTransferKeeper capabilitykeeper.ScopedKeeper ScopedIBCFeeKeeper capabilitykeeper.ScopedKeeper ScopedWasmKeeper capabilitykeeper.ScopedKeeper // the module manager - mm *module.Manager + ModuleManager *module.Manager // simulation manager sm *module.SimulationManager @@ -306,39 +325,66 @@ func NewTerpApp( db dbm.DB, traceStore io.Writer, loadLatest bool, - skipUpgradeHeights map[int64]bool, - homePath string, - invCheckPeriod uint, - encodingConfig wasmappparams.EncodingConfig, enabledProposals []wasm.ProposalType, appOpts servertypes.AppOptions, wasmOpts []wasm.Option, baseAppOptions ...func(*baseapp.BaseApp), ) *TerpApp { + encodingConfig := MakeEncodingConfig() + appCodec, legacyAmino := encodingConfig.Marshaler, encodingConfig.Amino interfaceRegistry := encodingConfig.InterfaceRegistry + txConfig := encodingConfig.TxConfig - bApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...) + bApp := baseapp.NewBaseApp(appName, logger, db, txConfig.TxDecoder(), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) + bApp.SetVersion(version.Version) bApp.SetInterfaceRegistry(interfaceRegistry) + bApp.SetTxEncoder(txConfig.TxEncoder()) keys := sdk.NewKVStoreKeys( - authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, - minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, - govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, - evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey, terpmoduletypes.StoreKey, - feegrant.StoreKey, authzkeeper.StoreKey, wasm.StoreKey, icahosttypes.StoreKey, - icacontrollertypes.StoreKey, intertxtypes.StoreKey, ibcfeetypes.StoreKey, + authtypes.StoreKey, + banktypes.StoreKey, + stakingtypes.StoreKey, + crisistypes.StoreKey, + minttypes.StoreKey, + distrtypes.StoreKey, + slashingtypes.StoreKey, + govtypes.StoreKey, + paramstypes.StoreKey, + consensusparamtypes.StoreKey, + upgradetypes.StoreKey, + feegrant.StoreKey, + evidencetypes.StoreKey, + capabilitytypes.StoreKey, + authzkeeper.StoreKey, + nftkeeper.StoreKey, + group.StoreKey, + // non sdk store keys + ibcexported.StoreKey, + ibctransfertypes.StoreKey, + ibcfeetypes.StoreKey, + wasm.StoreKey, + icahosttypes.StoreKey, + icacontrollertypes.StoreKey, + tokenfactorytypes.StoreKey, ) + tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) + // load state streaming if enabled + if _, _, err := streaming.LoadStreamingServices(bApp, appOpts, appCodec, logger, keys); err != nil { + logger.Error("failed to load state streaming", "err", err) + os.Exit(1) + } + app := &TerpApp{ BaseApp: bApp, legacyAmino: legacyAmino, appCodec: appCodec, + txConfig: txConfig, interfaceRegistry: interfaceRegistry, - invCheckPeriod: invCheckPeriod, keys: keys, tkeys: tkeys, memKeys: memKeys, @@ -352,7 +398,8 @@ func NewTerpApp( ) // set the BaseApp's parameter store - bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramskeeper.ConsensusParamsKeyTable())) + app.ConsensusParamsKeeper = consensusparamkeeper.NewKeeper(appCodec, keys[consensusparamtypes.StoreKey], authtypes.NewModuleAddress(govtypes.ModuleName).String()) + bApp.SetParamStore(&app.ConsensusParamsKeeper) // add capability keeper and ScopeToModule for ibc module app.CapabilityKeeper = capabilitykeeper.NewKeeper( @@ -360,10 +407,10 @@ func NewTerpApp( keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey], ) - scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibchost.ModuleName) + + scopedIBCKeeper := app.CapabilityKeeper.ScopeToModule(ibcexported.ModuleName) scopedICAHostKeeper := app.CapabilityKeeper.ScopeToModule(icahosttypes.SubModuleName) scopedICAControllerKeeper := app.CapabilityKeeper.ScopeToModule(icacontrollertypes.SubModuleName) - scopedInterTxKeeper := app.CapabilityKeeper.ScopeToModule(intertxtypes.ModuleName) scopedTransferKeeper := app.CapabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) scopedWasmKeeper := app.CapabilityKeeper.ScopeToModule(wasm.ModuleName) app.CapabilityKeeper.Seal() @@ -372,100 +419,170 @@ func NewTerpApp( app.AccountKeeper = authkeeper.NewAccountKeeper( appCodec, keys[authtypes.StoreKey], - app.getSubspace(authtypes.ModuleName), authtypes.ProtoBaseAccount, maccPerms, + Bech32Prefix, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) app.BankKeeper = bankkeeper.NewBaseKeeper( appCodec, keys[banktypes.StoreKey], app.AccountKeeper, - app.getSubspace(banktypes.ModuleName), - app.ModuleAccountAddrs(), + BlockedAddresses(), + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) - app.AuthzKeeper = authzkeeper.NewKeeper( - keys[authzkeeper.StoreKey], + app.StakingKeeper = stakingkeeper.NewKeeper( appCodec, - app.BaseApp.MsgServiceRouter(), + keys[stakingtypes.StoreKey], + app.AccountKeeper, + app.BankKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) app.FeeGrantKeeper = feegrantkeeper.NewKeeper( appCodec, keys[feegrant.StoreKey], app.AccountKeeper, ) - stakingKeeper := stakingkeeper.NewKeeper( - appCodec, - keys[stakingtypes.StoreKey], - app.AccountKeeper, - app.BankKeeper, - app.getSubspace(stakingtypes.ModuleName), - ) + app.MintKeeper = mintkeeper.NewKeeper( appCodec, keys[minttypes.StoreKey], - app.getSubspace(minttypes.ModuleName), - &stakingKeeper, + app.StakingKeeper, app.AccountKeeper, app.BankKeeper, authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) app.DistrKeeper = distrkeeper.NewKeeper( appCodec, keys[distrtypes.StoreKey], - app.getSubspace(distrtypes.ModuleName), app.AccountKeeper, app.BankKeeper, - &stakingKeeper, + app.StakingKeeper, authtypes.FeeCollectorName, - app.ModuleAccountAddrs(), + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + app.SlashingKeeper = slashingkeeper.NewKeeper( appCodec, + legacyAmino, keys[slashingtypes.StoreKey], - &stakingKeeper, - app.getSubspace(slashingtypes.ModuleName), + app.StakingKeeper, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + app.TokenFactoryKeeper = tokenfactorykeeper.NewKeeper( + keys[tokenfactorytypes.StoreKey], + app.GetSubspace(tokenfactorytypes.ModuleName), + app.AccountKeeper, + app.BankKeeper, + app.DistrKeeper, ) + + invCheckPeriod := cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)) app.CrisisKeeper = crisiskeeper.NewKeeper( - app.getSubspace(crisistypes.ModuleName), + appCodec, + keys[crisistypes.StoreKey], invCheckPeriod, app.BankKeeper, authtypes.FeeCollectorName, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + + 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) + + groupConfig := group.DefaultConfig() + /* + Example of setting group params: + groupConfig.MaxMetadataLen = 1000 + */ + app.GroupKeeper = groupkeeper.NewKeeper(keys[group.StoreKey], appCodec, app.MsgServiceRouter(), app.AccountKeeper, groupConfig) + + // get skipUpgradeHeights from the app options + skipUpgradeHeights := map[int64]bool{} + for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { + skipUpgradeHeights[int64(h)] = true + } + homePath := cast.ToString(appOpts.Get(flags.FlagHome)) + // set the governance module account as the authority for conducting upgrades app.UpgradeKeeper = upgradekeeper.NewKeeper( skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, homePath, app.BaseApp, - ) - - // register the staking hooks - // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks - app.StakingKeeper = *stakingKeeper.SetHooks( - stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) app.IBCKeeper = ibckeeper.NewKeeper( appCodec, - keys[ibchost.StoreKey], - app.getSubspace(ibchost.ModuleName), + keys[ibcexported.StoreKey], + app.GetSubspace(ibcexported.ModuleName), app.StakingKeeper, app.UpgradeKeeper, scopedIBCKeeper, ) - // register the proposal types - govRouter := govtypes.NewRouter() - govRouter. - AddRoute(govtypes.RouterKey, govtypes.ProposalHandler). - AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). - AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)). + // Register the proposal types + // Deprecated: Avoid adding new handlers, instead use the new proposal flow + // by granting the governance module the right to execute the message. + // See: https://docs.cosmos.network/main/modules/gov#proposal-messages + govRouter := govv1beta1.NewRouter() + govRouter.AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). // This should be removed. It is still in place to avoid failures of modules that have not yet been upgraded. AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper)). AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper)) + govConfig := govtypes.DefaultConfig() + /* + Example of setting gov params: + govConfig.MaxMetadataLen = 10000 + */ + govKeeper := govkeeper.NewKeeper( + appCodec, + keys[govtypes.StoreKey], + app.AccountKeeper, + app.BankKeeper, + app.StakingKeeper, + app.MsgServiceRouter(), + govConfig, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), + ) + + app.GovKeeper = *govKeeper.SetHooks( + govtypes.NewMultiGovHooks( + // register the governance hooks + ), + ) + + app.NFTKeeper = nftkeeper.NewKeeper( + keys[nftkeeper.StoreKey], + appCodec, + app.AccountKeeper, + app.BankKeeper, + ) + + // create evidence keeper with router + evidenceKeeper := evidencekeeper.NewKeeper( + appCodec, + keys[evidencetypes.StoreKey], + app.StakingKeeper, + app.SlashingKeeper, + ) + // If evidence needs to be handled for the app, set routes in router here and seal + app.EvidenceKeeper = *evidenceKeeper + // IBC Fee Module keeper app.IBCFeeKeeper = ibcfeekeeper.NewKeeper( - appCodec, keys[ibcfeetypes.StoreKey], app.getSubspace(ibcfeetypes.ModuleName), + appCodec, keys[ibcfeetypes.StoreKey], app.IBCKeeper.ChannelKeeper, // may be replaced with IBC middleware app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, @@ -475,7 +592,7 @@ func NewTerpApp( app.TransferKeeper = ibctransferkeeper.NewKeeper( appCodec, keys[ibctransfertypes.StoreKey], - app.getSubspace(ibctransfertypes.ModuleName), + app.GetSubspace(ibctransfertypes.ModuleName), app.IBCFeeKeeper, // ISC4 Wrapper: fee IBC middleware app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, @@ -484,10 +601,19 @@ 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.IBCKeeper.ChannelKeeper, + &app.IBCKeeper.PortKeeper, app.AccountKeeper, app.BankKeeper, + ) + app.ICAHostKeeper = icahostkeeper.NewKeeper( appCodec, keys[icahosttypes.StoreKey], - app.getSubspace(icahosttypes.SubModuleName), + app.GetSubspace(icahosttypes.SubModuleName), + app.IBCFeeKeeper, // use ics29 fee as ics4Wrapper in middleware stack app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, app.AccountKeeper, @@ -497,7 +623,7 @@ func NewTerpApp( app.ICAControllerKeeper = icacontrollerkeeper.NewKeeper( appCodec, keys[icacontrollertypes.StoreKey], - app.getSubspace(icacontrollertypes.SubModuleName), + app.GetSubspace(icacontrollertypes.SubModuleName), app.IBCFeeKeeper, // use ics29 fee as ics4Wrapper in middleware stack app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, @@ -505,43 +631,24 @@ func NewTerpApp( app.MsgServiceRouter(), ) - // For terpd we use the demo controller from https://github.com/cosmos/interchain-accounts but see notes below - app.InterTxKeeper = intertxkeeper.NewKeeper(appCodec, keys[intertxtypes.StoreKey], app.ICAControllerKeeper, scopedInterTxKeeper) - - // create evidence keeper with router - evidenceKeeper := evidencekeeper.NewKeeper( - appCodec, - keys[evidencetypes.StoreKey], - &app.StakingKeeper, - app.SlashingKeeper, - ) - app.EvidenceKeeper = *evidenceKeeper - wasmDir := filepath.Join(homePath, "wasm") wasmConfig, err := wasm.ReadWasmConfig(appOpts) if err != nil { panic(fmt.Sprintf("error while reading wasm config: %s", err)) } - app.TerpKeeper = *terpmodulekeeper.NewKeeper( - appCodec, - keys[terpmoduletypes.StoreKey], - keys[terpmoduletypes.MemStoreKey], - app.getSubspace(terpmoduletypes.ModuleName), - ) - terpModule := terpmodule.NewAppModule(appCodec, app.TerpKeeper, app.AccountKeeper, app.BankKeeper) - // The last arguments can contain custom message handlers, and custom query handlers, // if we want to allow any custom callbacks - availableCapabilities := "iterator,staking,stargate,cosmwasm_1_1" + // 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( appCodec, keys[wasm.StoreKey], - app.getSubspace(wasm.ModuleName), app.AccountKeeper, app.BankKeeper, app.StakingKeeper, - app.DistrKeeper, + distrkeeper.NewQuerier(app.DistrKeeper), app.IBCKeeper.ChannelKeeper, &app.IBCKeeper.PortKeeper, scopedWasmKeeper, @@ -551,6 +658,7 @@ func NewTerpApp( wasmDir, wasmConfig, availableCapabilities, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), wasmOpts..., ) @@ -558,6 +666,8 @@ func NewTerpApp( if len(enabledProposals) != 0 { govRouter.AddRoute(wasm.RouterKey, wasm.NewWasmProposalHandler(app.WasmKeeper, enabledProposals)) } + // Set legacy router for backwards compatibility with gov v1beta1 + app.GovKeeper.SetLegacyRouter(govRouter) // Create Transfer Stack var transferStack porttypes.IBCModule @@ -567,13 +677,11 @@ func NewTerpApp( // Create Interchain Accounts Stack // SendPacket, since it is originating from the application to core IBC: // icaAuthModuleKeeper.SendTx -> icaController.SendPacket -> fee.SendPacket -> channel.SendPacket - - // Note: please do your research before using this in production app, this is a demo and not an officially - // supported IBC team implementation. Do your own research before using it. var icaControllerStack porttypes.IBCModule - // You will likely want to use your own reviewed and maintained ica auth module - icaControllerStack = intertx.NewIBCModule(app.InterTxKeeper) - icaControllerStack = icacontroller.NewIBCMiddleware(icaControllerStack, app.ICAControllerKeeper) + // integration point for custom authentication modules + // see https://medium.com/the-interchain-foundation/ibc-go-v6-changes-to-interchain-accounts-and-how-it-impacts-your-chain-806c185300d7 + var noAuthzModule porttypes.IBCModule + icaControllerStack = icacontroller.NewIBCMiddleware(noAuthzModule, app.ICAControllerKeeper) icaControllerStack = ibcfee.NewIBCMiddleware(icaControllerStack, app.IBCFeeKeeper) // RecvPacket, message that originates from core IBC and goes down to app, the flow is: @@ -591,20 +699,10 @@ func NewTerpApp( ibcRouter := porttypes.NewRouter(). AddRoute(ibctransfertypes.ModuleName, transferStack). AddRoute(wasm.ModuleName, wasmStack). - AddRoute(intertxtypes.ModuleName, icaControllerStack). AddRoute(icacontrollertypes.SubModuleName, icaControllerStack). AddRoute(icahosttypes.SubModuleName, icaHostStack) app.IBCKeeper.SetRouter(ibcRouter) - app.GovKeeper = govkeeper.NewKeeper( - appCodec, - keys[govtypes.StoreKey], - app.getSubspace(govtypes.ModuleName), - app.AccountKeeper, - app.BankKeeper, - &stakingKeeper, - govRouter, - ) /**** Module Options ****/ // NOTE: we may consider parsing `appOpts` inside module constructors. For the moment @@ -613,195 +711,148 @@ func NewTerpApp( // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. - app.mm = module.NewManager( + app.ModuleManager = module.NewManager( genutil.NewAppModule( app.AccountKeeper, app.StakingKeeper, app.BaseApp.DeliverTx, encodingConfig.TxConfig, ), - auth.NewAppModule(appCodec, app.AccountKeeper, nil), + auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), vesting.NewAppModule(app.AccountKeeper, app.BankKeeper), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), - capability.NewAppModule(appCodec, *app.CapabilityKeeper), - gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), + bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper, app.GetSubspace(banktypes.ModuleName)), + capability.NewAppModule(appCodec, *app.CapabilityKeeper, false), + feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), + gov.NewAppModule(appCodec, &app.GovKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(govtypes.ModuleName)), + mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil, app.GetSubspace(minttypes.ModuleName)), + slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(slashingtypes.ModuleName)), + distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper, app.GetSubspace(distrtypes.ModuleName)), + staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName)), upgrade.NewAppModule(app.UpgradeKeeper), - wasm.NewAppModule(appCodec, &app.WasmKeeper, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), evidence.NewAppModule(app.EvidenceKeeper), - feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), + params.NewAppModule(app.ParamsKeeper), authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), + 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), + wasm.NewAppModule(appCodec, &app.WasmKeeper, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.MsgServiceRouter(), app.GetSubspace(wasmtypes.ModuleName)), ibc.NewAppModule(app.IBCKeeper), - params.NewAppModule(app.ParamsKeeper), transfer.NewAppModule(app.TransferKeeper), ibcfee.NewAppModule(app.IBCFeeKeeper), ica.NewAppModule(&app.ICAControllerKeeper, &app.ICAHostKeeper), - intertx.NewAppModule(appCodec, app.InterTxKeeper), - terpModule, - crisis.NewAppModule(&app.CrisisKeeper, skipGenesisInvariants), // always be last to make sure that it checks for all invariants and not only part of them + 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 ) // During begin block slashing happens after distr.BeginBlocker so that // there is nothing left over in the validator fee pool, so as to keep the // CanWithdrawInvariant invariant. // NOTE: staking module is required if HistoricalEntries param > 0 - app.mm.SetOrderBeginBlockers( - upgradetypes.ModuleName, - capabilitytypes.ModuleName, - minttypes.ModuleName, - distrtypes.ModuleName, - slashingtypes.ModuleName, - evidencetypes.ModuleName, - stakingtypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - govtypes.ModuleName, - crisistypes.ModuleName, - genutiltypes.ModuleName, - authz.ModuleName, - feegrant.ModuleName, - paramstypes.ModuleName, - vestingtypes.ModuleName, + // NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC) + app.ModuleManager.SetOrderBeginBlockers( + upgradetypes.ModuleName, capabilitytypes.ModuleName, minttypes.ModuleName, distrtypes.ModuleName, slashingtypes.ModuleName, + evidencetypes.ModuleName, stakingtypes.ModuleName, + authtypes.ModuleName, banktypes.ModuleName, govtypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, + authz.ModuleName, feegrant.ModuleName, nft.ModuleName, group.ModuleName, + paramstypes.ModuleName, vestingtypes.ModuleName, consensusparamtypes.ModuleName, // additional non simd modules ibctransfertypes.ModuleName, - ibchost.ModuleName, + ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, - intertxtypes.ModuleName, + tokenfactorytypes.ModuleName, wasm.ModuleName, - terpmoduletypes.ModuleName, - ) - - app.mm.SetOrderEndBlockers( - crisistypes.ModuleName, - govtypes.ModuleName, - stakingtypes.ModuleName, - capabilitytypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - slashingtypes.ModuleName, - minttypes.ModuleName, - genutiltypes.ModuleName, - evidencetypes.ModuleName, - authz.ModuleName, - feegrant.ModuleName, - paramstypes.ModuleName, - upgradetypes.ModuleName, - vestingtypes.ModuleName, + ) + + app.ModuleManager.SetOrderEndBlockers( + crisistypes.ModuleName, govtypes.ModuleName, stakingtypes.ModuleName, + capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, + slashingtypes.ModuleName, minttypes.ModuleName, + genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, + feegrant.ModuleName, nft.ModuleName, group.ModuleName, + paramstypes.ModuleName, upgradetypes.ModuleName, vestingtypes.ModuleName, consensusparamtypes.ModuleName, // additional non simd modules ibctransfertypes.ModuleName, - ibchost.ModuleName, + ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, - intertxtypes.ModuleName, + tokenfactorytypes.ModuleName, wasm.ModuleName, - terpmoduletypes.ModuleName, ) // NOTE: The genutils module must occur after staking so that pools are // properly initialized with tokens from genesis accounts. + // NOTE: The genutils module must also occur after auth so that it can access the params from auth. // NOTE: Capability module must occur first so that it can initialize any capabilities // so that other modules that want to create or claim capabilities afterwards in InitChain // can do so safely. // NOTE: wasm module should be at the end as it can call other module functionality direct or via message dispatching during // genesis phase. For example bank transfer, auth account check, staking, ... - app.mm.SetOrderInitGenesis( - capabilitytypes.ModuleName, - authtypes.ModuleName, - banktypes.ModuleName, - distrtypes.ModuleName, - stakingtypes.ModuleName, - slashingtypes.ModuleName, - govtypes.ModuleName, - minttypes.ModuleName, - crisistypes.ModuleName, - genutiltypes.ModuleName, - evidencetypes.ModuleName, - authz.ModuleName, - feegrant.ModuleName, - paramstypes.ModuleName, - upgradetypes.ModuleName, - vestingtypes.ModuleName, + genesisModuleOrder := []string{ + capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, + distrtypes.ModuleName, stakingtypes.ModuleName, slashingtypes.ModuleName, govtypes.ModuleName, + minttypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName, + feegrant.ModuleName, nft.ModuleName, group.ModuleName, paramstypes.ModuleName, upgradetypes.ModuleName, + vestingtypes.ModuleName, consensusparamtypes.ModuleName, // additional non simd modules ibctransfertypes.ModuleName, - ibchost.ModuleName, + ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, - intertxtypes.ModuleName, // wasm after ibc transfer + tokenfactorytypes.ModuleName, wasm.ModuleName, - terpmoduletypes.ModuleName, - ) + } + app.ModuleManager.SetOrderInitGenesis(genesisModuleOrder...) + app.ModuleManager.SetOrderExportGenesis(genesisModuleOrder...) // Uncomment if you want to set a custom migration order here. - // app.mm.SetOrderMigrations(custom order) - - app.mm.RegisterInvariants(&app.CrisisKeeper) - app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino) + // app.ModuleManager.SetOrderMigrations(custom order) + app.ModuleManager.RegisterInvariants(app.CrisisKeeper) app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter()) - app.mm.RegisterServices(app.configurator) + app.ModuleManager.RegisterServices(app.configurator) + + // RegisterUpgradeHandlers is used for registering any on-chain upgrades. + // Make sure it's called after `app.ModuleManager` and `app.configurator` are set. + app.RegisterUpgradeHandlers() + + autocliv1.RegisterQueryServer(app.GRPCQueryRouter(), runtimeservices.NewAutoCLIQueryService(app.ModuleManager.Modules)) + + reflectionSvc, err := runtimeservices.NewReflectionService() + if err != nil { + panic(err) + } + reflectionv1.RegisterReflectionServiceServer(app.GRPCQueryRouter(), reflectionSvc) + + // add test gRPC service for testing gRPC queries in isolation + // testdata_pulsar.RegisterQueryServer(app.GRPCQueryRouter(), testdata_pulsar.QueryImpl{}) // create the simulation manager and define the order of the modules for deterministic simulations // - app.RegisterUpgradeHandlers(app.configurator) // NOTE: this is not required apps that don't use the simulator for fuzz testing // transactions - app.sm = module.NewSimulationManager( - auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts), - bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper), - capability.NewAppModule(appCodec, *app.CapabilityKeeper), - feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry), - authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry), - gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper), - mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper), - staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), - distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper), - params.NewAppModule(app.ParamsKeeper), - evidence.NewAppModule(app.EvidenceKeeper), - wasm.NewAppModule(appCodec, &app.WasmKeeper, app.StakingKeeper, app.AccountKeeper, app.BankKeeper), - ibc.NewAppModule(app.IBCKeeper), - transfer.NewAppModule(app.TransferKeeper), - terpModule, - ) + overrideModules := map[string]module.AppModuleSimulation{ + authtypes.ModuleName: auth.NewAppModule(app.appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts, app.GetSubspace(authtypes.ModuleName)), + } + app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) app.sm.RegisterStoreDecoders() + // initialize stores app.MountKVStores(keys) app.MountTransientStores(tkeys) app.MountMemoryStores(memKeys) - anteHandler, err := NewAnteHandler( - HandlerOptions{ - HandlerOptions: ante.HandlerOptions{ - AccountKeeper: app.AccountKeeper, - BankKeeper: app.BankKeeper, - FeegrantKeeper: app.FeeGrantKeeper, - SignModeHandler: encodingConfig.TxConfig.SignModeHandler(), - SigGasConsumer: ante.DefaultSigVerificationGasConsumer, - }, - IBCKeeper: app.IBCKeeper, - WasmConfig: &wasmConfig, - TXCounterStoreKey: keys[wasm.StoreKey], - }, - ) - if err != nil { - panic(fmt.Errorf("failed to create AnteHandler: %s", err)) - } - - app.SetAnteHandler(anteHandler) + // initialize BaseApp app.SetInitChainer(app.InitChainer) app.SetBeginBlocker(app.BeginBlocker) app.SetEndBlocker(app.EndBlocker) + app.setAnteHandler(encodingConfig.TxConfig, wasmConfig, keys[wasm.StoreKey]) // must be before Loading version // requires the snapshot store to be created and registered as a BaseAppOption - // see cmd/terpd/root.go: 206 - 214 approx + // see cmd/wasmd/root.go: 206 - 214 approx if manager := app.SnapshotManager(); manager != nil { err := manager.RegisterExtensions( wasmkeeper.NewWasmSnapshotter(app.CommitMultiStore(), &app.WasmKeeper), @@ -811,27 +862,56 @@ func NewTerpApp( } } - upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() - if err != nil { - panic(err) - } - - if upgradeInfo.Name == v040UpgradeName && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) { - storeUpgrades := store.StoreUpgrades{} - - // configure store loader that checks if version == upgradeHeight and applies store upgrades - app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) - } app.ScopedIBCKeeper = scopedIBCKeeper app.ScopedTransferKeeper = scopedTransferKeeper app.ScopedWasmKeeper = scopedWasmKeeper app.ScopedICAHostKeeper = scopedICAHostKeeper app.ScopedICAControllerKeeper = scopedICAControllerKeeper - app.ScopedInterTxKeeper = scopedInterTxKeeper + + // 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() + + // 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() if loadLatest { if err := app.LoadLatestVersion(); err != nil { - tmos.Exit(fmt.Sprintf("failed to load latest version: %s", err)) + logger.Error("error on loading last version", "err", err) + os.Exit(1) } ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{}) @@ -844,39 +924,63 @@ func NewTerpApp( return app } -// Name returns the name of the App -func (app *TerpApp) Name() string { return app.BaseApp.Name() } - -// ModuleManager returns instance -func (app *TerpApp) ModuleManager() module.Manager { - return *app.mm +func (app *TerpApp) setAnteHandler(txConfig client.TxConfig, wasmConfig wasmtypes.WasmConfig, txCounterStoreKey storetypes.StoreKey) { + anteHandler, err := NewAnteHandler( + HandlerOptions{ + HandlerOptions: ante.HandlerOptions{ + AccountKeeper: app.AccountKeeper, + BankKeeper: app.BankKeeper, + SignModeHandler: txConfig.SignModeHandler(), + FeegrantKeeper: app.FeeGrantKeeper, + SigGasConsumer: ante.DefaultSigVerificationGasConsumer, + }, + IBCKeeper: app.IBCKeeper, + WasmConfig: &wasmConfig, + TXCounterStoreKey: txCounterStoreKey, + }, + ) + if err != nil { + panic(fmt.Errorf("failed to create AnteHandler: %s", err)) + } + app.SetAnteHandler(anteHandler) } -// ModuleConfigurator returns instance -func (app *TerpApp) ModuleConfigurator() module.Configurator { - return app.configurator +func (app *TerpApp) setPostHandler() { + postHandler, err := posthandler.NewPostHandler( + posthandler.HandlerOptions{}, + ) + if err != nil { + panic(err) + } + + app.SetPostHandler(postHandler) } +// Name returns the name of the App +func (app *TerpApp) Name() string { return app.BaseApp.Name() } + // BeginBlocker application updates every begin block func (app *TerpApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock { - return app.mm.BeginBlock(ctx, req) + return app.ModuleManager.BeginBlock(ctx, req) } // EndBlocker application updates every end block func (app *TerpApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock { - return app.mm.EndBlock(ctx, req) + return app.ModuleManager.EndBlock(ctx, req) +} + +func (app *TerpApp) Configurator() module.Configurator { + return app.configurator } // InitChainer application update at chain initialization func (app *TerpApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { var genesisState GenesisState - if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil { + if err := json.Unmarshal(req.AppStateBytes, &genesisState); err != nil { panic(err) } - - app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()) - - return app.mm.InitGenesis(ctx, app.appCodec, genesisState) + app.UpgradeKeeper.SetModuleVersionMap(ctx, app.ModuleManager.GetVersionMap()) + return app.ModuleManager.InitGenesis(ctx, app.appCodec, genesisState) } // LoadHeight loads a particular height @@ -884,28 +988,62 @@ func (app *TerpApp) LoadHeight(height int64) error { return app.LoadVersion(height) } -// ModuleAccountAddrs returns all the app's module account addresses. -func (app *TerpApp) ModuleAccountAddrs() map[string]bool { - modAccAddrs := make(map[string]bool) - for acc := range maccPerms { - modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true - } - - return modAccAddrs -} - // LegacyAmino returns legacy amino codec. // // NOTE: This is solely to be used for testing purposes as it may be desirable // for modules to register their own custom testing types. -func (app *TerpApp) LegacyAmino() *codec.LegacyAmino { //nolint:staticcheck +func (app *TerpApp) LegacyAmino() *codec.LegacyAmino { return app.legacyAmino } -// getSubspace returns a param subspace for a given module name. +// AppCodec returns app codec. +// +// NOTE: This is solely to be used for testing purposes as it may be desirable +// for modules to register their own custom testing types. +func (app *TerpApp) AppCodec() codec.Codec { + return app.appCodec +} + +// InterfaceRegistry returns TerpApp's InterfaceRegistry +func (app *TerpApp) InterfaceRegistry() types.InterfaceRegistry { + return app.interfaceRegistry +} + +// TxConfig returns TerpApp's TxConfig +func (app *TerpApp) TxConfig() client.TxConfig { + return app.txConfig +} + +// DefaultGenesis returns a default genesis from the registered AppModuleBasic's. +func (app *TerpApp) DefaultGenesis() map[string]json.RawMessage { + return ModuleBasics.DefaultGenesis(app.appCodec) +} + +// GetKey returns the KVStoreKey for the provided store key. +// +// NOTE: This is solely to be used for testing purposes. +func (app *TerpApp) GetKey(storeKey string) *storetypes.KVStoreKey { + return app.keys[storeKey] +} + +// GetTKey returns the TransientStoreKey for the provided store key. // // NOTE: This is solely to be used for testing purposes. -func (app *TerpApp) getSubspace(moduleName string) paramstypes.Subspace { +func (app *TerpApp) GetTKey(storeKey string) *storetypes.TransientStoreKey { + return app.tkeys[storeKey] +} + +// GetMemKey returns the MemStoreKey for the provided mem key. +// +// NOTE: This is solely used for testing purposes. +func (app *TerpApp) GetMemKey(storeKey string) *storetypes.MemoryStoreKey { + return app.memKeys[storeKey] +} + +// GetSubspace returns a param subspace for a given module name. +// +// NOTE: This is solely to be used for testing purposes. +func (app *TerpApp) GetSubspace(moduleName string) paramstypes.Subspace { subspace, _ := app.ParamsKeeper.GetSubspace(moduleName) return subspace } @@ -919,21 +1057,21 @@ func (app *TerpApp) SimulationManager() *module.SimulationManager { // API server. func (app *TerpApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { clientCtx := apiSvr.ClientCtx - rpc.RegisterRoutes(clientCtx, apiSvr.Router) - // Register legacy tx routes. - authrest.RegisterTxRoutes(clientCtx, apiSvr.Router) // Register new tx routes from grpc-gateway. authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + // Register new tendermint queries routes from grpc-gateway. tmservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) - // Register legacy and grpc-gateway routes for all modules. - ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router) + // Register node gRPC service for grpc-gateway. + nodeservice.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) + + // Register grpc-gateway routes for all modules. ModuleBasics.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter) // register swagger API from root so that other applications can override easily - if apiConfig.Swagger { - RegisterSwaggerAPI(apiSvr.Router) + if err := server.RegisterSwaggerAPI(apiSvr.ClientCtx, apiSvr.Router, apiConfig.Swagger); err != nil { + panic(err) } } @@ -944,35 +1082,45 @@ func (app *TerpApp) RegisterTxService(clientCtx client.Context) { // RegisterTendermintService implements the Application.RegisterTendermintService method. func (app *TerpApp) RegisterTendermintService(clientCtx client.Context) { - tmservice.RegisterTendermintService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.interfaceRegistry) + tmservice.RegisterTendermintService( + clientCtx, + app.BaseApp.GRPCQueryRouter(), + app.interfaceRegistry, + app.Query, + ) } -func (app *TerpApp) AppCodec() codec.Codec { - return app.appCodec -} - -// RegisterSwaggerAPI registers swagger route with API Server -func RegisterSwaggerAPI(rtr *mux.Router) { - statikFS, err := fs.New() - if err != nil { - panic(err) - } - - staticServer := http.FileServer(statikFS) - rtr.PathPrefix("/swagger/").Handler(http.StripPrefix("/swagger/", staticServer)) +func (app *TerpApp) RegisterNodeService(clientCtx client.Context) { + nodeservice.RegisterNodeService(clientCtx, app.GRPCQueryRouter()) } // GetMaccPerms returns a copy of the module account permissions +// +// NOTE: This is solely to be used for testing purposes. func GetMaccPerms() map[string][]string { dupMaccPerms := make(map[string][]string) for k, v := range maccPerms { dupMaccPerms[k] = v } + return dupMaccPerms } +// BlockedAddresses returns all the app's blocked account addresses. +func BlockedAddresses() map[string]bool { + modAccAddrs := make(map[string]bool) + for acc := range GetMaccPerms() { + modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true + } + + // allow the following addresses to receive funds + delete(modAccAddrs, authtypes.NewModuleAddress(govtypes.ModuleName).String()) + + return modAccAddrs +} + // initParamsKeeper init params keeper and its subspaces -func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper { +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) @@ -981,22 +1129,14 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(minttypes.ModuleName) paramsKeeper.Subspace(distrtypes.ModuleName) paramsKeeper.Subspace(slashingtypes.ModuleName) - paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()) + paramsKeeper.Subspace(govtypes.ModuleName) paramsKeeper.Subspace(crisistypes.ModuleName) paramsKeeper.Subspace(ibctransfertypes.ModuleName) - paramsKeeper.Subspace(ibchost.ModuleName) - paramsKeeper.Subspace(terpmoduletypes.ModuleName) + paramsKeeper.Subspace(ibcexported.ModuleName) + paramsKeeper.Subspace(tokenfactorytypes.ModuleName) paramsKeeper.Subspace(icahosttypes.SubModuleName) paramsKeeper.Subspace(icacontrollertypes.SubModuleName) paramsKeeper.Subspace(wasm.ModuleName) return paramsKeeper } - -// RegisterUpgradeHandlers returns upgrade handlers -func (app *TerpApp) RegisterUpgradeHandlers(cfg module.Configurator) { - app.UpgradeKeeper.SetUpgradeHandler(v040UpgradeName, func(ctx sdk.Context, plan upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { - - return app.mm.RunMigrations(ctx, cfg, vm) - }) -} diff --git a/app/app_test.go b/app/app_test.go index 8311e15..f7f4ba3 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -1,55 +1,49 @@ package app import ( - "encoding/json" "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/tendermint/tendermint/libs/log" - db "github.com/tendermint/tm-db" - - abci "github.com/tendermint/tendermint/abci/types" "github.com/terpnetwork/terp-core/x/wasm" ) -var emptyWasmOpts []wasm.Option = nil - -func TestTerpdExport(t *testing.T) { - db := db.NewMemDB() - gapp := NewTerpApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, emptyWasmOpts) - - genesisState := NewDefaultGenesisState() - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - require.NoError(t, err) +var emptyWasmOpts []wasm.Option - // Initialize the chain - gapp.InitChain( - abci.RequestInitChain{ - Validators: []abci.ValidatorUpdate{}, - AppStateBytes: stateBytes, - }, - ) +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, map[int64]bool{}, DefaultNodeHome, 0, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, emptyWasmOpts) - _, err = newGapp.ExportAppStateAndValidators(false, []string{}) + 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) { - db := db.NewMemDB() - gapp := NewTerpApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, emptyWasmOpts) + gapp := Setup(t) - for acc := range maccPerms { + for acc := range BlockedAddresses() { t.Run(acc, func(t *testing.T) { - require.True(t, gapp.BankKeeper.BlockedAddr(gapp.AccountKeeper.GetModuleAddress(acc)), - "ensure that blocked addresses are properly set in bank keeper", - ) + 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") }) } } @@ -89,22 +83,3 @@ func TestGetEnabledProposals(t *testing.T) { }) } } - -func setGenesis(gapp *TerpApp) error { - genesisState := NewDefaultGenesisState() - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - if err != nil { - return err - } - - // Initialize the chain - gapp.InitChain( - abci.RequestInitChain{ - Validators: []abci.ValidatorUpdate{}, - AppStateBytes: stateBytes, - }, - ) - - gapp.Commit() - return nil -} diff --git a/app/apptesting/events.go b/app/apptesting/events.go new file mode 100644 index 0000000..f5a4349 --- /dev/null +++ b/app/apptesting/events.go @@ -0,0 +1,17 @@ +package apptesting + +import sdk "github.com/cosmos/cosmos-sdk/types" + +// AssertEventEmitted asserts that ctx's event manager has emitted the given number of events +// of the given type. +func (s *KeeperTestHelper) AssertEventEmitted(ctx sdk.Context, eventTypeExpected string, numEventsExpected int) { + allEvents := ctx.EventManager().Events() + // filter out other events + actualEvents := make([]sdk.Event, 0) + for _, event := range allEvents { + if event.Type == eventTypeExpected { + actualEvents = append(actualEvents, event) + } + } + s.Equal(numEventsExpected, len(actualEvents)) +} diff --git a/app/apptesting/test_suite.go b/app/apptesting/test_suite.go new file mode 100644 index 0000000..6974e77 --- /dev/null +++ b/app/apptesting/test_suite.go @@ -0,0 +1,299 @@ +package apptesting + +import ( + "encoding/json" + "fmt" + "os" + "testing" + "time" + + "cosmossdk.io/math" + 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" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/store/rootmulti" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" + "github.com/cosmos/cosmos-sdk/x/authz" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/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" + + 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" +) + +type KeeperTestHelper struct { + suite.Suite + + App *app.TerpApp + Ctx sdk.Context + QueryHelper *baseapp.QueryServiceTestHelper + TestAccs []sdk.AccAddress +} + +var ( + SecondaryDenom = "uthiol" + 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()}) + s.QueryHelper = &baseapp.QueryServiceTestHelper{ + GRPCQueryRouter: s.App.GRPCQueryRouter(), + Ctx: s.Ctx, + } + s.TestAccs = CreateRandomAccounts(3) +} + +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()), + }) + s.Ctx = s.App.BaseApp.NewContext(true, tmtypes.Header{}) +} + +// CreateTestContext creates a test context. +func (s *KeeperTestHelper) CreateTestContext() sdk.Context { + ctx, _ := s.CreateTestContextWithMultiStore() + return ctx +} + +// CreateTestContextWithMultiStore creates a test context and returns it together with multi store. +func (s *KeeperTestHelper) CreateTestContextWithMultiStore() (sdk.Context, sdk.CommitMultiStore) { + db := dbm.NewMemDB() + logger := log.NewNopLogger() + + ms := rootmulti.NewStore(db, logger) + + return sdk.NewContext(ms, tmtypes.Header{}, false, logger), ms +} + +// CreateTestContext creates a test context. +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)} + 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) + 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) + s.Require().NoError(err) +} + +func (s *KeeperTestHelper) MintCoins(coins sdk.Coins) { + err := s.App.BankKeeper.MintCoins(s.Ctx, minttypes.ModuleName, coins) + s.Require().NoError(err) +} + +// SetupValidator sets up a validator and returns the ValAddress. +func (s *KeeperTestHelper) SetupValidator(bondStatus stakingtypes.BondStatus) sdk.ValAddress { + 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}) + + s.FundAcc(sdk.AccAddress(valAddr), selfBond) + + stakingCoin := sdk.NewCoin(sdk.DefaultBondDenom, 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) + + val, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + s.Require().True(found) + + val = val.UpdateStatus(bondStatus) + s.App.StakingKeeper.SetValidator(s.Ctx, val) + + consAddr, err := val.GetConsAddr() + s.Suite.Require().NoError(err) + + signingInfo := slashingtypes.NewValidatorSigningInfo( + consAddr, + s.Ctx.BlockHeight(), + 0, + time.Unix(0, 0), + false, + 0, + ) + s.App.SlashingKeeper.SetValidatorSigningInfo(s.Ctx, consAddr, signingInfo) + + return valAddr +} + +// BeginNewBlock starts a new block. +func (s *KeeperTestHelper) BeginNewBlock() { + var valAddr []byte + + validators := s.App.StakingKeeper.GetAllValidators(s.Ctx) + if len(validators) >= 1 { + valAddrFancy, err := validators[0].GetConsAddr() + s.Require().NoError(err) + valAddr = valAddrFancy.Bytes() + } else { + valAddrFancy := s.SetupValidator(stakingtypes.Bonded) + validator, _ := s.App.StakingKeeper.GetValidator(s.Ctx, valAddrFancy) + valAddr2, _ := validator.GetConsAddr() + valAddr = valAddr2.Bytes() + } + + s.BeginNewBlockWithProposer(valAddr) +} + +// BeginNewBlockWithProposer begins a new block with a proposer. +func (s *KeeperTestHelper) BeginNewBlockWithProposer(proposer sdk.ValAddress) { + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, proposer) + s.Assert().True(found) + + valConsAddr, err := validator.GetConsAddr() + s.Require().NoError(err) + + valAddr := valConsAddr.Bytes() + + newBlockTime := s.Ctx.BlockTime().Add(5 * time.Second) + + header := tmtypes.Header{Height: s.Ctx.BlockHeight() + 1, Time: newBlockTime} + newCtx := s.Ctx.WithBlockTime(newBlockTime).WithBlockHeight(s.Ctx.BlockHeight() + 1) + s.Ctx = newCtx + lastCommitInfo := abci.CommitInfo{ + Votes: []abci.VoteInfo{{ + Validator: abci.Validator{Address: valAddr, Power: 1000}, + SignedLastBlock: true, + }}, + } + reqBeginBlock := abci.RequestBeginBlock{Header: header, LastCommitInfo: lastCommitInfo} + + fmt.Println("beginning block ", s.Ctx.BlockHeight()) + s.App.BeginBlocker(s.Ctx, reqBeginBlock) +} + +// EndBlock ends the block. +func (s *KeeperTestHelper) EndBlock() { + reqEndBlock := abci.RequestEndBlock{Height: s.Ctx.BlockHeight()} + s.App.EndBlocker(s.Ctx, reqEndBlock) +} + +// AllocateRewardsToValidator allocates reward tokens to a distribution module then allocates rewards to the validator address. +func (s *KeeperTestHelper) AllocateRewardsToValidator(valAddr sdk.ValAddress, rewardAmt math.Int) { + validator, found := s.App.StakingKeeper.GetValidator(s.Ctx, valAddr) + 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) + 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)}} + s.App.DistrKeeper.AllocateTokensToValidator(s.Ctx, validator, decTokens) +} + +// BuildTx builds a transaction. +func (s *KeeperTestHelper) BuildTx( + txBuilder client.TxBuilder, + msgs []sdk.Msg, + sigV2 signing.SignatureV2, + memo string, txFee sdk.Coins, + gasLimit uint64, +) authsigning.Tx { + err := txBuilder.SetMsgs(msgs[0]) + s.Require().NoError(err) + + err = txBuilder.SetSignatures(sigV2) + s.Require().NoError(err) + + txBuilder.SetMemo(memo) + txBuilder.SetFeeAmount(txFee) + txBuilder.SetGasLimit(gasLimit) + + return txBuilder.GetTx() +} + +// CreateRandomAccounts is a function return a list of randomly generated AccAddresses +func CreateRandomAccounts(numAccts int) []sdk.AccAddress { + testAddrs := make([]sdk.AccAddress, numAccts) + for i := 0; i < numAccts; i++ { + pk := ed25519.GenPrivKey().PubKey() + testAddrs[i] = sdk.AccAddress(pk.Address()) + } + + return testAddrs +} + +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" + ) + + var ( + mockMsgGrant authz.MsgGrant + mockMsgRevoke authz.MsgRevoke + mockMsgExec authz.MsgExec + ) + + // Authz: Grant Msg + typeURL := sdk.MsgTypeURL(msg) + grant, err := authz.NewGrant(someDate, authz.NewGenericAuthorization(typeURL), expire) + require.NoError(t, err) + + msgGrant := authz.MsgGrant{Granter: mockGranter, Grantee: mockGrantee, Grant: grant} + msgGrantBytes := json.RawMessage(sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msgGrant))) + err = authzcodec.ModuleCdc.UnmarshalJSON(msgGrantBytes, &mockMsgGrant) + require.NoError(t, err) + + // Authz: Revoke Msg + msgRevoke := authz.MsgRevoke{Granter: mockGranter, Grantee: mockGrantee, MsgTypeUrl: typeURL} + msgRevokeByte := json.RawMessage(sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msgRevoke))) + err = authzcodec.ModuleCdc.UnmarshalJSON(msgRevokeByte, &mockMsgRevoke) + require.NoError(t, err) + + // Authz: Exec Msg + msgAny, err := cdctypes.NewAnyWithValue(msg) + require.NoError(t, err) + msgExec := authz.MsgExec{Grantee: mockGrantee, Msgs: []*cdctypes.Any{msgAny}} + execMsgByte := json.RawMessage(sdk.MustSortJSON(authzcodec.ModuleCdc.MustMarshalJSON(&msgExec))) + err = authzcodec.ModuleCdc.UnmarshalJSON(execMsgByte, &mockMsgExec) + require.NoError(t, err) + require.Equal(t, msgExec.Msgs[0].Value, mockMsgExec.Msgs[0].Value) +} + +func GenerateTestAddrs() (string, string) { + pk1 := ed25519.GenPrivKey().PubKey() + validAddr := sdk.AccAddress(pk1.Address()).String() + invalidAddr := sdk.AccAddress("invalid").String() + return validAddr, invalidAddr +} diff --git a/app/export.go b/app/export.go index 2d4c2fc..ee366ac 100644 --- a/app/export.go +++ b/app/export.go @@ -2,9 +2,10 @@ package app import ( "encoding/json" + "fmt" "log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -15,9 +16,7 @@ import ( // ExportAppStateAndValidators exports the state of the application for a genesis // file. -func (app *TerpApp) ExportAppStateAndValidators( - forZeroHeight bool, jailAllowedAddrs []string, -) (servertypes.ExportedApp, error) { +func (app *TerpApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs []string, modulesToExport []string) (servertypes.ExportedApp, error) { // as if they could withdraw from the start of the next block ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) @@ -29,7 +28,7 @@ func (app *TerpApp) ExportAppStateAndValidators( app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs) } - genState := app.mm.ExportGenesis(ctx, app.appCodec) + genState := app.ModuleManager.ExportGenesisForModules(ctx, app.appCodec, modulesToExport) appState, err := json.MarshalIndent(genState, "", " ") if err != nil { return servertypes.ExportedApp{}, err @@ -73,7 +72,7 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ // withdraw all validator commission app.StakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { - _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) //nolint:errcheck + _, _ = app.DistrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) return false }) @@ -85,11 +84,11 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ panic(err) } - delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) - if err != nil { + delAddr := sdk.MustAccAddressFromBech32(delegation.DelegatorAddress) + + if _, err = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr); err != nil { panic(err) } - _, _ = app.DistrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) //nolint:errcheck } // clear validator slash events @@ -110,7 +109,9 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) app.DistrKeeper.SetFeePool(ctx, feePool) - app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()) + if err := app.DistrKeeper.Hooks().AfterValidatorCreated(ctx, val.GetOperator()); err != nil { + panic(err) + } return false }) @@ -120,12 +121,17 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ if err != nil { panic(err) } - delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) - if err != nil { - panic(err) + delAddr := sdk.MustAccAddressFromBech32(del.DelegatorAddress) + + if err := app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr); err != nil { + // never called as BeforeDelegationCreated always returns nil + panic(fmt.Errorf("error while incrementing period: %w", err)) + } + + if err := app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr); err != nil { + // never called as AfterDelegationModified always returns nil + panic(fmt.Errorf("error while creating a new delegation period record: %w", err)) } - app.DistrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) - app.DistrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) } // reset context height @@ -153,7 +159,7 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ // Iterate through validators by power descending, reset bond heights, and // update bond intra-tx counters. - store := ctx.KVStore(app.keys[stakingtypes.StoreKey]) + store := ctx.KVStore(app.GetKey(stakingtypes.StoreKey)) iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) counter := int16(0) @@ -173,7 +179,10 @@ func (app *TerpApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs [ counter++ } - iter.Close() + if err := iter.Close(); err != nil { + app.Logger().Error("error while closing the key-value store reverse prefix iterator: ", err) + return + } _, err := app.StakingKeeper.ApplyAndReturnValidatorSetUpdates(ctx) if err != nil { diff --git a/app/genesis.go b/app/genesis.go index 622c15d..2900679 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -2,9 +2,11 @@ package app import ( "encoding/json" + + "github.com/cosmos/cosmos-sdk/codec" ) -// GenesisState The genesis state of the blockchain is represented here as a map of raw json +// GenesisState of the blockchain is represented here as a map of raw json // messages key'd by a identifier string. // The identifier is used to determine which module genesis information belongs // to so it may be appropriately routed during init chain. @@ -14,7 +16,6 @@ import ( type GenesisState map[string]json.RawMessage // NewDefaultGenesisState generates the default state for the application. -func NewDefaultGenesisState() GenesisState { - encodingConfig := MakeEncodingConfig() - return ModuleBasics.DefaultGenesis(encodingConfig.Marshaler) +func NewDefaultGenesisState(cdc codec.JSONCodec) GenesisState { + return ModuleBasics.DefaultGenesis(cdc) } diff --git a/app/params/params.go b/app/params/params.go deleted file mode 100644 index b6aa5fb..0000000 --- a/app/params/params.go +++ /dev/null @@ -1,7 +0,0 @@ -package params - -// Simulation parameter constants -const ( - StakePerAccount = "stake_per_account" - InitiallyBondedValidators = "initially_bonded_validators" -) diff --git a/app/params/weights.go b/app/params/weights.go index 4e5452c..997b814 100644 --- a/app/params/weights.go +++ b/app/params/weights.go @@ -40,3 +40,12 @@ const ( DefaultWeightUpdateInstantiateConfigProposal int = 5 DefaultWeightStoreAndInstantiateContractProposal int = 5 ) + +// Token Factory Weights +const ( + DefaultWeightMsgCreateDenom int = 100 + DefaultWeightMsgMint int = 100 + DefaultWeightMsgBurn int = 100 + DefaultWeightMsgChangeAdmin int = 100 + DefaultWeightMsgSetDenomMetadata int = 100 +) diff --git a/app/sim_test.go b/app/sim_test.go index 689f13a..9e84c78 100644 --- a/app/sim_test.go +++ b/app/sim_test.go @@ -3,17 +3,23 @@ package app import ( "encoding/json" "fmt" + "math/rand" "os" - "path/filepath" + "runtime/debug" + "strings" "testing" - "time" + 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/codec" - "github.com/cosmos/cosmos-sdk/simapp" + "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" - "github.com/cosmos/cosmos-sdk/types/module" 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" @@ -21,179 +27,154 @@ import ( 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" - "github.com/cosmos/cosmos-sdk/x/feegrant" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" - paramstypes "github.com/cosmos/cosmos-sdk/x/params/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" - ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - ibchost "github.com/cosmos/ibc-go/v4/modules/core/24-host" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/terpnetwork/terp-core/x/wasm" - wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" ) +// SimAppChainID hardcoded chainID for simulation +const SimAppChainID = "simulation-app" + // Get flags every time the simulator is run func init() { - simapp.GetSimulatorFlags() + simcli.GetSimulatorFlags() } type StoreKeysPrefixes struct { - A sdk.StoreKey - B sdk.StoreKey + A storetypes.StoreKey + B storetypes.StoreKey Prefixes [][]byte } -// SetupSimulation wraps simapp.SetupSimulation in order to create any export directory if they do not exist yet -func SetupSimulation(dirPrefix, dbName string) (simtypes.Config, dbm.DB, string, log.Logger, bool, error) { - config, db, dir, logger, skip, err := simapp.SetupSimulation(dirPrefix, dbName) - if err != nil { - return simtypes.Config{}, nil, "", nil, false, err - } - - paths := []string{config.ExportParamsPath, config.ExportStatePath, config.ExportStatsPath} - for _, path := range paths { - if len(path) == 0 { - continue - } - - path = filepath.Dir(path) - if _, err := os.Stat(path); os.IsNotExist(err) { - if err := os.MkdirAll(path, os.ModePerm); err != nil { - panic(err) - } - } - } - - return config, db, dir, logger, skip, err -} - -// 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) - } - } - - return log -} - // fauxMerkleModeOpt returns a BaseApp option to use a dbStoreAdapter instead of // an IAVLStore for faster simulation speed. func fauxMerkleModeOpt(bapp *baseapp.BaseApp) { bapp.SetFauxMerkleMode() } -func TestAppImportExport(t *testing.T) { - config, db, dir, logger, skip, err := SetupSimulation("leveldb-app-sim", "Simulation") - if skip { - t.Skip("skipping application import/export simulation") - } - require.NoError(t, err, "simulation setup failed") +// 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()) +} - defer func() { - db.Close() - require.NoError(t, os.RemoveAll(dir)) - }() +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(), + ) - encConf := MakeEncodingConfig() - app := NewTerpApp(logger, db, nil, true, map[int64]bool{}, dir, simapp.FlagPeriodValue, encConf, wasm.EnableAllProposals, EmptyBaseAppOptions{}, nil, fauxMerkleModeOpt) - require.Equal(t, appName, app.Name()) + // export state and simParams before the simulation error is checked + err := simtestutil.CheckExportSimulation(app, config, simParams) + require.NoError(t, err) + require.NoError(t, simErr) + + if config.Commit { + simtestutil.PrintStats(db) + } +} + +func TestAppImportExport(t *testing.T) { + config, db, appOptions, app := setupSimulationApp(t, "skipping application import/export simulation") // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( t, os.Stdout, app.BaseApp, - AppStateFn(app.AppCodec(), app.SimulationManager()), - simtypes.RandomAccounts, - simapp.SimulationOperations(app, app.AppCodec(), config), - app.ModuleAccountAddrs(), + 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 = simapp.CheckExportSimulation(app, config, simParams) + err := simtestutil.CheckExportSimulation(app, config, simParams) require.NoError(t, err) require.NoError(t, simErr) if config.Commit { - simapp.PrintStats(db) + simtestutil.PrintStats(db) } - t.Log("exporting genesis...") + fmt.Printf("exporting genesis...\n") - exported, err := app.ExportAppStateAndValidators(false, []string{}) + exported, err := app.ExportAppStateAndValidators(false, []string{}, []string{}) require.NoError(t, err) - t.Log("importing genesis...") + fmt.Printf("importing genesis...\n") - _, newDB, newDir, _, _, err := SetupSimulation("leveldb-app-sim-2", "Simulation-2") + 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() { - newDB.Close() + require.NoError(t, newDB.Close()) require.NoError(t, os.RemoveAll(newDir)) }() - newApp := NewTerpApp(logger, newDB, nil, true, map[int64]bool{}, newDir, simapp.FlagPeriodValue, encConf, wasm.EnableAllProposals, EmptyBaseAppOptions{}, nil, fauxMerkleModeOpt) - require.Equal(t, appName, newApp.Name()) + + 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())) + } + }() + ctxA := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) ctxB := newApp.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) - newApp.mm.InitGenesis(ctxB, app.AppCodec(), genesisState) + newApp.ModuleManager.InitGenesis(ctxB, app.AppCodec(), genesisState) newApp.StoreConsensusParams(ctxB, exported.ConsensusParams) - t.Log("comparing stores...") + fmt.Printf("comparing stores...\n") storeKeysPrefixes := []StoreKeysPrefixes{ - {app.keys[authtypes.StoreKey], newApp.keys[authtypes.StoreKey], [][]byte{}}, + {app.GetKey(authtypes.StoreKey), newApp.GetKey(authtypes.StoreKey), [][]byte{}}, { - app.keys[stakingtypes.StoreKey], newApp.keys[stakingtypes.StoreKey], + app.GetKey(stakingtypes.StoreKey), newApp.GetKey(stakingtypes.StoreKey), [][]byte{ stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey, - stakingtypes.HistoricalInfoKey, + stakingtypes.HistoricalInfoKey, stakingtypes.UnbondingIDKey, stakingtypes.UnbondingIndexKey, stakingtypes.UnbondingTypeKey, stakingtypes.ValidatorUpdatesKey, }, - }, - {app.keys[slashingtypes.StoreKey], newApp.keys[slashingtypes.StoreKey], [][]byte{}}, - {app.keys[minttypes.StoreKey], newApp.keys[minttypes.StoreKey], [][]byte{}}, - {app.keys[distrtypes.StoreKey], newApp.keys[distrtypes.StoreKey], [][]byte{}}, - {app.keys[banktypes.StoreKey], newApp.keys[banktypes.StoreKey], [][]byte{banktypes.BalancesPrefix}}, - {app.keys[paramstypes.StoreKey], newApp.keys[paramstypes.StoreKey], [][]byte{}}, - {app.keys[govtypes.StoreKey], newApp.keys[govtypes.StoreKey], [][]byte{}}, - {app.keys[evidencetypes.StoreKey], newApp.keys[evidencetypes.StoreKey], [][]byte{}}, - {app.keys[capabilitytypes.StoreKey], newApp.keys[capabilitytypes.StoreKey], [][]byte{}}, - {app.keys[ibchost.StoreKey], newApp.keys[ibchost.StoreKey], [][]byte{}}, - {app.keys[ibctransfertypes.StoreKey], newApp.keys[ibctransfertypes.StoreKey], [][]byte{}}, - {app.keys[authzkeeper.StoreKey], newApp.keys[authzkeeper.StoreKey], [][]byte{}}, - {app.keys[feegrant.StoreKey], newApp.keys[feegrant.StoreKey], [][]byte{}}, - {app.keys[wasm.StoreKey], newApp.keys[wasm.StoreKey], [][]byte{}}, + }, // 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}}, } - // delete persistent tx counter value - ctxA.KVStore(app.keys[wasm.StoreKey]).Delete(wasmtypes.TXCounterPrefix) - - // diff both stores for _, skp := range storeKeysPrefixes { storeA := ctxA.KVStore(skp.A) storeB := ctxB.KVStore(skp.B) @@ -201,58 +182,170 @@ func TestAppImportExport(t *testing.T) { failedKVAs, failedKVBs := sdk.DiffKVStores(storeA, storeB, skp.Prefixes) require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare") - t.Logf("compared %d different key/value pairs between %s and %s\n", len(failedKVAs), skp.A, skp.B) - require.Len(t, failedKVAs, 0, GetSimulationLog(skp.A.Name(), app.SimulationManager().StoreDecoders, failedKVAs, failedKVBs)) + 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)) } } -func TestFullAppSimulation(t *testing.T) { - config, db, dir, logger, skip, err := SetupSimulation("leveldb-app-sim", "Simulation") - if skip { - t.Skip("skipping application simulation") - } - require.NoError(t, err, "simulation setup failed") - - defer func() { - db.Close() - require.NoError(t, os.RemoveAll(dir)) - }() - encConf := MakeEncodingConfig() - app := NewTerpApp(logger, db, nil, true, map[int64]bool{}, t.TempDir(), simapp.FlagPeriodValue, - encConf, wasm.EnableAllProposals, simapp.EmptyAppOptions{}, nil, fauxMerkleModeOpt) - require.Equal(t, "TerpApp", app.Name()) +func TestAppSimulationAfterImport(t *testing.T) { + config, db, appOptions, app := setupSimulationApp(t, "skipping application simulation after import") - // run randomized simulation - _, simParams, simErr := simulation.SimulateFromSeed( + // Run randomized simulation + stopEarly, simParams, simErr := simulation.SimulateFromSeed( t, os.Stdout, app.BaseApp, - AppStateFn(app.appCodec, app.SimulationManager()), + simtestutil.AppStateFn(app.AppCodec(), app.SimulationManager(), app.DefaultGenesis()), simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 - simapp.SimulationOperations(app, app.AppCodec(), config), - app.ModuleAccountAddrs(), + simtestutil.SimulationOperations(app, app.AppCodec(), config), + BlockedAddresses(), config, app.AppCodec(), ) // export state and simParams before the simulation error is checked - err = simapp.CheckExportSimulation(app, config, simParams) + err := simtestutil.CheckExportSimulation(app, config, simParams) require.NoError(t, err) require.NoError(t, simErr) if config.Commit { - simapp.PrintStats(db) + 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 } -// AppStateFn returns the initial application state using a genesis or the simulation parameters. -// It panics if the user provides files for both of them. -// If a file is not given for the genesis or the sim params, it creates a randomized one. -func AppStateFn(codec codec.Codec, manager *module.SimulationManager) simtypes.AppStateFn { - // quick hack to setup app state genesis with our app modules - simapp.ModuleBasics = ModuleBasics - if simapp.FlagGenesisTimeValue == 0 { // always set to have a block time - simapp.FlagGenesisTimeValue = time.Now().Unix() +// 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, + ) + } + } } - return simapp.AppStateFn(codec, manager) } diff --git a/app/test_access.go b/app/test_access.go deleted file mode 100644 index ebee745..0000000 --- a/app/test_access.go +++ /dev/null @@ -1,73 +0,0 @@ -package app - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" - - "github.com/terpnetwork/terp-core/app/params" - - "github.com/cosmos/cosmos-sdk/codec" - bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" - capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" - stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - ibctransferkeeper "github.com/cosmos/ibc-go/v4/modules/apps/transfer/keeper" - ibckeeper "github.com/cosmos/ibc-go/v4/modules/core/keeper" - - "github.com/terpnetwork/terp-core/x/wasm" -) - -// Deprecated: use public app attributes directly -type TestSupport struct { - t testing.TB - app *TerpApp -} - -func NewTestSupport(t testing.TB, app *TerpApp) *TestSupport { - return &TestSupport{t: t, app: app} -} - -func (s TestSupport) IBCKeeper() *ibckeeper.Keeper { - return s.app.IBCKeeper -} - -func (s TestSupport) WasmKeeper() wasm.Keeper { - return s.app.WasmKeeper -} - -func (s TestSupport) AppCodec() codec.Codec { - return s.app.appCodec -} - -func (s TestSupport) ScopedWasmIBCKeeper() capabilitykeeper.ScopedKeeper { - return s.app.ScopedWasmKeeper -} - -func (s TestSupport) ScopeIBCKeeper() capabilitykeeper.ScopedKeeper { - return s.app.ScopedIBCKeeper -} - -func (s TestSupport) ScopedTransferKeeper() capabilitykeeper.ScopedKeeper { - return s.app.ScopedTransferKeeper -} - -func (s TestSupport) StakingKeeper() stakingkeeper.Keeper { - return s.app.StakingKeeper -} - -func (s TestSupport) BankKeeper() bankkeeper.Keeper { - return s.app.BankKeeper -} - -func (s TestSupport) TransferKeeper() ibctransferkeeper.Keeper { - return s.app.TransferKeeper -} - -func (s TestSupport) GetBaseApp() *baseapp.BaseApp { - return s.app.BaseApp -} - -func (s TestSupport) GetTxConfig() client.TxConfig { - return params.MakeEncodingConfig().TxConfig -} diff --git a/app/test_helpers.go b/app/test_helpers.go index 354be2e..a448d6d 100644 --- a/app/test_helpers.go +++ b/app/test_helpers.go @@ -1,262 +1,235 @@ package app import ( - "bytes" - "encoding/hex" "encoding/json" "fmt" + "math/rand" + "os" "path/filepath" - "strconv" "testing" "time" + "cosmossdk.io/math" + + dbm "github.com/cometbft/cometbft-db" + abci "github.com/cometbft/cometbft/abci/types" + tmjson "github.com/cometbft/cometbft/libs/json" + "github.com/cometbft/cometbft/libs/log" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + tmtypes "github.com/cometbft/cometbft/types" 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/ed25519" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/simapp/helpers" + "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/errors" + "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" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - tmtypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/terpnetwork/terp-core/x/wasm" + wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" ) -// DefaultConsensusParams defines the default Tendermint consensus params used in -// TerpApp testing. -var DefaultConsensusParams = &abci.ConsensusParams{ - Block: &abci.BlockParams{ - MaxBytes: 8000000, - MaxGas: 1234000000, - }, - Evidence: &tmproto.EvidenceParams{ - MaxAgeNumBlocks: 302400, - MaxAgeDuration: 504 * time.Hour, // 3 weeks is the max duration - MaxBytes: 10000, - }, - Validator: &tmproto.ValidatorParams{ - PubKeyTypes: []string{ - tmtypes.ABCIPubKeyTypeEd25519, - }, - }, +// SetupOptions defines arguments that are passed into `TerpApp` constructor. +type SetupOptions struct { + Logger log.Logger + DB *dbm.MemDB + AppOpts servertypes.AppOptions + WasmOpts []wasm.Option } -func setup(t testing.TB, withGenesis bool, invCheckPeriod uint, opts ...wasm.Option) (*TerpApp, GenesisState) { - nodeHome := t.TempDir() +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 := sdk.NewLevelDB("metadata", snapshotDir) - require.NoError(t, err) - t.Cleanup(func() { snapshotDB.Close() }) + + 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(t, err) - baseAppOpts := []func(*bam.BaseApp){bam.SetSnapshotStore(snapshotStore), bam.SetSnapshotKeepRecent(2)} - db := dbm.NewMemDB() - t.Cleanup(func() { db.Close() }) - app := NewTerpApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, nodeHome, invCheckPeriod, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, opts, baseAppOpts...) + 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() + return app, NewDefaultGenesisState(app.AppCodec()) } return app, GenesisState{} } -// Setup initializes a new TerpApp with DefaultNodeHome for integration tests -func Setup(isCheckTx bool, opts ...wasm.Option) *TerpApp { - db := dbm.NewMemDB() - app := NewTerpApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, 5, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, opts) +// 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 { - genesisState := NewDefaultGenesisState() - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - if err != nil { - panic(err) - } + // init chain must be called to stop deliverState from being nil + stateBytes, err := tmjson.MarshalIndent(genesisState, "", " ") + require.NoError(t, err) + // Initialize the chain app.InitChain( abci.RequestInitChain{ Validators: []abci.ValidatorUpdate{}, - ConsensusParams: DefaultConsensusParams, + ConsensusParams: simtestutil.DefaultConsensusParams, AppStateBytes: stateBytes, }, ) } + return app } -// SetupWithGenesisValSet initializes a new TerpApp with a validator set and genesis accounts -// that also act as delegators. For simplicity, each validator is bonded with a delegation -// of one consensus engine unit (10^6) in the default token of the 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 { - app, genesisState := setup(t, true, 5, opts...) - // set genesis accounts - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) - genesisState[authtypes.ModuleName] = app.appCodec.MustMarshalJSON(authGenesis) +// Setup initializes a new TerpApp. A Nop logger is set in TerpApp. +func Setup(t *testing.T, opts ...wasm.Option) *TerpApp { + t.Helper() - validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) - delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + require.NoError(t, err) - bondAmt := sdk.TokensFromConsensusPower(1, sdk.DefaultPowerReduction) + // create validator set with single validator + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - for _, val := range valSet.Validators { - pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) - require.NoError(t, err) - pkAny, err := codectypes.NewAnyWithValue(pk) - require.NoError(t, err) - validator := stakingtypes.Validator{ - OperatorAddress: sdk.ValAddress(val.Address).String(), - ConsensusPubkey: pkAny, - Jailed: false, - Status: stakingtypes.Bonded, - Tokens: bondAmt, - DelegatorShares: sdk.OneDec(), - Description: stakingtypes.Description{}, - UnbondingHeight: int64(0), - UnbondingTime: time.Unix(0, 0).UTC(), - Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - MinSelfDelegation: sdk.ZeroInt(), - } - - validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) + // 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))), } + chainID := "testing" + app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, chainID, opts, balance) - // set validators and delegations - var stakingGenesis stakingtypes.GenesisState - app.AppCodec().MustUnmarshalJSON(genesisState[stakingtypes.ModuleName], &stakingGenesis) - - bondDenom := stakingGenesis.Params.BondDenom - - // add bonded amount to bonded pool module account - balances = append(balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin(bondDenom, bondAmt.Mul(sdk.NewInt(int64(len(valSet.Validators)))))}, - }) + return app +} - // set validators and delegations - stakingGenesis = *stakingtypes.NewGenesisState(stakingGenesis.Params, validators, delegations) - genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(&stakingGenesis) +// SetupWithGenesisValSet initializes a new TerpApp 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 { + t.Helper() - // update total supply - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, sdk.NewCoins(), []banktypes.Metadata{}) - genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) + app, genesisState := setup(t, chainID, true, 5, opts...) + genesisState, err := GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, genAccs, balances...) + require.NoError(t, err) 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( abci.RequestInitChain{ ChainId: chainID, Validators: []abci.ValidatorUpdate{}, - ConsensusParams: DefaultConsensusParams, + ConsensusParams: consensusParams, AppStateBytes: stateBytes, }, ) - // commit genesis changes app.Commit() - app.BeginBlock( - abci.RequestBeginBlock{ - Header: tmproto.Header{ - ChainID: chainID, - Height: app.LastBlockHeight() + 1, - AppHash: app.LastCommitID().Hash, - ValidatorsHash: valSet.Hash(), - NextValidatorsHash: valSet.Hash(), - }, - }, - ) + app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{ + ChainID: chainID, + Height: app.LastBlockHeight() + 1, + AppHash: app.LastCommitID().Hash, + Time: time.Now().UTC(), + ValidatorsHash: valSet.Hash(), + NextValidatorsHash: valSet.Hash(), + }}) return app } -// SetupWithEmptyStore setup a terpd app instance with empty DB -func SetupWithEmptyStore(t testing.TB) *TerpApp { - app, _ := setup(t, false, 0) +// 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 } -type GenerateAccountStrategy func(int) []sdk.AccAddress - -// createRandomAccounts is a strategy used by addTestAddrs() in order to generated addresses in random order. -func createRandomAccounts(accNum int) []sdk.AccAddress { - testAddrs := make([]sdk.AccAddress, accNum) - for i := 0; i < accNum; i++ { - pk := ed25519.GenPrivKey().PubKey() - testAddrs[i] = sdk.AccAddress(pk.Address()) - } - - return testAddrs -} - -// createIncrementalAccounts is a strategy used by addTestAddrs() in order to generated addresses in ascending order. -func createIncrementalAccounts(accNum int) []sdk.AccAddress { - addresses := make([]sdk.AccAddress, 0, accNum) - var buffer bytes.Buffer - - // start at 100 so we can make up to 999 test addresses with valid test addresses - for i := 100; i < (accNum + 100); i++ { - numString := strconv.Itoa(i) - buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") // base address string +// 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() - buffer.WriteString(numString) // adding on final two digits to make addresses unique - res, err := sdk.AccAddressFromHex(buffer.String()) - if err != nil { - panic(err) - } - bech := res.String() - addr, err := TestAddr(buffer.String(), bech) - if err != nil { - panic(err) - } + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + require.NoError(t, err) - addresses = append(addresses, addr) - buffer.Reset() + // 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))), + }, } - return addresses -} - -// AddTestAddrsFromPubKeys adds the addresses into the TerpApp providing only the public keys. -func AddTestAddrsFromPubKeys(app *TerpApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt sdk.Int) { - initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) - - for _, pk := range pubKeys { - initAccountWithCoins(app, ctx, sdk.AccAddress(pk.Address()), initCoins) - } -} + genesisState := NewDefaultGenesisState(app.appCodec) + genesisState, err = GenesisStateWithValSet(app.AppCodec(), genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...) + require.NoError(t, err) -// AddTestAddrs constructs and returns accNum amount of accounts with an -// initial balance of accAmt in random order -func AddTestAddrs(app *TerpApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress { - return addTestAddrs(app, ctx, accNum, accAmt, createRandomAccounts) + return genesisState } -// AddTestAddrs constructs and returns accNum amount of accounts with an +// 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 sdk.Int) []sdk.AccAddress { - return addTestAddrs(app, ctx, accNum, accAmt, createIncrementalAccounts) +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 sdk.Int, strategy GenerateAccountStrategy) []sdk.AccAddress { +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)) - // fill all the addresses with some coins, set the loose pool tokens simultaneously for _, addr := range testAddrs { initAccountWithCoins(app, ctx, addr, initCoins) } @@ -276,188 +249,142 @@ func initAccountWithCoins(app *TerpApp, ctx sdk.Context, addr sdk.AccAddress, co } } -// ConvertAddrsToValAddrs converts the provided addresses to ValAddress. -func ConvertAddrsToValAddrs(addrs []sdk.AccAddress) []sdk.ValAddress { - valAddrs := make([]sdk.ValAddress, len(addrs)) - - for i, addr := range addrs { - valAddrs[i] = sdk.ValAddress(addr) - } - - return valAddrs +// ModuleAccountAddrs provides a list of blocked module accounts from configuration in AppConfig +// +// Ported from TerpApp +func ModuleAccountAddrs() map[string]bool { + return BlockedAddresses() } -func TestAddr(addr string, bech string) (sdk.AccAddress, error) { - res, err := sdk.AccAddressFromHex(addr) - if err != nil { - return nil, err - } - bechexpected := res.String() - if bech != bechexpected { - return nil, fmt.Errorf("bech encoding doesn't match reference") - } +var emptyWasmOptions []wasm.Option - bechres, err := sdk.AccAddressFromBech32(bech) +// NewTestNetworkFixture returns a new TerpApp AppConstructor for network simulation tests +func NewTestNetworkFixture() network.TestFixture { + dir, err := os.MkdirTemp("", "simapp") if err != nil { - return nil, err + panic(fmt.Sprintf("failed creating temporary directory: %v", err)) } - if !bytes.Equal(bechres, res) { - return nil, 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 res, nil -} - -// CheckBalance checks the balance of an account. -func CheckBalance(t *testing.T, app *TerpApp, addr sdk.AccAddress, balances sdk.Coins) { - ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) - require.True(t, balances.IsEqual(app.BankKeeper.GetAllBalances(ctxCheck, addr))) + return network.TestFixture{ + AppConstructor: appCtr, + GenesisState: NewDefaultGenesisState(app.AppCodec()), + EncodingConfig: testutil.TestEncodingConfig{ + InterfaceRegistry: app.InterfaceRegistry(), + Codec: app.AppCodec(), + TxConfig: app.TxConfig(), + Amino: app.LegacyAmino(), + }, + } } -const DefaultGas = 1_500_000 - -// SignCheckDeliver checks a generated signed transaction and simulates a -// block commitment with the given transaction. A test assertion is made using -// the parameter 'expPass' against the result. A corresponding result is -// returned. -func SignCheckDeliver( +// 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, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, + chainID string, accNums, accSeqs []uint64, priv ...cryptotypes.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { - tx, err := helpers.GenTx( + t.Helper() + tx, err := simtestutil.GenSignedMockTx( + rand.New(rand.NewSource(time.Now().UnixNano())), txCfg, msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - helpers.DefaultGenTxGas, + simtestutil.DefaultGenTxGas, chainID, accNums, accSeqs, priv..., ) require.NoError(t, err) - txBytes, err := txCfg.TxEncoder()(tx) - require.Nil(t, err) - - // Must simulate now as CheckTx doesn't run Msgs anymore - _, res, err := app.Simulate(txBytes) - - if expSimPass { - require.NoError(t, err) - require.NotNil(t, res) - } else { - require.Error(t, err) - require.Nil(t, res) - } // Simulate a sending a transaction and committing a block - app.BeginBlock(abci.RequestBeginBlock{Header: header}) - gInfo, res, err := app.Deliver(txCfg.TxEncoder(), tx) - - if expPass { - require.NoError(t, err) - require.NotNil(t, res) - } else { - require.Error(t, err) - require.Nil(t, res) - } - - app.EndBlock(abci.RequestEndBlock{}) - app.Commit() + // app.BeginBlock(abci.RequestBeginBlock{Header: header}) + gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx) + // app.EndBlock(abci.RequestEndBlock{}) + // app.Commit() return gInfo, res, err } -// SignAndDeliver signs and delivers a transaction. No simulation occurs as the -// ibc testing package causes checkState and deliverState to diverge in block time. -func SignAndDeliver( - 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) { - tx, err := helpers.GenTx( - txCfg, - msgs, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - 2*DefaultGas, - chainID, - accNums, - accSeqs, - priv..., - ) - require.NoError(t, err) +// 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, + balances ...banktypes.Balance, +) (map[string]json.RawMessage, error) { + // set genesis accounts + authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) + genesisState[authtypes.ModuleName] = codec.MustMarshalJSON(authGenesis) - // Simulate a sending a transaction and committing a block - app.BeginBlock(abci.RequestBeginBlock{Header: header}) - gInfo, res, err := app.Deliver(txCfg.TxEncoder(), tx) - return gInfo, res, err -} + validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) + delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) -// GenSequenceOfTxs generates a set of signed transactions of messages, such -// that they differ only by having the sequence numbers incremented between -// every transaction. -func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...cryptotypes.PrivKey) ([]sdk.Tx, error) { - txs := make([]sdk.Tx, numToGenerate) - var err error - for i := 0; i < numToGenerate; i++ { - txs[i], err = helpers.GenTx( - txGen, - msgs, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - helpers.DefaultGenTxGas, - "", - accNums, - initSeqNums, - priv..., - ) + bondAmt := sdk.DefaultPowerReduction + + for _, val := range valSet.Validators { + pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) if err != nil { - break + return nil, fmt.Errorf("failed to convert pubkey: %w", err) } - incrementAllSequenceNumbers(initSeqNums) - } - return txs, err -} + pkAny, err := codectypes.NewAnyWithValue(pk) + if err != nil { + return nil, fmt.Errorf("failed to create new any: %w", err) + } -func incrementAllSequenceNumbers(initSeqNums []uint64) { - for i := 0; i < len(initSeqNums); i++ { - initSeqNums[i]++ + validator := stakingtypes.Validator{ + OperatorAddress: sdk.ValAddress(val.Address).String(), + ConsensusPubkey: pkAny, + Jailed: false, + Status: stakingtypes.Bonded, + Tokens: bondAmt, + DelegatorShares: math.LegacyOneDec(), + Description: stakingtypes.Description{}, + UnbondingHeight: int64(0), + UnbondingTime: time.Unix(0, 0).UTC(), + Commission: stakingtypes.NewCommission(math.LegacyZeroDec(), math.LegacyZeroDec(), math.LegacyZeroDec()), + MinSelfDelegation: math.ZeroInt(), + } + validators = append(validators, validator) + delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), math.LegacyOneDec())) } -} -// CreateTestPubKeys returns a total of numPubKeys public keys in ascending order. -func CreateTestPubKeys(numPubKeys int) []cryptotypes.PubKey { - publicKeys := make([]cryptotypes.PubKey, 0, numPubKeys) - var buffer bytes.Buffer - - // start at 10 to avoid changing 1 to 01, 2 to 02, etc - for i := 100; i < (numPubKeys + 100); i++ { - numString := strconv.Itoa(i) - buffer.WriteString("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AF") // base pubkey string - buffer.WriteString(numString) // adding on final two digits to make pubkeys unique - publicKeys = append(publicKeys, NewPubKeyFromHex(buffer.String())) - buffer.Reset() - } + // set validators and delegations + stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations) + genesisState[stakingtypes.ModuleName] = codec.MustMarshalJSON(stakingGenesis) - return publicKeys -} + // 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))))}, + }) -// NewPubKeyFromHex returns a PubKey from a hex string. -func NewPubKeyFromHex(pk string) (res cryptotypes.PubKey) { - pkBytes, err := hex.DecodeString(pk) - if err != nil { - panic(err) - } - if len(pkBytes) != ed25519.PubKeySize { - panic(errors.Wrap(errors.ErrInvalidPubKey, "invalid pubkey size")) + totalSupply := sdk.NewCoins() + for _, b := range balances { + // add genesis acc tokens to total supply + totalSupply = totalSupply.Add(b.Coins...) } - return &ed25519.PubKey{Key: pkBytes} -} -// EmptyBaseAppOptions is a stub implementing AppOptions -type EmptyBaseAppOptions struct{} - -// Get implements AppOptions -func (ao EmptyBaseAppOptions) Get(o string) interface{} { - return nil + // 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 } // FundAccount is a utility function that funds an account by minting and diff --git a/app/upgrades.go b/app/upgrades.go new file mode 100644 index 0000000..6cf7fa0 --- /dev/null +++ b/app/upgrades.go @@ -0,0 +1,108 @@ +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 deleted file mode 100644 index 9f96b5e..0000000 --- a/app/upgrades/types.go +++ /dev/null @@ -1,37 +0,0 @@ -/* package upgrades - -import ( - store "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/terpnetwork/terp-core/app/keepers" -) - -// BaseAppParamManager defines an interrace that BaseApp is expected to fullfil -// that allows upgrade handlers to modify BaseApp parameters. -type BaseAppParamManager interface { - GetConsensusParams(ctx sdk.Context) *abci.ConsensusParams - StoreConsensusParams(ctx sdk.Context, cp *abci.ConsensusParams) -} - -// Upgrade defines a struct containing necessary fields that a SoftwareUpgradeProposal -// must have written, in order for the state migration to go smoothly. -// An upgrade must implement this struct, and then set it in the app.go. -// The app.go will then define the handler. -type Upgrade struct { - // Upgrade version name, for the upgrade handler, e.g. `v7` - UpgradeName string - - // CreateUpgradeHandler defines the function that creates an upgrade handler - CreateUpgradeHandler func( - *module.Manager, - module.Configurator, - *keepers.AppKeepers, - ) upgradetypes.UpgradeHandler - - // Store upgrades, should be used for any new modules introduced, new modules deleted, or store names renamed. - StoreUpgrades store.StoreUpgrades -} -*/ \ No newline at end of file diff --git a/app/upgrades/v040/constants.go b/app/upgrades/v040/constants.go deleted file mode 100644 index 037f78f..0000000 --- a/app/upgrades/v040/constants.go +++ /dev/null @@ -1,18 +0,0 @@ -/*package v1 - -import ( - store "github.com/cosmos/cosmos-sdk/store/types" - "github.com/terpnetwork/terp-core/app/upgrades" -) - -// UpgradeName defines the on-chain upgrade name for the Terp Network v1 upgrade. -const UpgradeName = "v1" // maybe ? - -var Upgrade = upgrades.Upgrade{ - UpgradeName: UpgradeName, - CreateUpgradeHandler: CreateV1UpgradeHandler, - StoreUpgrades: store.StoreUpgrades{ - Added: []string{TBD.StoreKey, TBD.StoreKey}, - }, -} -*/ diff --git a/app/upgrades/v040/upgrades.go b/app/upgrades/v040/upgrades.go deleted file mode 100644 index 20ebf35..0000000 --- a/app/upgrades/v040/upgrades.go +++ /dev/null @@ -1,22 +0,0 @@ -/*package v1 - -import ( - 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/terpnetwork/terp-core/app/keepers" -) - -// CreateV10UpgradeHandler makes an upgrade handler for v10 of Juno -func CreateV1UpgradeHandler( - mm *module.Manager, - cfg module.Configurator, - keepers *keepers.AppKeepers, -) upgradetypes.UpgradeHandler { - return func(ctx sdk.Context, _ upgradetypes.Plan, vm module.VersionMap) (module.VersionMap, error) { - - // mint module consensus version bumped - return mm.RunMigrations(ctx, cfg, vm) - } -} -*/ \ No newline at end of file diff --git a/benchmarks/app_test.go b/benchmarks/app_test.go index 391bbbd..89855c1 100644 --- a/benchmarks/app_test.go +++ b/benchmarks/app_test.go @@ -2,21 +2,23 @@ package benchmarks import ( "encoding/json" + "math/rand" "os" "testing" "time" - "github.com/stretchr/testify/require" + simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" + moduletestutil "github.com/cosmos/cosmos-sdk/types/module/testutil" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" + 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" + tmtypes "github.com/cometbft/cometbft/types" + "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - "github.com/cosmos/cosmos-sdk/simapp/helpers" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/testutil/mock" 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" @@ -24,32 +26,82 @@ import ( "github.com/terpnetwork/terp-core/app" "github.com/terpnetwork/terp-core/x/wasm" wasmtypes "github.com/terpnetwork/terp-core/x/wasm/types" + + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" ) -func setup(db dbm.DB, withGenesis bool, invCheckPeriod uint, opts ...wasm.Option) (*app.TerpApp, app.GenesisState) { - encodingConfig := app.MakeEncodingConfig() - wasmApp := app.NewTerpApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, app.DefaultNodeHome, invCheckPeriod, encodingConfig, wasm.EnableAllProposals, app.EmptyBaseAppOptions{}, opts) +func setup(db dbm.DB, withGenesis bool, invCheckPeriod uint, opts ...wasm.Option) (*app.TerpApp, app.GenesisState) { //nolint:unparam + wasmApp := app.NewTerpApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, wasm.EnableAllProposals, simtestutil.EmptyAppOptions{}, nil) + if withGenesis { - return wasmApp, app.NewDefaultGenesisState() + return wasmApp, app.NewDefaultGenesisState(wasmApp.AppCodec()) } return wasmApp, app.GenesisState{} } -// SetupWithGenesisAccounts initializes a new TerpApp with the provided genesis +// SetupWithGenesisAccountsAndValSet initializes a new TerpApp with the provided genesis // accounts and possible balances. -func SetupWithGenesisAccounts(b testing.TB, db dbm.DB, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *app.TerpApp { +func SetupWithGenesisAccountsAndValSet(tb testing.TB, db dbm.DB, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *app.TerpApp { + tb.Helper() wasmApp, genesisState := setup(db, true, 0) authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) - appCodec := app.NewTestSupport(b, wasmApp).AppCodec() + appCodec := wasmApp.AppCodec() + + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + require.NoError(tb, err) genesisState[authtypes.ModuleName] = appCodec.MustMarshalJSON(authGenesis) + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) + + validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) + delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) + + bondAmt := sdk.DefaultPowerReduction + + for _, val := range valSet.Validators { + pk, _ := cryptocodec.FromTmPubKeyInterface(val.PubKey) + pkAny, _ := codectypes.NewAnyWithValue(pk) + validator := stakingtypes.Validator{ + OperatorAddress: sdk.ValAddress(val.Address).String(), + ConsensusPubkey: pkAny, + Jailed: false, + Status: stakingtypes.Bonded, + Tokens: bondAmt, + DelegatorShares: sdk.OneDec(), + Description: stakingtypes.Description{}, + UnbondingHeight: int64(0), + UnbondingTime: time.Unix(0, 0).UTC(), + Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), + MinSelfDelegation: sdk.ZeroInt(), + } + validators = append(validators, validator) + delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) + + } + // set validators and delegations + stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations) + genesisState[stakingtypes.ModuleName] = appCodec.MustMarshalJSON(stakingGenesis) + totalSupply := sdk.NewCoins() + + // 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)}, + }) + // update total supply for _, b := range balances { + // add genesis acc tokens and delegated tokens to total supply totalSupply = totalSupply.Add(b.Coins...) } - - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}) + bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}, nil) genesisState[banktypes.ModuleName] = appCodec.MustMarshalJSON(bankGenesis) stateBytes, err := json.MarshalIndent(genesisState, "", " ") @@ -57,10 +109,13 @@ func SetupWithGenesisAccounts(b testing.TB, db dbm.DB, genAccs []authtypes.Genes panic(err) } + consensusParams := simtestutil.DefaultConsensusParams + consensusParams.Block.MaxGas = 100 * simtestutil.DefaultGenTxGas + wasmApp.InitChain( abci.RequestInitChain{ Validators: []abci.ValidatorUpdate{}, - ConsensusParams: app.DefaultConsensusParams, + ConsensusParams: consensusParams, AppStateBytes: stateBytes, }, ) @@ -82,7 +137,8 @@ type AppInfo struct { TxConfig client.TxConfig } -func InitializeTerpApp(b testing.TB, db dbm.DB, numAccounts int) AppInfo { +func InitializeTerpApp(tb testing.TB, db dbm.DB, numAccounts int) AppInfo { + tb.Helper() // constants minter := secp256k1.GenPrivKey() addr := sdk.AccAddress(minter.PubKey().Address()) @@ -111,24 +167,25 @@ func InitializeTerpApp(b testing.TB, db dbm.DB, numAccounts int) AppInfo { Coins: sdk.NewCoins(sdk.NewInt64Coin(denom, 100000000000)), } } - wasmApp := SetupWithGenesisAccounts(b, db, genAccs, bals...) + wasmApp := SetupWithGenesisAccountsAndValSet(tb, db, genAccs, bals...) // add wasm contract height := int64(2) - txGen := simappparams.MakeTestEncodingConfig().TxConfig + txGen := moduletestutil.MakeTestEncodingConfig().TxConfig wasmApp.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{Height: height, Time: time.Now()}}) // upload the code cw20Code, err := os.ReadFile("./testdata/cw20_base.wasm") - require.NoError(b, err) + require.NoError(tb, err) storeMsg := wasmtypes.MsgStoreCode{ Sender: addr.String(), WASMByteCode: cw20Code, } - storeTx, err := helpers.GenTx(txGen, []sdk.Msg{&storeMsg}, nil, 55123123, "", []uint64{0}, []uint64{0}, minter) - require.NoError(b, err) - _, res, err := wasmApp.Deliver(txGen.TxEncoder(), storeTx) - require.NoError(b, err) + r := rand.New(rand.NewSource(time.Now().UnixNano())) + storeTx, err := simtestutil.GenSignedMockTx(r, txGen, []sdk.Msg{&storeMsg}, nil, 55123123, "", []uint64{0}, []uint64{0}, minter) + require.NoError(tb, err) + _, _, err = wasmApp.SimDeliver(txGen.TxEncoder(), storeTx) + require.NoError(tb, err) codeID := uint64(1) // instantiate the contract @@ -150,7 +207,7 @@ func InitializeTerpApp(b testing.TB, db dbm.DB, numAccounts int) AppInfo { InitialBalances: initialBalances, } initBz, err := json.Marshal(init) - require.NoError(b, err) + require.NoError(tb, err) initMsg := wasmtypes.MsgInstantiateContract{ Sender: addr.String(), Admin: addr.String(), @@ -159,15 +216,15 @@ func InitializeTerpApp(b testing.TB, db dbm.DB, numAccounts int) AppInfo { Msg: initBz, } gasWanted := 500000 + 10000*uint64(numAccounts) - initTx, err := helpers.GenTx(txGen, []sdk.Msg{&initMsg}, nil, gasWanted, "", []uint64{0}, []uint64{1}, minter) - require.NoError(b, err) - _, res, err = wasmApp.Deliver(txGen.TxEncoder(), initTx) - require.NoError(b, err) + initTx, err := simtestutil.GenSignedMockTx(r, txGen, []sdk.Msg{&initMsg}, nil, gasWanted, "", []uint64{0}, []uint64{1}, minter) + require.NoError(tb, err) + _, res, err := wasmApp.SimDeliver(txGen.TxEncoder(), initTx) + require.NoError(tb, err) // TODO: parse contract address better evt := res.Events[len(res.Events)-1] attr := evt.Attributes[0] - contractAddr := string(attr.Value) + contractAddr := attr.Value wasmApp.EndBlock(abci.RequestEndBlock{Height: height}) wasmApp.Commit() @@ -180,18 +237,21 @@ func InitializeTerpApp(b testing.TB, db dbm.DB, numAccounts int) AppInfo { Denom: denom, AccNum: 0, SeqNum: 2, - TxConfig: simappparams.MakeTestEncodingConfig().TxConfig, + TxConfig: moduletestutil.MakeTestEncodingConfig().TxConfig, } } -func GenSequenceOfTxs(b testing.TB, info *AppInfo, msgGen func(*AppInfo) ([]sdk.Msg, error), numToGenerate int) []sdk.Tx { +func GenSequenceOfTxs(tb testing.TB, info *AppInfo, msgGen func(*AppInfo) ([]sdk.Msg, error), numToGenerate int) []sdk.Tx { + tb.Helper() fees := sdk.Coins{sdk.NewInt64Coin(info.Denom, 0)} txs := make([]sdk.Tx, numToGenerate) + r := rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < numToGenerate; i++ { msgs, err := msgGen(info) - require.NoError(b, err) - txs[i], err = helpers.GenTx( + require.NoError(tb, err) + txs[i], err = simtestutil.GenSignedMockTx( + r, info.TxConfig, msgs, fees, @@ -201,8 +261,8 @@ func GenSequenceOfTxs(b testing.TB, info *AppInfo, msgGen func(*AppInfo) ([]sdk. []uint64{info.SeqNum}, info.MinterKey, ) - require.NoError(b, err) - info.SeqNum += 1 + require.NoError(tb, err) + info.SeqNum++ } return txs diff --git a/benchmarks/bench_test.go b/benchmarks/bench_test.go index a58c4d2..7b4df8b 100644 --- a/benchmarks/bench_test.go +++ b/benchmarks/bench_test.go @@ -8,9 +8,9 @@ import ( "github.com/stretchr/testify/require" "github.com/syndtr/goleveldb/leveldb/opt" - abci "github.com/tendermint/tendermint/abci/types" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" + dbm "github.com/cometbft/cometbft-db" + abci "github.com/cometbft/cometbft/abci/types" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" @@ -107,15 +107,16 @@ func BenchmarkTxSending(b *testing.B) { for j := 0; j < blockSize; j++ { idx := i*blockSize + j - - _, _, err := appInfo.App.Check(txEncoder, txs[idx]) - if err != nil { - panic("something is broken in checking transaction") - } - _, _, err = appInfo.App.Deliver(txEncoder, txs[idx]) + bz, err := txEncoder(txs[idx]) require.NoError(b, err) + rsp := appInfo.App.CheckTx(abci.RequestCheckTx{ + Tx: bz, + Type: abci.CheckTxType_New, + }) + require.True(b, rsp.IsOK()) + dRsp := appInfo.App.DeliverTx(abci.RequestDeliverTx{Tx: bz}) + require.True(b, dRsp.IsOK()) } - appInfo.App.EndBlock(abci.RequestEndBlock{Height: height}) appInfo.App.Commit() height++ @@ -153,15 +154,17 @@ func cw20TransferMsg(info *AppInfo) ([]sdk.Msg, error) { func buildTxFromMsg(builder func(info *AppInfo) ([]sdk.Msg, error)) func(b *testing.B, info *AppInfo) []sdk.Tx { return func(b *testing.B, info *AppInfo) []sdk.Tx { + b.Helper() return GenSequenceOfTxs(b, info, builder, b.N) } } -func buildMemDB(b *testing.B) dbm.DB { +func buildMemDB(_ *testing.B) dbm.DB { return dbm.NewMemDB() } func buildLevelDB(b *testing.B) dbm.DB { + b.Helper() levelDB, err := dbm.NewGoLevelDBWithOpts("testing", b.TempDir(), &opt.Options{BlockCacher: opt.NoCacher}) require.NoError(b, err) return levelDB diff --git a/cmd/terpd/genaccounts.go b/cmd/terpd/genaccounts.go deleted file mode 100644 index 9acf2ce..0000000 --- a/cmd/terpd/genaccounts.go +++ /dev/null @@ -1,192 +0,0 @@ -package main - -import ( - "bufio" - "encoding/json" - "errors" - "fmt" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - "github.com/cosmos/cosmos-sdk/server" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/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" -) - -const ( - flagVestingStart = "vesting-start-time" - flagVestingEnd = "vesting-end-time" - flagVestingAmt = "vesting-amount" -) - -// AddGenesisAccountCmd returns add-genesis-account cobra Command. -func AddGenesisAccountCmd(defaultNodeHome string) *cobra.Command { - cmd := &cobra.Command{ - Use: "add-genesis-account [address_or_key_name] [coin][,[coin]]", - Short: "Add a genesis account to genesis.json", - Long: `Add a genesis account to genesis.json. The provided account must specify -the account address or key name and a list of initial coins. If a key name is given, -the address will be looked up in the local Keybase. The list of initial tokens must -contain valid denominations. Accounts may optionally be supplied with vesting parameters. -`, - 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) - - var kr keyring.Keyring - addr, err := sdk.AccAddressFromBech32(args[0]) - if err != nil { - inBuf := bufio.NewReader(cmd.InOrStdin()) - keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend) - if err != nil { - return fmt.Errorf("failed to parse keyring backend: %w", err) - } - if keyringBackend != "" && clientCtx.Keyring == nil { - var err error - kr, err = keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf) - if err != nil { - return err - } - } else { - kr = clientCtx.Keyring - } - - info, err := kr.Key(args[0]) - if err != nil { - return fmt.Errorf("failed to get address from Keyring: %w", err) - } - addr = info.GetAddress() - } - - coins, err := sdk.ParseCoinsNormalized(args[1]) - if err != nil { - return fmt.Errorf("failed to parse coins: %w", err) - } - - vestingStart, err := cmd.Flags().GetInt64(flagVestingStart) - if err != nil { - return fmt.Errorf("failed to parse vesting start: %w", err) - } - vestingEnd, err := cmd.Flags().GetInt64(flagVestingEnd) - if err != nil { - return fmt.Errorf("failed to parse vesting end: %w", err) - } - vestingAmtStr, err := cmd.Flags().GetString(flagVestingAmt) - if err != nil { - return fmt.Errorf("failed to parse vesting amount: %w", err) - } - - vestingAmt, err := sdk.ParseCoinsNormalized(vestingAmtStr) - if err != nil { - return fmt.Errorf("failed to parse vesting amount: %w", err) - } - - // create concrete account type based on input parameters - var genAccount authtypes.GenesisAccount - - balances := banktypes.Balance{Address: addr.String(), Coins: coins.Sort()} - baseAccount := authtypes.NewBaseAccount(addr, nil, 0, 0) - - if !vestingAmt.IsZero() { - baseVestingAccount := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd) - - if (balances.Coins.IsZero() && !baseVestingAccount.OriginalVesting.IsZero()) || - baseVestingAccount.OriginalVesting.IsAnyGT(balances.Coins) { - return errors.New("vesting amount cannot be greater than total amount") - } - - switch { - case vestingStart != 0 && vestingEnd != 0: - genAccount = authvesting.NewContinuousVestingAccountRaw(baseVestingAccount, vestingStart) - - case vestingEnd != 0: - genAccount = authvesting.NewDelayedVestingAccountRaw(baseVestingAccount) - - default: - return errors.New("invalid vesting parameters; must supply start and end time or end time") - } - } else { - genAccount = baseAccount - } - - if err := genAccount.Validate(); err != nil { - return fmt.Errorf("failed to validate new genesis account: %w", err) - } - - genFile := config.GenesisFile() - appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile) - if err != nil { - return fmt.Errorf("failed to unmarshal genesis state: %w", err) - } - - authGenState := authtypes.GetGenesisStateFromAppState(clientCtx.Codec, appState) - - accs, err := authtypes.UnpackAccounts(authGenState.Accounts) - if err != nil { - return fmt.Errorf("failed to get accounts from any: %w", err) - } - - if accs.Contains(addr) { - return fmt.Errorf("cannot add account at existing address %s", addr) - } - - // Add the new account to the set of genesis accounts and sanitize the - // accounts afterwards. - accs = append(accs, genAccount) - accs = authtypes.SanitizeGenesisAccounts(accs) - - genAccs, err := authtypes.PackAccounts(accs) - if err != nil { - return fmt.Errorf("failed to convert accounts into any's: %w", err) - } - authGenState.Accounts = genAccs - - authGenStateBz, err := clientCtx.Codec.MarshalJSON(&authGenState) - if err != nil { - return fmt.Errorf("failed to marshal auth genesis state: %w", err) - } - - appState[authtypes.ModuleName] = authGenStateBz - - bankGenState := banktypes.GetGenesisStateFromAppState(clientCtx.Codec, appState) - bankGenState.Balances = append(bankGenState.Balances, balances) - bankGenState.Balances = banktypes.SanitizeGenesisBalances(bankGenState.Balances) - bankGenState.Supply = bankGenState.Supply.Add(balances.Coins...) - - bankGenStateBz, err := clientCtx.Codec.MarshalJSON(bankGenState) - if err != nil { - return fmt.Errorf("failed to marshal bank genesis state: %w", err) - } - - appState[banktypes.ModuleName] = bankGenStateBz - - 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)") - cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts") - cmd.Flags().Int64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") - cmd.Flags().Int64(flagVestingEnd, 0, "schedule end time (unix epoch) for vesting accounts") - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} diff --git a/cmd/terpd/main.go b/cmd/terpd/main.go index 7edc30d..4ecbabd 100644 --- a/cmd/terpd/main.go +++ b/cmd/terpd/main.go @@ -12,7 +12,7 @@ import ( func main() { rootCmd, _ := NewRootCmd() - if err := svrcmd.Execute(rootCmd, app.DefaultNodeHome); err != nil { + if err := svrcmd.Execute(rootCmd, "", app.DefaultNodeHome); err != nil { switch e := err.(type) { case server.ErrorCode: os.Exit(e.Code) diff --git a/cmd/terpd/root.go b/cmd/terpd/root.go index da1702a..28b88bb 100644 --- a/cmd/terpd/root.go +++ b/cmd/terpd/root.go @@ -4,32 +4,31 @@ import ( "errors" "io" "os" - "path/filepath" - "github.com/cosmos/cosmos-sdk/baseapp" + rosettaCmd "cosmossdk.io/tools/rosetta/cmd" + dbm "github.com/cometbft/cometbft-db" + tmcfg "github.com/cometbft/cometbft/config" + "github.com/cometbft/cometbft/libs/log" "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" "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/server" + serverconfig "github.com/cosmos/cosmos-sdk/server/config" servertypes "github.com/cosmos/cosmos-sdk/server/types" - "github.com/cosmos/cosmos-sdk/snapshots" - "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" "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" - tmcli "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" + "github.com/spf13/viper" "github.com/terpnetwork/terp-core/app" "github.com/terpnetwork/terp-core/app/params" @@ -57,13 +56,12 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { WithLegacyAmino(encodingConfig.Amino). WithInput(os.Stdin). WithAccountRetriever(authtypes.AccountRetriever{}). - WithBroadcastMode(flags.BroadcastBlock). WithHomeDir(app.DefaultNodeHome). - WithViper("") + WithViper("") // In terpd, we don't use any prefix for env variables. rootCmd := &cobra.Command{ Use: version.AppName, - Short: "Wasm Daemon (server)", + Short: "Terp Network Daemon (server)", PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { // set the default command outputs cmd.SetOut(cmd.OutOrStdout()) @@ -83,7 +81,10 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { return err } - return server.InterceptConfigsPreRunHandler(cmd, "", nil) + customAppTemplate, customAppConfig := initAppConfig() + customTMConfig := initTendermintConfig() + + return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customTMConfig) }, } @@ -92,31 +93,79 @@ func NewRootCmd() (*cobra.Command, params.EncodingConfig) { return rootCmd, encodingConfig } +// initTendermintConfig helps to override default Tendermint Config values. +// return tmcfg.DefaultConfig if no custom configuration is required for the application. +func initTendermintConfig() *tmcfg.Config { + cfg := tmcfg.DefaultConfig() + + // these values put a higher strain on node memory + // cfg.P2P.MaxNumInboundPeers = 100 + // cfg.P2P.MaxNumOutboundPeers = 40 + + return cfg +} + +// initAppConfig helps to override default appConfig template and configs. +// return "", nil if no custom configuration is required for the application. +func initAppConfig() (string, interface{}) { + // The following code snippet is just for reference. + + type CustomAppConfig struct { + serverconfig.Config + + Wasm wasmtypes.WasmConfig `mapstructure:"wasm"` + } + + // Optionally allow the chain developer to overwrite the SDK's default + // server config. + srvCfg := serverconfig.DefaultConfig() + // The SDK's default minimum gas price is set to "" (empty value) inside + // app.toml. If left empty by validators, the node will halt on startup. + // However, the chain developer can set a default app.toml value for their + // validators here. + // + // In summary: + // - if you leave srvCfg.MinGasPrices = "", all validators MUST tweak their + // own app.toml config, + // - if you set srvCfg.MinGasPrices non-empty, validators CAN tweak their + // own app.toml to override, or use this default value. + // + // In simapp, we set the min gas prices to 0. + srvCfg.MinGasPrices = "0stake" + // srvCfg.BaseConfig.IAVLDisableFastNode = true // disable fastnode by default + + customAppConfig := CustomAppConfig{ + Config: *srvCfg, + Wasm: wasmtypes.DefaultWasmConfig(), + } + + customAppTemplate := serverconfig.DefaultConfigTemplate + + wasmtypes.DefaultConfigTemplate() + + return customAppTemplate, customAppConfig +} + func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) { rootCmd.AddCommand( genutilcli.InitCmd(app.ModuleBasics, app.DefaultNodeHome), - genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome), - genutilcli.GenTxCmd(app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome), - genutilcli.ValidateGenesisCmd(app.ModuleBasics), - AddGenesisAccountCmd(app.DefaultNodeHome), - tmcli.NewCompletionCmd(rootCmd, true), // testnetCmd(app.ModuleBasics, banktypes.GenesisBalancesIterator{}), debug.Cmd(), config.Cmd(), + pruning.PruningCmd(newApp), ) - ac := appCreator{ - encCfg: encodingConfig, - } - server.AddCommands(rootCmd, app.DefaultNodeHome, ac.newApp, ac.appExport, addModuleInitFlags) + server.AddCommands(rootCmd, app.DefaultNodeHome, newApp, appExport, addModuleInitFlags) // add keybase, auxiliary RPC, query, and tx child commands rootCmd.AddCommand( rpc.StatusCommand(), + genesisCommand(encodingConfig), queryCommand(), txCommand(), keys.Commands(app.DefaultNodeHome), ) + // add rosetta + rootCmd.AddCommand(rosettaCmd.RosettaCommand(encodingConfig.InterfaceRegistry, encodingConfig.Marshaler)) } func addModuleInitFlags(startCmd *cobra.Command) { @@ -124,12 +173,22 @@ func addModuleInitFlags(startCmd *cobra.Command) { wasm.AddModuleInitFlags(startCmd) } +// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter +func genesisCommand(encodingConfig params.EncodingConfig, cmds ...*cobra.Command) *cobra.Command { + cmd := genutilcli.GenesisCoreCommand(encodingConfig.TxConfig, app.ModuleBasics, app.DefaultNodeHome) + + for _, subCmd := range cmds { + cmd.AddCommand(subCmd) + } + return cmd +} + func queryCommand() *cobra.Command { cmd := &cobra.Command{ Use: "query", Aliases: []string{"q"}, Short: "Querying subcommands", - DisableFlagParsing: true, + DisableFlagParsing: false, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } @@ -143,7 +202,6 @@ func queryCommand() *cobra.Command { ) app.ModuleBasics.AddQueryCommands(cmd) - cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") return cmd } @@ -152,7 +210,7 @@ func txCommand() *cobra.Command { cmd := &cobra.Command{ Use: "tx", Short: "Transactions subcommands", - DisableFlagParsing: true, + DisableFlagParsing: false, SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } @@ -163,80 +221,42 @@ func txCommand() *cobra.Command { authcmd.GetMultiSignCommand(), authcmd.GetMultiSignBatchCmd(), authcmd.GetValidateSignaturesCommand(), - flags.LineBreak, authcmd.GetBroadcastCommand(), authcmd.GetEncodeCommand(), authcmd.GetDecodeCommand(), + authcmd.GetAuxToFeeCommand(), ) app.ModuleBasics.AddTxCommands(cmd) - cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") return cmd } -type appCreator struct { - encCfg params.EncodingConfig -} - -func (ac appCreator) newApp( +// newApp creates the application +func newApp( logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions, ) servertypes.Application { - var cache sdk.MultiStorePersistentCache - - if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) { - cache = store.NewCommitKVStoreCacheManager() - } - - skipUpgradeHeights := make(map[int64]bool) - for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { - skipUpgradeHeights[int64(h)] = true - } - - pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts) - if err != nil { - panic(err) - } + baseappOptions := server.DefaultBaseappOptions(appOpts) - snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots") - snapshotDB, err := sdk.NewLevelDB("metadata", snapshotDir) - if err != nil { - panic(err) - } - snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) - if err != nil { - panic(err) - } var wasmOpts []wasm.Option if cast.ToBool(appOpts.Get("telemetry.enabled")) { wasmOpts = append(wasmOpts, wasmkeeper.WithVMCacheMetrics(prometheus.DefaultRegisterer)) } - return app.NewTerpApp(logger, db, traceStore, true, skipUpgradeHeights, - cast.ToString(appOpts.Get(flags.FlagHome)), - cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), - ac.encCfg, + return app.NewTerpApp( + logger, db, traceStore, true, app.GetEnabledProposals(), appOpts, wasmOpts, - baseapp.SetPruning(pruningOpts), - baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(server.FlagMinGasPrices))), - baseapp.SetHaltHeight(cast.ToUint64(appOpts.Get(server.FlagHaltHeight))), - baseapp.SetHaltTime(cast.ToUint64(appOpts.Get(server.FlagHaltTime))), - baseapp.SetMinRetainBlocks(cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks))), - baseapp.SetInterBlockCache(cache), - baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))), - baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents))), - baseapp.SetSnapshotStore(snapshotStore), - baseapp.SetSnapshotInterval(cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval))), - baseapp.SetSnapshotKeepRecent(cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent))), + baseappOptions..., ) } -func (ac appCreator) appExport( +// appExport creates a new wasm app (optionally at a given height) and exports state. +func appExport( logger log.Logger, db dbm.DB, traceStore io.Writer, @@ -244,6 +264,7 @@ func (ac appCreator) appExport( forZeroHeight bool, jailAllowedAddrs []string, appOpts servertypes.AppOptions, + modulesToExport []string, ) (servertypes.ExportedApp, error) { var wasmApp *app.TerpApp homePath, ok := appOpts.Get(flags.FlagHome).(string) @@ -251,17 +272,21 @@ func (ac appCreator) appExport( return servertypes.ExportedApp{}, errors.New("application home is not set") } - loadLatest := height == -1 + viperAppOpts, ok := appOpts.(*viper.Viper) + if !ok { + return servertypes.ExportedApp{}, errors.New("appOpts is not viper.Viper") + } + + // overwrite the FlagInvCheckPeriod + viperAppOpts.Set(server.FlagInvCheckPeriod, 1) + appOpts = viperAppOpts + var emptyWasmOpts []wasm.Option wasmApp = app.NewTerpApp( logger, db, traceStore, - loadLatest, - map[int64]bool{}, - homePath, - cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), - ac.encCfg, + height == -1, app.GetEnabledProposals(), appOpts, emptyWasmOpts, @@ -273,5 +298,5 @@ func (ac appCreator) appExport( } } - return wasmApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs) + return wasmApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) } diff --git a/config.yml b/config.yml new file mode 100644 index 0000000..ce1af9f --- /dev/null +++ b/config.yml @@ -0,0 +1,16 @@ +accounts: + - name: alex + coins: ["20000token", "200000000stake"] + - name: bob + coins: ["10000token", "100000000stake"] +validator: + name: alex + staked: "100000000stake" +client: + openapi: + path: "docs/static/openapi.yml" +faucet: + name: bob + coins: ["5token", "100000stake"] +build: + main: "cmd/terpd" diff --git a/contrib/devtools/Makefile b/contrib/devtools/Makefile index 611f0c4..1f2c3a5 100644 --- a/contrib/devtools/Makefile +++ b/contrib/devtools/Makefile @@ -76,7 +76,7 @@ $(RUNSIM): golangci-lint: $(GOLANGCI_LINT) $(GOLANGCI_LINT): @echo "Installing golangci-lint..." - @(cd /tmp && go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.47.0) + @(cd /tmp && go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.47) tools-clean: rm -f $(STATIK) $(GOLANGCI_LINT) $(RUNSIM) diff --git a/contrib/devtools/README.md b/contrib/devtools/README.md index 659804a..6cd3450 100644 --- a/contrib/devtools/README.md +++ b/contrib/devtools/README.md @@ -3,4 +3,4 @@ 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/master/contrib/devtools/Makefile \ No newline at end of file +https://github.com/cosmos/cosmos-sdk/blob/masSSter/contrib/devtools/Makefile \ No newline at end of file diff --git a/contrib/local/00-genesis.sh b/contrib/local/00-genesis.sh deleted file mode 100755 index f7a90e0..0000000 --- a/contrib/local/00-genesis.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash -set -o errexit -o nounset -o pipefail - -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" -BASE_ACCOUNT=$(terpd keys show validator -a) - -echo "-----------------------" -echo "## Genesis CosmWasm contract" -terpd add-wasm-genesis-message store "$DIR/../../x/wasm/keeper/testdata/hackatom.wasm" --instantiate-everybody true --builder=foo/bar:latest --run-as validator - -echo "-----------------------" -echo "## Genesis CosmWasm instance" -INIT="{\"verifier\":\"$(terpd keys show validator -a)\", \"beneficiary\":\"$(terpd keys show fred -a)\"}" -terpd add-wasm-genesis-message instantiate-contract 1 "$INIT" --run-as validator --label=foobar --amount=100ustake --admin "$BASE_ACCOUNT" - -echo "-----------------------" -echo "## Genesis CosmWasm execute" -FIRST_CONTRACT_ADDR=wasm18vd8fpwxzck93qlwghaj6arh4p7c5n89k7fvsl -MSG='{"release":{}}' -terpd add-wasm-genesis-message execute $FIRST_CONTRACT_ADDR "$MSG" --run-as validator --amount=1ustake - -echo "-----------------------" -echo "## List Genesis CosmWasm codes" -terpd add-wasm-genesis-message list-codes - -echo "-----------------------" -echo "## List Genesis CosmWasm contracts" -terpd add-wasm-genesis-message list-contracts diff --git a/contrib/local/01-accounts.sh b/contrib/local/01-accounts.sh index 54a9a8c..c58e467 100755 --- a/contrib/local/01-accounts.sh +++ b/contrib/local/01-accounts.sh @@ -1,18 +1,18 @@ #!/bin/bash set -o errexit -o nounset -o pipefail -BASE_ACCOUNT=$(terpd keys show validator -a) +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 +terpd keys add fred --keyring-backend=test echo "## Check balance" -NEW_ACCOUNT=$(terpd keys show fred -a) +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 block -o json | jq +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 index 8d8089c..4544d0b 100755 --- a/contrib/local/02-contracts.sh +++ b/contrib/local/02-contracts.sh @@ -6,10 +6,11 @@ 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 block -o json) - -CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[1].attributes[-1].value') -CODE_HASH=$(echo "$RESP" | jq -r '.logs[0].events[1].attributes[-2].value') + --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" @@ -19,26 +20,31 @@ terpd q wasm code "$CODE_ID" "$TMPDIR" rm -f "$TMPDIR" echo "-----------------------" echo "## List code" -terpd query wasm list-code --node=http://localhost:26657 --chain-id=testing -o json | jq +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)\", \"beneficiary\":\"$(terpd keys show fred -a)\"}" -terpd tx wasm instantiate "$CODE_ID" "$INIT" --admin="$(terpd keys show validator -a)" \ +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 block -o json | jq + --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" -terpd tx wasm instantiate2 "$CODE_ID" "$INIT" $(echo -n "testing" | xxd -ps) \ - --admin="$(terpd keys show validator -a)" \ +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 block -o json | jq + --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) $(echo -n "testing" | xxd -ps) "$INIT") +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" @@ -53,30 +59,39 @@ terpd query wasm contract-state raw "$CONTRACT" "$KEY" -o json | jq echo "-----------------------" echo "## Execute contract $CONTRACT" MSG='{"release":{}}' -terpd tx wasm execute "$CONTRACT" "$MSG" \ +RESP=$(terpd tx wasm execute "$CONTRACT" "$MSG" \ --from validator \ - --gas 1000000 -y --chain-id=testing -b block -o json | jq + --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" -terpd tx wasm set-contract-admin "$CONTRACT" "$(terpd keys show fred -a)" \ - --from validator -y --chain-id=testing -b block -o json | jq +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 block -o json) - -BURNER_CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[1].attributes[-1].value') + --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) -terpd tx wasm migrate "$CONTRACT" "$BURNER_CODE_ID" "{\"payout\": \"$DEST_ACCOUNT\"}" --from fred \ - --chain-id=testing -b block -y -o json | jq +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 @@ -90,6 +105,8 @@ echo "-----------------------" echo "## Clear contract admin" echo "### Query old admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" echo "### Update contract" -terpd tx wasm clear-contract-admin "$CONTRACT" \ - --from fred -y --chain-id=testing -b block -o json | jq -echo "### Query new admin: $(terpd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')" +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 index 063bd06..4544d0b 100755 --- a/contrib/local/03-grpc-queries.sh +++ b/contrib/local/03-grpc-queries.sh @@ -1,31 +1,112 @@ #!/bin/bash -set -o errexit -o nounset -o pipefail +set -o errexit -o nounset -o pipefail -x DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" echo "-----------------------" -PROTO_THRD="$DIR/../../third_party/proto" -PROTO_TERPD="$DIR/../../proto" -PROTO_TERPD_QUERY="$PROTO_TERPD/cosmwasm/wasm/v1/query.proto" +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 "### List all codes" -RESP=$(grpcurl -plaintext -import-path "$PROTO_THRD" -import-path "$PROTO_TERPD" -proto "$PROTO_TERPD_QUERY" \ - localhost:9090 cosmwasm.wasm.v1.Query/Codes) -echo "$RESP" | jq +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" -CODE_ID=$(echo "$RESP" | jq -r '.codeInfos[-1].codeId') -echo "### List contracts by code" -RESP=$(grpcurl -plaintext -import-path "$PROTO_THRD" -import-path "$PROTO_TERPD" -proto "$PROTO_TERPD_QUERY" \ - -d "{\"codeId\": $CODE_ID}" localhost:9090 cosmwasm.wasm.v1.Query/ContractsByCode) +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 "### Show history for contract" -CONTRACT=$(echo "$RESP" | jq -r ".contracts[-1]") -grpcurl -plaintext -import-path "$PROTO_THRD" -import-path "$PROTO_TERPD" -proto "$PROTO_TERPD_QUERY" \ - -d "{\"address\": \"$CONTRACT\"}" localhost:9090 cosmwasm.wasm.v1.Query/ContractHistory | 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 "### Show contract state" -grpcurl -plaintext -import-path "$PROTO_THRD" -import-path "$PROTO_TERPD" -proto "$PROTO_TERPD_QUERY" \ - -d "{\"address\": \"$CONTRACT\"}" localhost:9090 cosmwasm.wasm.v1.Query/AllContractState | 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" -echo "Empty state due to 'burner' contract cleanup" +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 index b070672..234e442 100644 --- a/contrib/local/README.md +++ b/contrib/local/README.md @@ -8,7 +8,7 @@ For manual testing. Works on my box(*) ... make install cd contrib/local rm -rf /tmp/trash -HOME=/tmp/trash bash setup_terpd.sh +HOME=/tmp/trash bash setup_wasmd.sh HOME=/tmp/trash bash start_node.sh ``` diff --git a/contrib/local/setup_wasmd.sh b/contrib/local/setup_terpd.sh similarity index 65% rename from contrib/local/setup_wasmd.sh rename to contrib/local/setup_terpd.sh index ada14d8..8c25e0b 100755 --- a/contrib/local/setup_wasmd.sh +++ b/contrib/local/setup_terpd.sh @@ -11,18 +11,18 @@ 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; then +if ! terpd keys show validator --keyring-backend=test; then ( echo "$PASSWORD" echo "$PASSWORD" - ) | terpd keys add validator + ) | terpd keys add validator --keyring-backend=test fi # hardcode the validator account for this instance -echo "$PASSWORD" | terpd add-genesis-account validator "1000000000$STAKE,1000000000$FEE" +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 add-genesis-account "$addr" "1000000000$STAKE,1000000000$FEE" + 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 @@ -30,7 +30,7 @@ done echo "$PASSWORD" echo "$PASSWORD" echo "$PASSWORD" -) | terpd gentx validator "250000000$STAKE" --chain-id="$CHAIN_ID" --amount="250000000$STAKE" +) | 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 collect-gentxs +terpd genesis collect-gentxs diff --git a/contrib/local/start_node.sh b/contrib/local/start_node.sh index 9834077..8bd2a2c 100755 --- a/contrib/local/start_node.sh +++ b/contrib/local/start_node.sh @@ -1,4 +1,4 @@ #!/bin/bash set -eu -terpd start --rpc.laddr tcp://0.0.0.0:26657 --log_level=info --trace # --trace # does not work anymore: --log_level="main:info,state:debug,*:error" +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 index 5c2e947..c3864e5 100644 --- a/contrib/prometheus/README.md +++ b/contrib/prometheus/README.md @@ -1,9 +1,7 @@ # Setup - Enable prometheus metrics in terpd: -- Edit `$HOME/config/app.toml` - +* Edit `$HOME/config/app.toml` ```toml [telemetry] @@ -19,8 +17,8 @@ prometheus-retention-time = 15 `retention-time` must be >0 (see prometheus scrape config) -- Edit `$HOME/config/config.toml` +* Edit `$HOME/config/config.toml` ```toml [instrumentation] @@ -35,26 +33,21 @@ Test manually at: Note the `format` parameter in the request for the endpoint: -# Local testing +# 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 +* 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` - +* Add Prometheus data source +`http://host.docker.internal:9091` ### Labels - -- `wasm_contract_create` = nanosec +* `wasm_contract_create` = nanosec \ No newline at end of file diff --git a/docker/setup_terpd.sh b/docker/setup_terpd.sh index b6811be..c80a89b 100755 --- a/docker/setup_terpd.sh +++ b/docker/setup_terpd.sh @@ -2,9 +2,9 @@ #set -o errexit -o nounset -o pipefail PASSWORD=${PASSWORD:-1234567890} -STAKE=${STAKE_TOKEN:-uterp} -FEE=${FEE_TOKEN:-uthoil} -CHAIN_ID=${CHAIN_ID:-testing} +STAKE=${STAKE_TOKEN:-uterpx} +FEE=${FEE_TOKEN:-uthiolx} +CHAIN_ID=${CHAIN_ID:-athena-4} MONIKER=${MONIKER:-node001} terpd init --chain-id "$CHAIN_ID" "$MONIKER" @@ -17,17 +17,17 @@ if ! terpd keys show validator; then (echo "$PASSWORD"; echo "$PASSWORD") | terpd keys add validator fi # hardcode the validator account for this instance -echo "$PASSWORD" | terpd add-genesis-account validator "1000000000$STAKE,1000000000$FEE" +echo "$PASSWORD" | terpd genesis add-genesis-account validator "1000000000$STAKE,1000000000$FEE" # (optionally) add a few more genesis accounts for addr in "$@"; do echo $addr - terpd add-genesis-account "$addr" "1000000000$STAKE,1000000000$FEE" + terpd genesis add-genesis-account "$addr" "1000000000$STAKE,1000000000$FEE" done # submit a genesis validator tx ## Workraround for https://github.com/cosmos/cosmos-sdk/issues/8251 -(echo "$PASSWORD"; echo "$PASSWORD"; echo "$PASSWORD") | terpd gentx validator "250000000$STAKE" --chain-id="$CHAIN_ID" --amount="250000000$STAKE" +(echo "$PASSWORD"; echo "$PASSWORD"; echo "$PASSWORD") | terpd gentx validator "1000000$STAKE" --chain-id="$CHAIN_ID" --amount="1000000$STAKE" ## should be: -# (echo "$PASSWORD"; echo "$PASSWORD"; echo "$PASSWORD") | terpd gentx validator "250000000$STAKE" --chain-id="$CHAIN_ID" -terpd collect-gentxs +# (echo "$PASSWORD"; echo "$PASSWORD"; echo "$PASSWORD") | terpd gentx validator "1000000$STAKE" --chain-id="$CHAIN_ID" +terpd genesis collect-gentxs diff --git a/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md similarity index 98% rename from CODE_OF_CONDUCT.md rename to docs/CODE_OF_CONDUCT.md index 55151c3..c0261e7 100644 --- a/CODE_OF_CONDUCT.md +++ b/docs/CODE_OF_CONDUCT.md @@ -43,4 +43,4 @@ Project maintainers who do not follow or enforce the Code of Conduct in good fai 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/ \ No newline at end of file +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/docs/CODING_GUIDELINES.md b/docs/CODING_GUIDELINES.md index b6d2b5c..eda2155 100644 --- a/docs/CODING_GUIDELINES.md +++ b/docs/CODING_GUIDELINES.md @@ -10,7 +10,6 @@ This document is an extension to [CONTRIBUTING](./CONTRIBUTING.md) and provides * 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. -* Take advantage of `internal` package concept. * 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. @@ -31,94 +30,22 @@ Security: * 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. -## Acceptance tests - -Start the design by defining Acceptance Tests. The purpose of Acceptance Testing is to -validate that the product being developed corresponds to the needs of the real users -and is ready for launch. Hence we often talk about **User Acceptance Test** (UAT). -It also gives a better understanding of the product and helps designing a right interface -and API. - -UAT should be revisited at each stage of the product development: - -![acceptance-tests.png](https://github.com/cosmos/cosmos-sdk/blob/main/docs/static/img/acceptance-tests.png) - -### Why Acceptance Testing - -* Automated acceptance tests catch serious problems that unit or component test suites could never catch. -* Automated acceptance tests deliver business value the users are expecting as they test user scenarios. -* Automated acceptance tests executed and passed on every build help improve the software delivery process. -* Testers, developers, and customers need to work closely to create suitable automated acceptance test suites. - -### How to define Acceptance Test - -The best way to define AT is by starting from the user stories and think about all positive and negative scenarios a user can perform. - -Product Developers should collaborate with stakeholders to define AT. Functional experts and business users are both needed for defining AT. - -A good pattern for defining AT is listing scenarios with [GIVEN-WHEN-THEN](https://martinfowler.com/bliki/GivenWhenThen.html) format where: - -* **GIVEN**: A set of initial circumstances (e.g. bank balance) -* **WHEN**: Some event happens (e.g. customer attempts a transfer) -* **THEN**: The expected result as per the defined behavior of the system - -In other words: we define a use case input, current state and the expected outcome. Example: - -> Feature: User trades stocks. -> Scenario: User requests a sell before close of trading -> -> Given I have 100 shares of MSFT stock -> And I have 150 shares of APPL stock -> And the time is before close of trading -> -> When I ask to sell 20 shares of MSFT stock -> -> Then I should have 80 shares of MSFT stock -> And I should have 150 shares of APPL stock -> And a sell order for 20 shares of MSFT stock should have been executed - -*Reference: [writing acceptance tests](https://openclassrooms.com/en/courses/4544611-write-agile-documentation-user-stories-acceptance-tests/4810081-writing-acceptance-tests)*. - -### How and where to add acceptance tests - -Acceptance tests are written in the Markdown format, using the scenario template described above, and be part of the specification (`xx_test.md` file in *spec* directory). Example: [`eco-credits/spec/06.test.md`](https://github.com/regen-network/regen-ledger/blob/7297783577e6cd102c5093365b573163680f36a1/x/ecocredit/spec/06_tests.md). - -Acceptance tests should be defined during the design phase or at an early stage of development. Moreover, they should be defined before writing a module architecture - it will clarify the purpose and usage of the software. -Automated tests should cover all acceptance tests scenarios. - -## Automated Tests - -TBD - -## Quality Assurance - -We are forming a QA team that will support the core terp-core team and collaborators by: - -* Improving the Terp-Core QA Processes -* Improving automation in QA and testing -* Defining high-quality metrics -* Maintaining and improving testing frameworks (unit tests, integration tests, and functional tests) -* Defining test scenarios. -* Verifying user experience and defining a high quality. - * We want to have **acceptance tests**! Document and list acceptance lists that are implemented and identify acceptance tests that are still missing. - * Acceptance tests should be specified in `acceptance-tests` directory as Markdown files. -* Supporting other teams with testing frameworks, automation, and User Experience testing. -* Testing chain upgrades for every new breaking change. - * Defining automated tests that assure data integrity after an update. - -Desired outcomes: - -* QA team works with Development Team. -* QA is happening in parallel with Core Terp-Core development. -* Releases are more predictable. -* QA reports. Goal is to guide with new tasks and be one of the QA measures. - -As a developer, you must help the QA team by providing instructions for User Experience (UX) and functional testing. - -### QA Team to cross check Acceptance Tests - -Once the AT are defined, the QA team will have an overview of the behavior a user can expect and: - -* validate the user experience will be good -* validate the implementation conforms the acceptance tests -* by having a broader overview of the use cases, QA team should be able to define **test suites** and test data to efficiently automate Acceptance Tests and reuse the work. \ No newline at end of file +## 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 index c8a796d..05cb53b 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -1,41 +1,16 @@ # Contributing -* [Contributing](#contributing) - * [Teams Dev Calls](#teams-dev-calls) - * [Architecture Decision Records (ADR)](#architecture-decision-records-adr) - * [Development Procedure](#development-procedure) - * [Testing](#testing) - * [Pull Requests](#pull-requests) - * [Pull Request Templates](#pull-request-templates) - * [Requesting Reviews](#requesting-reviews) - * [Updating Documentation](#updating-documentation) - * [Dependencies](#dependencies) - * [`go.work`](#gowork) - * [Protobuf](#protobuf) - * [Branching Model and Release](#branching-model-and-release) - * [PR Targeting](#pr-targeting) - * [Code Owner Membership](#code-owner-membership) - * [Concept & Feature Approval Process](#concept--feature-approval-process) - * [Strategy Discovery](#strategy-discovery) - * [Concept Approval](#concept-approval) - * [Time Bound Period](#time-bound-period) - * [Approval Committee & Decision Making](#approval-committee--decision-making) - * [Committee Members](#committee-members) - * [Committee Criteria](#committee-criteria) - * [Implementation & Release Approval](#implementation--release-approval) - -Thank you for considering making contributions to the Terp-Core and related repositories! +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) and [discussions](https://github.com/terpnetwork/terp-core/discussions). If you are looking for something interesting or if you have something in your mind, there is a chance it had been discussed. - * 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:open+is:issue+label:%22good+first+issue%22) or [bugs](https://github.com/terpnetwork/terp-core/issues?q=is:open+is:issue+label:%22T:+Bug%22)? +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 want to propose something new that requires specification or an additional design, or you would like to change a process, start with a [new discussion](https://github.com/terpnetwork/terp-core/discussions/new). With discussions, we can better handle the design process using discussion threads. A discussion usually leads to one or more issues. - 2. 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/choose). - 3. Review existing [issues](https://github.com/terpnetwork/terp-core/issues) to find an issue you'd like to help with. + 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. @@ -51,132 +26,56 @@ 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. -## Teams Dev Calls - -The Terp Network is growing its stakeholders contributing and shaping the project. The TerpNET team is composed of Discover Decentralization and others focused on ensure decentralization. Any long-term contributors and additional maintainers from other projects are welcome. We use self-organizing principles to coordinate and collaborate across organizations in structured "EPIC" that focus on specific problem domains or architectural components of the Terp-Core. - -The developers work in sprints, which are available in a [GitHub Project](https://docs.github.com/en/issues/planning-and-tracking-with-projects). The current EPICs are pinned at the top of the [issues list](https://github.com/terpnetwork/terp-core/issues). - -The important development announcements are shared on [Discord](https://discord.com/invite/terpnetwork) in the `#dev-announcements` channel. - -To synchronize we have few major meetings: - -* Terp-Core Review on Every 1st & 3rd Monday at a determined time UTC (limited participation to core devs). -* Terp-Core Community Call on the Third Thursday at a determined time UTC. - -If you would like to join one of the community call, then please contact us on [Discord](https://discord.com/invite/terpnetwork). - -## Architecture Decision Records (ADR) - -When proposing an architecture decision for the Terp-Core, please start by opening an [issue](https://github.com/terpnetwork/terp-core/issues/new/choose) or a [discussion](https://github.com/terpnetwork/terp-core/discussions/new) with a summary of the proposal. Once the proposal has been discussed and there is rough alignment on a high-level approach to the design, the [ADR creation process](https://github.com/t/cosmos-sdk/blob/main/docs/architecture/PROCESS.md) can begin. We are following this process to ensure all involved parties are in agreement before any party begins coding the proposed implementation. If you would like to see examples of how these are written, please refer to the current [ADRs](https://github.com/cosmos/cosmos-sdk/tree/main/docs/architecture). - ## Development Procedure * The latest state of development is on `main`. -* `main` must never fail any future implemented network. +* `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 Terp-Core repo), + * 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 `terp-core` repo, follow branch name conventions to ensure a clear - ownership of branches: `{moniker}/{issue#}-branch-name`. + * 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. -* 'make format' TBD. +* 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 are slowly being integrated to improve the reliability of our confidence in changes made to the terp-core repository. +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` TBD. +* 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. Go through the actions for each checkbox present in the PR template description. The PR actions are automatically provided for each new PR. -4. 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. - +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. -Pull requests are merged automatically using [`A:automerge` action](https://mergify.io/features/auto-merge). +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. -### Pull Request Templates - -There are three PR templates. The [default template](./.github/PULL_REQUEST_TEMPLATE.md) is for types `fix`, `feat`, and `refactor`. We also have a [docs template](./.github/PULL_REQUEST_TEMPLATE/docs.md) for documentation changes and an [other template](./.github/PULL_REQUEST_TEMPLATE/other.md) for changes that do not affect production code. When previewing a PR before it has been opened, you can change the template by adding one of the following parameters to the url: - -* `template=docs.md` -* `template=other.md` - -### Requesting Reviews - -In order to accommodate the review process, the author of the PR must complete the author checklist -(from the pull request template) -to the best of their abilities before marking the PR as "Ready for Review". If you would like to -receive early feedback on the PR, open the PR as a "Draft" and leave a comment in the PR indicating -that you would like early feedback and tagging whoever you would like to receive feedback from. - -Codeowners are marked automatically as the reviewers. - -All PRs require at least two review approvals before they can be merged (one review might be acceptable in -the case of minor changes to [docs](./.github/PULL_REQUEST_TEMPLATE/docs.md) or [other](./.github/PULL_REQUEST_TEMPLATE/other.md) changes that do not affect production code). Each PR template has a reviewers checklist that must be completed before the PR can be merged. Each reviewer is responsible -for all checked items unless they have indicated otherwise by leaving their handle next to specific -items. In addition, use the following review explanations: - -* `LGTM` without an explicit approval means that the changes look good, but you haven't thoroughly reviewed the reviewer checklist items. -* `Approval` means that you have completed some or all of the reviewer checklist items. If you only reviewed selected items, you must add your handle next to the items that you have reviewed. In addition, follow these guidelines: - * You must also think through anything which ought to be included but is not - * You must think through whether any added code could be partially combined (DRYed) with existing code - * You must think through any potential security issues or incentive-compatibility flaws introduced by the changes - * Naming must be consistent with conventions and the rest of the codebase - * Code must live in a reasonable location, considering dependency structures (for example, not importing testing modules in production code, or including example code modules in production code). - * If you approve the PR, you are responsible for any issues mentioned here and any issues that should have been addressed after thoroughly reviewing the reviewer checklist items in the pull request template. -* If you sat down with the PR submitter and did a pairing review, add this information in the `Approval` or your PR comments. -* If you are only making "surface level" reviews, submit notes as a `comment` review. - -### Updating Documentation - -If you open a PR on the Terp-Core, it is mandatory to update the relevant documentation in `/docs`. - -* If your change relates to the core SDK (baseapp, store, ...), be sure to update the content in `docs/basics/`, `docs/core/` and/or `docs/building-modules/` folders. -* If your changes relate to the core of the CLI (not specifically to module's CLI/Rest), then modify the content in the `docs/run-node/` folder. -* If your changes relate to a module, then be sure to update the module's spec in `x/{moduleName}/README.md`. - -When writing documentation, follow the [Documentation Writing Guidelines](./docs/DOC_WRITING_GUIDELINES.md). - -## Dependencies - -We use [Go Modules](https://github.com/golang/go/wiki/Modules) to manage -dependency versions. - -Since some dependencies are not under our control, a third party may break our -build, in which case we can fall back on `go mod tidy -v`. - -### `go.work` - -The Terp-Core is a multi-module repo, for this reason, the use of a `go.work` file is handy. -We provide a [`go.work.example`](./go.work.example) that contains all the modules used in the SDK. -Do note that contributions modifying multiple Go modules should be submitted as separate PRs, this allows us to tag the changes and avoid `replace`s. -For consistency between our CI and the local tests, `GOWORK=off` is set in the `Makefile`. This means that the `go.work` file is not used when using `make test` or any other `make` command. - ## 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 the Terp Core. +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 and checking breaking changes, we use [buf](https://buf.build/). You can use the commands `make proto-lint` and `make proto-check-breaking` to respectively lint your proto files and check for breaking changes. +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`. @@ -200,9 +99,7 @@ For example, in vscode your `.vscode/settings.json` should look like: 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`. -The Terp-Core repository is a [multi Go module](https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository) repository. It means that we have more than one Go module in a single repository. - -The Terp-Core utilizes [semantic versioning](https://semver.org/). +Wasmd utilizes [semantic versioning](https://semver.org/). ### PR Targeting @@ -210,116 +107,4 @@ 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). - -## Code Owner Membership - -In the ethos of open-source projects, and out of necessity to keep the code -alive, the core contributor team will strive to permit special repo privileges -to developers who show an aptitude towards developing with this code base. - -Several different kinds of privileges may be granted however most common -privileges to be granted are merge rights to either part of, or the entirety of the -code base (through the GitHub `CODEOWNERS` file). The on-boarding process for -new code owners is as follows: On a bi-monthly basis (or more frequently if -agreeable) all the existing code owners will privately convene to discuss -potential new candidates as well as the potential for existing code-owners to -exit or "pass on the torch". This private meeting is to be a held as a -phone/video meeting. - -Subsequently after the meeting, and pending final approval from the Terp Foundation, -one of the existing code owners should open a PR modifying the `CODEOWNERS` file. -The other code owners should then all approve this PR to publicly display their support. - -Only if unanimous consensus is reached among all the existing code-owners will -an invitation be extended to a new potential-member. Likewise, when an existing -member is suggested to be removed/or have their privileges reduced, the member -in question must agree to the decision for their removal or else no action -should be taken. If however, a code-owner is demonstrably shown to intentionally -have had acted maliciously or grossly negligent, code-owner privileges may be -stripped with no prior warning or consent from the member in question. - -Other potential removal criteria: - -* Missing 3 scheduled meetings results in the Foundation evaluating whether the member should be - removed / replaced -* Violation of Code of Conduct - -Earning this privilege should be considered to be no small feat and is by no -means guaranteed by any quantifiable metric. Serving as a code owner is a symbol of great trust from -the community of this project. - -## Concept & Feature Approval Process - -The process for how Terp-Core maintainers take features and ADRs from concept to release -is broken up into three distinct stages: **Strategy Discovery**, **Concept Approval**, and -**Implementation & Release Approval** - -### Strategy Discovery - -* Develop long term priorities, strategy and roadmap for the Terp-Core -* Release committee not yet defined as there is already a roadmap that can be used for the time being - -### Concept Approval - -* Architecture Decision Records (ADRs) may be proposed by any contributors or maintainers of the Terp-Core, - and should follow the guidelines outlined in the - [ADR Creation Process](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/PROCESS.md) -* After proposal, a time bound period for Request for Comment (RFC) on ADRs commences -* ADRs are intended to be iterative, and may be merged into `main` while still in a `Proposed` status - -#### Time Bound Period - -* Once a PR for an ADR is opened, reviewers are expected to perform a first review within 1 week of pull request being open -* Time bound period for individual ADR Pull Requests to be merged should not exceed 2 weeks -* Total time bound period for an ADR to reach a decision (`ABANDONED | ACCEPTED | REJECTED`) should not exceed 4 weeks - -If an individual Pull Request for an ADR needs more time than 2 weeks to reach resolution, it should be merged -in current state (`Draft` or `Proposed`), with its contents updated to summarize -the current state of its discussion. - -If an ADR is taking longer than 4 weeks to reach a final conclusion, the **Concept Approval Committee** -should convene to rectify the situation by either: - -* unanimously setting a new time bound period for this ADR -* making changes to the Concept Approval Process (as outlined here) -* making changes to the members of the Concept Approval Committee - -#### Approval Committee & Decision Making - -In absence of general consensus, decision making requires 1/2 vote from the two members -of the **Concept Approval Committee**. - -#### Committee Members - - - -#### Committee Criteria - -Members must: - -* Participate in all or almost all ADR discussions, both on GitHub as well as in bi-weekly Architecture Review - meetings -* Be active contributors to the Terp-Core, and furthermore should be continuously making substantial contributions - to the project's codebase, review process, documentation and ADRs -* Have stake in the Terp-Core project, represented by: - * Being a client / user of the Comsos SDK - * "[giving back](https://www.debian.org/social_contract)" to the software -* Delegate representation in case of vacation or absence - -Code owners need to maintain participation in the process, ideally as members of **Concept Approval Committee** -members, but at the very least as active participants in ADR discussions - -Removal criteria: - -* Missing 3 meetings results in ICF evaluating whether the member should be removed / replaced -* Violation of Code of Conduct - -### Implementation & Release Approval - -The following process should be adhered to both for implementation PRs corresponding to ADRs, as -well as for PRs made as part of a release process: - -* Code reviewers should ensure the PR does exactly what the ADR said it should -* Code reviewers should have more senior engineering capability -* 1/2 approval is required from the **primary repo maintainers** in `CODEOWNERS` \ No newline at end of file +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 index 9a0e6c5..2407b3b 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -1,11 +1,11 @@ # Event System -## Usage in the Terp-Core +## Usage in the SDK -Events are an essential part of the Terp-Core. They are similar to "logs" in Ethereum and allow a blockchain +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). +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. @@ -15,29 +15,39 @@ Every message in the SDK may add events to the EventManager and these are then a 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. +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 Terp-Core may consist of multiple messages that are executed atomically. Maybe we send tokens, then issue a swap +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" } - ] +{ + "type": "wasm", + "attributes": [ + {"key": "_contract_address", "value": "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6"}, + {"key": "transfered", "value": "777000"} + ] } ``` @@ -45,40 +55,37 @@ And here is a sample log output for a transaction with one message, which emitte ```json [ - [ - { - "type": "message", - "attributes": [ - { "key": "module", "value": "bank" }, - { "key": "action", "value": "send" } - ] - }, - { - "type": "transfer", - "attributes": [ - { - "key": "recipient", - "value": "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6" + [ + { + "type": "message", + "attributes": [ + {"key": "module", "value": "bank"}, + {"key": "action", "value": "send"} + ] }, - { "key": "amount", "value": "777000uatom" } - ] - } - ] + { + "type": "transfer", + "attributes": [ + {"key": "recipient", "value": "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6"}, + {"key": "amount", "value": "777000uatom"} + ] + } + ] ] ``` -### Default Events in the Terp-Core +### 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. +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. +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 Terp-COre +### 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: @@ -98,7 +105,7 @@ sdk.NewEvent( ), ``` -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** +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). @@ -116,9 +123,9 @@ sdk.NewEvent( ), ``` -## Usage in terpd +## 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 +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. @@ -137,7 +144,7 @@ sdk.NewEvent( "message", sdk.NewAttribute("module", "wasm"), // Note: this was "signer" before 0.18 - sdk.NewAttribute("sender", msg.Sender), + sdk.NewAttribute("sender", msg.Sender), ), ``` @@ -150,7 +157,7 @@ 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/terpd/issues/574 + // see https://github.com/CosmWasm/wasmd/issues/574 sdk.NewAttribute("feature", "stargate"), sdk.NewAttribute("feature", "staking"), ) @@ -159,13 +166,13 @@ sdk.NewEvent( sdk.NewEvent( "instantiate", sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), ) // Execute Contract sdk.NewEvent( "execute", - sdk.NewAttribute("_contract_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), ) // Migrate Contract @@ -173,20 +180,20 @@ 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_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), ) // Set new admin sdk.NewEvent( "update_admin", - sdk.NewAttribute("_contract_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), sdk.NewAttribute("admin", msg.NewAdmin), ) // Clear admin sdk.NewEvent( "clear_admin", - sdk.NewAttribute("_contract_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), ) // Pin Code @@ -204,7 +211,7 @@ sdk.NewEvent( // Emitted when processing a submessage reply sdk.NewEvent( "reply", - sdk.NewAttribute("_contract_addr", contractAddr.String()), + 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 @@ -214,13 +221,13 @@ sdk.NewEvent( // Emitted when handling sudo sdk.NewEvent( "sudo", - sdk.NewAttribute("_contract_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), ) ``` -Note that every event that affects a contract (not store code, pin or unpin) will return the contract*addr as -`_contract_addr`. 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, +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 @@ -240,14 +247,14 @@ an eg. `transfer` event from the bank module. The output here may look like: ```go sdk.NewEvent( "wasm-promote" - sdk.NewAttribute("_contract_addr", contractAddr.String()), + 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_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), sdk.NewAttribute("batch_id", "7"), sdk.NewAttribute("address", "cosmos19875632"), ) @@ -260,7 +267,7 @@ more than flattening them all into one event like: ```go sdk.NewEvent( "wasm" - sdk.NewAttribute("_contract_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), sdk.NewAttribute("action", "promote"), sdk.NewAttribute("batch_id", "6"), sdk.NewAttribute("address", "cosmos1234567"), @@ -280,14 +287,14 @@ to find all transactions related to the contract. 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 +* 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 terpd +## 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 @@ -309,12 +316,12 @@ contact and the `wasm` event with any custom fields from the contract itself. It 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 +* 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`, +* 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. +* 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 @@ -325,17 +332,17 @@ address). It will emit a series of events that looks something like this: sdk.NewEvent( "message", sdk.NewAttribute("module", "wasm"), - sdk.NewAttribute("sender", msg.Sender), + sdk.NewAttribute("sender", msg.Sender), ), // top-level exection call sdk.NewEvent( "execute", - sdk.NewAttribute("_contract_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), ), sdk.NewEvent( "wasm", - sdk.NewAttribute("_contract_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), sdk.NewAttribute("custom", "from contract"), ), @@ -343,24 +350,24 @@ sdk.NewEvent( sdk.NewEvent( "instantiate", sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_addr", newContract.String()), + sdk.NewAttribute("_contract_address", newContract.String()), ) // didn't emit any attributes, but one event sdk.NewEvent( "wasm-custom", - sdk.NewAttribute("_contract_addr", newContract.String()), + 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_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), sdk.NewAttribute("mode", "handle_success"), ), sdk.NewEvent( "wasm", - sdk.NewAttribute("_contract_addr", contractAddr.String()), + sdk.NewAttribute("_contract_address", contractAddr.String()), sdk.NewAttribute("custom", "from contract"), ), @@ -382,11 +389,11 @@ field, and the following in the `events` field: sdk.NewEvent( "instantiate", sdk.NewAttribute("code_id", fmt.Sprintf("%d", msg.CodeID)), - sdk.NewAttribute("_contract_addr", newContract.String()), + sdk.NewAttribute("_contract_address", newContract.String()), ) sdk.NewEvent( "wasm-custom", - sdk.NewAttribute("_contract_addr", newContract.String()), + sdk.NewAttribute("_contract_address", newContract.String()), sdk.NewAttribute("foobar", "baz"), ), ``` @@ -396,11 +403,9 @@ and it registered a ReplyOn clause, the `reply` function on that contract would 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", diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md new file mode 100644 index 0000000..177af46 --- /dev/null +++ b/docs/INTEGRATION.md @@ -0,0 +1,198 @@ + + +# 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/feature_request.md b/docs/ISSUE_TEMPLATES/features_request.md similarity index 100% rename from docs/ISSUE_TEMPLATES/feature_request.md rename to docs/ISSUE_TEMPLATES/features_request.md diff --git a/docs/PULL_REQUEST_TEMPLATE/PULL_REQUEST_TEMPLATE.md b/docs/PULL_REQUEST_TEMPLATE/PR_TEMPLATE.md similarity index 100% rename from docs/PULL_REQUEST_TEMPLATE/PULL_REQUEST_TEMPLATE.md rename to docs/PULL_REQUEST_TEMPLATE/PR_TEMPLATE.md diff --git a/docs/PULL_REQUEST_TEMPLATE/update_docs.md b/docs/PULL_REQUEST_TEMPLATE/update_docs.md index 50b4f94..696706e 100644 --- a/docs/PULL_REQUEST_TEMPLATE/update_docs.md +++ b/docs/PULL_REQUEST_TEMPLATE/update_docs.md @@ -1 +1,5 @@ -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. Description of the Change Release Notes \ No newline at end of file +### 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/README.md b/docs/README.md index 02945e5..8beace1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,3 +1,3 @@ # Generated doc only -Tutorials and project doc is available on https://docs.terp.network/ +Tutorials and project doc is available on https://docs.cosmwasm.com/ diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 557ff1b..021b58b 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -1,117 +1,13 @@ -# Security +# Security Policy -> **IMPORTANT**: If you find a security issue, you can -report it to our core-team. *DO NOT* open a public issue on the repository. +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. -## Bug Bounty +## Supported Versions -A Bug bounty program is needed to contrinute to minimize vulnerability breaches. +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. -See the policy linked above for more details on submissions and rewards and read -this [blog post](https://blog.cosmos.network/bug-bounty-program-for-tendermint-cosmos-833c67693586) for the program scope. +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. -The following is a list of examples of the kinds of bugs we're most interested -in for the Terp-Core. See [here](https://github.com/tendermint/tendermint/blob/master/SECURITY.md) for vulnerabilities we are interested -in for Tendermint and other lower-level libraries (eg. [IAVL](https://github.com/cosmos/iavl)). - -### Core packages - -* [`/app`](https://github.com/terpnetwork/terp-core/tree/main/app) -* [`/proto`](https://github.com/terpnetwork/terp-core/tree/main/proto) -* [`/x`](https://github.com/terpnetwork/terp-core/tree/main/x) - -### Modules - - -We are interested in bugs in other modules, however the above are most likely to -have significant vulnerabilities, due to the complexity / nuance involved. - -### How we process Tx parameters - -* Integer operations on tx parameters, especially `sdk.Int` / `sdk.Dec` -* Gas calculation & parameter choices -* Possible Node DoS vectors (perhaps due to gas weighting / non constant timing) - -### Handling private keys - -* HD key derivation, local and Ledger, and all key-management functionality - - -## Disclosure Process - -The TerpNET team uses the following disclosure process: - -1. After a security report is received, the TerpNET team works to verify the issue and confirm its severity level using Common Vulnerability Scoring System (CVSS). -1. The TerpNET team collaborates with the Tendermint and Gaia teams to determine the vulnerability’s potential impact on the Cosmos Hub and partners. -1. Patches are prepared in private repositories for eligible releases of TerpNET. See [Stable Release Policy](https://github.com/cosmos/cosmos-sdk/blob/main/RELEASE_PROCESS.md#stable-release-policy) for a list of eligible releases. -1. If it is determined that a CVE-ID is required, we request a CVE through a CVE Numbering Authority. -1. We notify the community that a security release is coming to give users time to prepare their systems for the update. Notifications can include forum posts, tweets, and emails to partners and validators. -1. 24 hours after the notification, fixes are applied publicly and new releases are issued. -1. After releases are available for Cosmos-SDK, Terp-Core, and Tendermint, we notify the community again through the same channels. We also publish a Security Advisory on Github and publish the CVE, as long as the Security Advisory and the CVE do not include information on how to exploit these vulnerabilities beyond the information that is available in the patch. -1. After the community is notified, Tendermint pays out any relevant bug bounties to submitters. -1. One week after the releases go out, we publish a post with details and our response to the vulnerability. - -This process can take some time. Every effort is made to handle the bug in as timely a manner as possible. However, it's important that we follow this security process to ensure that disclosures are handled consistently and to keep Terp-Core and its downstream dependent projects--including but not limited to Gaia and the Cosmos Hub--as secure as possible. - -### Disclosure Communications - -Communications to partners usually include the following details: - -1. Affected version or versions -1. New release version -1. Impact on user funds -1. For timed releases, a date and time that the new release will be made available -1. Impact on the partners if upgrades are not completed in a timely manner -1. Potential required actions if an adverse condition arises during the security release process - -An example notice looks like: - -```text -Dear TerpNET partners, - -A critical security vulnerability has been identified in Terp-Core vX.X.X. -User funds are NOT at risk; however, the vulnerability can result in a chain halt. - -This notice is to inform you that on [[**March 1 at 1pm EST/6pm UTC**]], we will be releasing Terp-Core vX.X.Y to fix the security issue. -We ask all validators to upgrade their nodes ASAP. - -If the chain halts, validators with sufficient voting power must upgrade and come online for the chain to resume. -``` - -### Example Timeline - -The following timeline is an example of triage and response. Each task identifies the required roles and team members; however, multiple people can play each role and each person may play multiple roles. - -#### 24+ Hours Before Release Time - -1. Request CVE number (ADMIN) -1. Gather emails and other contact info for validators (COMMS LEAD) -1. Test fixes on a testnet (Terp-Core ENG) -1. Write “Security Advisory” for forum (Terp-Core LEAD) - -#### 24 Hours Before Release Time - -1. Post “Security Advisory” pre-notification on forum (Terp-Core LEAD) -1. Post Tweet linking to forum post (COMMS LEAD) -1. Announce security advisory/link to post in various other social channels (Telegram, Discord) (COMMS LEAD) -1. Send emails to partners or other users (PARTNERSHIPS LEAD) - -#### Release Time - -1. Cut Terp-Core releases for eligible versions (Terp-Core ENG) -1. Cut Gaia release for eligible versions (GAIA ENG) -1. Post “Security releases” on forum (Terp-Core LEAD) -1. Post new Tweet linking to forum post (COMMS LEAD) -1. Remind everyone using social channels (Telegram, Discord) that the release is out (COMMS LEAD) -1. Send emails to validators and other users (COMMS LEAD) -1. Publish Security Advisory and CVE if the CVE has no sensitive information (ADMIN) - -#### After Release Time - -1. Write forum post with exploit details (Terp-Core LEAD) -1. Approve payout on HackerOne for submitter (ADMIN) - -#### 7 Days After Release Time - -1. Publish CVE if it has not yet been published (ADMIN) -1. Publish forum post with exploit details (Terp-Core ENG, Terp-Core LEAD) \ No newline at end of file +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 new file mode 100644 index 0000000..827d7d8 --- /dev/null +++ b/docs/UPGRADING.md @@ -0,0 +1,277 @@ +# 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 new file mode 100644 index 0000000..734099e --- /dev/null +++ b/docs/api_migration.md @@ -0,0 +1,36 @@ +# 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 1167d56..92b90ac 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -2,5 +2,5 @@ package docs import "embed" -//go:embed static +//go:embed * var Docs embed.FS diff --git a/docs/proto/proto-docs.md b/docs/proto/proto-docs.md deleted file mode 100644 index 9a0635f..0000000 --- a/docs/proto/proto-docs.md +++ /dev/null @@ -1,1554 +0,0 @@ - -# Protobuf Documentation - - -## Table of Contents - -- [cosmwasm/wasm/v1/authz.proto](#cosmwasm/wasm/v1/authz.proto) - - [AcceptedMessageKeysFilter](#cosmwasm.wasm.v1.AcceptedMessageKeysFilter) - - [AcceptedMessagesFilter](#cosmwasm.wasm.v1.AcceptedMessagesFilter) - - [AllowAllMessagesFilter](#cosmwasm.wasm.v1.AllowAllMessagesFilter) - - [CombinedLimit](#cosmwasm.wasm.v1.CombinedLimit) - - [ContractExecutionAuthorization](#cosmwasm.wasm.v1.ContractExecutionAuthorization) - - [ContractGrant](#cosmwasm.wasm.v1.ContractGrant) - - [ContractMigrationAuthorization](#cosmwasm.wasm.v1.ContractMigrationAuthorization) - - [MaxCallsLimit](#cosmwasm.wasm.v1.MaxCallsLimit) - - [MaxFundsLimit](#cosmwasm.wasm.v1.MaxFundsLimit) - -- [cosmwasm/wasm/v1/types.proto](#cosmwasm/wasm/v1/types.proto) - - [AbsoluteTxPosition](#cosmwasm.wasm.v1.AbsoluteTxPosition) - - [AccessConfig](#cosmwasm.wasm.v1.AccessConfig) - - [AccessTypeParam](#cosmwasm.wasm.v1.AccessTypeParam) - - [CodeInfo](#cosmwasm.wasm.v1.CodeInfo) - - [ContractCodeHistoryEntry](#cosmwasm.wasm.v1.ContractCodeHistoryEntry) - - [ContractInfo](#cosmwasm.wasm.v1.ContractInfo) - - [Model](#cosmwasm.wasm.v1.Model) - - [Params](#cosmwasm.wasm.v1.Params) - - - [AccessType](#cosmwasm.wasm.v1.AccessType) - - [ContractCodeHistoryOperationType](#cosmwasm.wasm.v1.ContractCodeHistoryOperationType) - -- [cosmwasm/wasm/v1/genesis.proto](#cosmwasm/wasm/v1/genesis.proto) - - [Code](#cosmwasm.wasm.v1.Code) - - [Contract](#cosmwasm.wasm.v1.Contract) - - [GenesisState](#cosmwasm.wasm.v1.GenesisState) - - [Sequence](#cosmwasm.wasm.v1.Sequence) - -- [cosmwasm/wasm/v1/ibc.proto](#cosmwasm/wasm/v1/ibc.proto) - - [MsgIBCCloseChannel](#cosmwasm.wasm.v1.MsgIBCCloseChannel) - - [MsgIBCSend](#cosmwasm.wasm.v1.MsgIBCSend) - -- [cosmwasm/wasm/v1/proposal.proto](#cosmwasm/wasm/v1/proposal.proto) - - [AccessConfigUpdate](#cosmwasm.wasm.v1.AccessConfigUpdate) - - [ClearAdminProposal](#cosmwasm.wasm.v1.ClearAdminProposal) - - [ExecuteContractProposal](#cosmwasm.wasm.v1.ExecuteContractProposal) - - [InstantiateContract2Proposal](#cosmwasm.wasm.v1.InstantiateContract2Proposal) - - [InstantiateContractProposal](#cosmwasm.wasm.v1.InstantiateContractProposal) - - [MigrateContractProposal](#cosmwasm.wasm.v1.MigrateContractProposal) - - [PinCodesProposal](#cosmwasm.wasm.v1.PinCodesProposal) - - [StoreAndInstantiateContractProposal](#cosmwasm.wasm.v1.StoreAndInstantiateContractProposal) - - [StoreCodeProposal](#cosmwasm.wasm.v1.StoreCodeProposal) - - [SudoContractProposal](#cosmwasm.wasm.v1.SudoContractProposal) - - [UnpinCodesProposal](#cosmwasm.wasm.v1.UnpinCodesProposal) - - [UpdateAdminProposal](#cosmwasm.wasm.v1.UpdateAdminProposal) - - [UpdateInstantiateConfigProposal](#cosmwasm.wasm.v1.UpdateInstantiateConfigProposal) - -- [cosmwasm/wasm/v1/query.proto](#cosmwasm/wasm/v1/query.proto) - - [CodeInfoResponse](#cosmwasm.wasm.v1.CodeInfoResponse) - - [QueryAllContractStateRequest](#cosmwasm.wasm.v1.QueryAllContractStateRequest) - - [QueryAllContractStateResponse](#cosmwasm.wasm.v1.QueryAllContractStateResponse) - - [QueryCodeRequest](#cosmwasm.wasm.v1.QueryCodeRequest) - - [QueryCodeResponse](#cosmwasm.wasm.v1.QueryCodeResponse) - - [QueryCodesRequest](#cosmwasm.wasm.v1.QueryCodesRequest) - - [QueryCodesResponse](#cosmwasm.wasm.v1.QueryCodesResponse) - - [QueryContractHistoryRequest](#cosmwasm.wasm.v1.QueryContractHistoryRequest) - - [QueryContractHistoryResponse](#cosmwasm.wasm.v1.QueryContractHistoryResponse) - - [QueryContractInfoRequest](#cosmwasm.wasm.v1.QueryContractInfoRequest) - - [QueryContractInfoResponse](#cosmwasm.wasm.v1.QueryContractInfoResponse) - - [QueryContractsByCodeRequest](#cosmwasm.wasm.v1.QueryContractsByCodeRequest) - - [QueryContractsByCodeResponse](#cosmwasm.wasm.v1.QueryContractsByCodeResponse) - - [QueryContractsByCreatorRequest](#cosmwasm.wasm.v1.QueryContractsByCreatorRequest) - - [QueryContractsByCreatorResponse](#cosmwasm.wasm.v1.QueryContractsByCreatorResponse) - - [QueryParamsRequest](#cosmwasm.wasm.v1.QueryParamsRequest) - - [QueryParamsResponse](#cosmwasm.wasm.v1.QueryParamsResponse) - - [QueryPinnedCodesRequest](#cosmwasm.wasm.v1.QueryPinnedCodesRequest) - - [QueryPinnedCodesResponse](#cosmwasm.wasm.v1.QueryPinnedCodesResponse) - - [QueryRawContractStateRequest](#cosmwasm.wasm.v1.QueryRawContractStateRequest) - - [QueryRawContractStateResponse](#cosmwasm.wasm.v1.QueryRawContractStateResponse) - - [QuerySmartContractStateRequest](#cosmwasm.wasm.v1.QuerySmartContractStateRequest) - - [QuerySmartContractStateResponse](#cosmwasm.wasm.v1.QuerySmartContractStateResponse) - - - [Query](#cosmwasm.wasm.v1.Query) - -- [cosmwasm/wasm/v1/tx.proto](#cosmwasm/wasm/v1/tx.proto) - - [MsgClearAdmin](#cosmwasm.wasm.v1.MsgClearAdmin) - - [MsgClearAdminResponse](#cosmwasm.wasm.v1.MsgClearAdminResponse) - - [MsgExecuteContract](#cosmwasm.wasm.v1.MsgExecuteContract) - - [MsgExecuteContractResponse](#cosmwasm.wasm.v1.MsgExecuteContractResponse) - - [MsgInstantiateContract](#cosmwasm.wasm.v1.MsgInstantiateContract) - - [MsgInstantiateContract2](#cosmwasm.wasm.v1.MsgInstantiateContract2) - - [MsgInstantiateContract2Response](#cosmwasm.wasm.v1.MsgInstantiateContract2Response) - - [MsgInstantiateContractResponse](#cosmwasm.wasm.v1.MsgInstantiateContractResponse) - - [MsgMigrateContract](#cosmwasm.wasm.v1.MsgMigrateContract) - - [MsgMigrateContractResponse](#cosmwasm.wasm.v1.MsgMigrateContractResponse) - - [MsgStoreCode](#cosmwasm.wasm.v1.MsgStoreCode) - - [MsgStoreCodeResponse](#cosmwasm.wasm.v1.MsgStoreCodeResponse) - - [MsgUpdateAdmin](#cosmwasm.wasm.v1.MsgUpdateAdmin) - - [MsgUpdateAdminResponse](#cosmwasm.wasm.v1.MsgUpdateAdminResponse) - - - [Msg](#cosmwasm.wasm.v1.Msg) - -- [Scalar Value Types](#scalar-value-types) - - - - -

Top

- -## cosmwasm/wasm/v1/authz.proto - - - - - -### AcceptedMessageKeysFilter -AcceptedMessageKeysFilter accept only the specific contract message keys in -the json object to be executed. -Since: terpd 0.2.0 - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `keys` | [string](#string) | repeated | Messages is the list of unique keys | - - - - - - - - -### AcceptedMessagesFilter -AcceptedMessagesFilter accept only the specific raw contract messages to be -executed. -Since: terpd 0.2.0 - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `messages` | [bytes](#bytes) | repeated | Messages is the list of raw contract messages | - - - - - - - - -### AllowAllMessagesFilter -AllowAllMessagesFilter is a wildcard to allow any type of contract payload -message. -Since: terpd 0.2.0 - - - - - - - - -### CombinedLimit -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: terpd 0.2.0 - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `calls_remaining` | [uint64](#uint64) | | Remaining number that is decremented on each execution | -| `amounts` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Amounts is the maximal amount of tokens transferable to the contract. | - - - - - - - - -### ContractExecutionAuthorization -ContractExecutionAuthorization defines authorization for wasm execute. -Since: terpd 0.2.0 - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `grants` | [ContractGrant](#cosmwasm.wasm.v1.ContractGrant) | repeated | Grants for contract executions | - - - - - - - - -### ContractGrant -ContractGrant a granted permission for a single contract -Since: terpd 0.2.0 - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `contract` | [string](#string) | | Contract is the bech32 address of the smart contract | -| `limit` | [google.protobuf.Any](#google.protobuf.Any) | | Limit defines execution limits that are enforced and updated when the grant is applied. When the limit lapsed the grant is removed. | -| `filter` | [google.protobuf.Any](#google.protobuf.Any) | | 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. | - - - - - - - - -### ContractMigrationAuthorization -ContractMigrationAuthorization defines authorization for wasm contract -migration. Since: terpd 0.2.0 - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `grants` | [ContractGrant](#cosmwasm.wasm.v1.ContractGrant) | repeated | Grants for contract migrations | - - - - - - - - -### MaxCallsLimit -MaxCallsLimit limited number of calls to the contract. No funds transferable. -Since: terpd 0.2.0 - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `remaining` | [uint64](#uint64) | | Remaining number that is decremented on each execution | - - - - - - - - -### MaxFundsLimit -MaxFundsLimit defines the maximal amounts that can be sent to the contract. -Since: terpd 0.2.0 - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `amounts` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Amounts is the maximal amount of tokens transferable to the contract. | - - - - - - - - - - - - - - - - -

Top

- -## cosmwasm/wasm/v1/types.proto - - - - - -### AbsoluteTxPosition -AbsoluteTxPosition is a unique transaction position that allows for global -ordering of transactions. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `block_height` | [uint64](#uint64) | | BlockHeight is the block the contract was created at | -| `tx_index` | [uint64](#uint64) | | TxIndex is a monotonic counter within the block (actual transaction index, or gas consumed) | - - - - - - - - -### AccessConfig -AccessConfig access control type. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `permission` | [AccessType](#cosmwasm.wasm.v1.AccessType) | | | -| `address` | [string](#string) | | Address Deprecated: replaced by addresses | -| `addresses` | [string](#string) | repeated | | - - - - - - - - -### AccessTypeParam -AccessTypeParam - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `value` | [AccessType](#cosmwasm.wasm.v1.AccessType) | | | - - - - - - - - -### CodeInfo -CodeInfo is data for the uploaded contract WASM code - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_hash` | [bytes](#bytes) | | CodeHash is the unique identifier created by wasmvm | -| `creator` | [string](#string) | | Creator address who initially stored the code | -| `instantiate_config` | [AccessConfig](#cosmwasm.wasm.v1.AccessConfig) | | InstantiateConfig access control to apply on contract creation, optional | - - - - - - - - -### ContractCodeHistoryEntry -ContractCodeHistoryEntry metadata to a contract. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `operation` | [ContractCodeHistoryOperationType](#cosmwasm.wasm.v1.ContractCodeHistoryOperationType) | | | -| `code_id` | [uint64](#uint64) | | CodeID is the reference to the stored WASM code | -| `updated` | [AbsoluteTxPosition](#cosmwasm.wasm.v1.AbsoluteTxPosition) | | Updated Tx position when the operation was executed. | -| `msg` | [bytes](#bytes) | | | - - - - - - - - -### ContractInfo -ContractInfo stores a WASM contract instance - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_id` | [uint64](#uint64) | | CodeID is the reference to the stored Wasm code | -| `creator` | [string](#string) | | Creator address who initially instantiated the contract | -| `admin` | [string](#string) | | Admin is an optional address that can execute migrations | -| `label` | [string](#string) | | Label is optional metadata to be stored with a contract instance. | -| `created` | [AbsoluteTxPosition](#cosmwasm.wasm.v1.AbsoluteTxPosition) | | Created Tx position when the contract was instantiated. | -| `ibc_port_id` | [string](#string) | | | -| `extension` | [google.protobuf.Any](#google.protobuf.Any) | | Extension is an extension point to store custom metadata within the persistence model. | - - - - - - - - -### Model -Model is a struct that holds a KV pair - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `key` | [bytes](#bytes) | | hex-encode key to read it better (this is often ascii) | -| `value` | [bytes](#bytes) | | base64-encode raw value | - - - - - - - - -### Params -Params defines the set of wasm parameters. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_upload_access` | [AccessConfig](#cosmwasm.wasm.v1.AccessConfig) | | | -| `instantiate_default_permission` | [AccessType](#cosmwasm.wasm.v1.AccessType) | | | - - - - - - - - - - -### AccessType -AccessType permission types - -| Name | Number | Description | -| ---- | ------ | ----------- | -| ACCESS_TYPE_UNSPECIFIED | 0 | AccessTypeUnspecified placeholder for empty value | -| ACCESS_TYPE_NOBODY | 1 | AccessTypeNobody forbidden | -| ACCESS_TYPE_ONLY_ADDRESS | 2 | AccessTypeOnlyAddress restricted to a single address Deprecated: use AccessTypeAnyOfAddresses instead | -| ACCESS_TYPE_EVERYBODY | 3 | AccessTypeEverybody unrestricted | -| ACCESS_TYPE_ANY_OF_ADDRESSES | 4 | AccessTypeAnyOfAddresses allow any of the addresses | - - - - - -### ContractCodeHistoryOperationType -ContractCodeHistoryOperationType actions that caused a code change - -| Name | Number | Description | -| ---- | ------ | ----------- | -| CONTRACT_CODE_HISTORY_OPERATION_TYPE_UNSPECIFIED | 0 | ContractCodeHistoryOperationTypeUnspecified placeholder for empty value | -| CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT | 1 | ContractCodeHistoryOperationTypeInit on chain contract instantiation | -| CONTRACT_CODE_HISTORY_OPERATION_TYPE_MIGRATE | 2 | ContractCodeHistoryOperationTypeMigrate code migration | -| CONTRACT_CODE_HISTORY_OPERATION_TYPE_GENESIS | 3 | ContractCodeHistoryOperationTypeGenesis based on genesis data | - - - - - - - - - - - -

Top

- -## cosmwasm/wasm/v1/genesis.proto - - - - - -### Code -Code struct encompasses CodeInfo and CodeBytes - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_id` | [uint64](#uint64) | | | -| `code_info` | [CodeInfo](#cosmwasm.wasm.v1.CodeInfo) | | | -| `code_bytes` | [bytes](#bytes) | | | -| `pinned` | [bool](#bool) | | Pinned to wasmvm cache | - - - - - - - - -### Contract -Contract struct encompasses ContractAddress, ContractInfo, and ContractState - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `contract_address` | [string](#string) | | | -| `contract_info` | [ContractInfo](#cosmwasm.wasm.v1.ContractInfo) | | | -| `contract_state` | [Model](#cosmwasm.wasm.v1.Model) | repeated | | -| `contract_code_history` | [ContractCodeHistoryEntry](#cosmwasm.wasm.v1.ContractCodeHistoryEntry) | repeated | | - - - - - - - - -### GenesisState -GenesisState - genesis state of x/wasm - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `params` | [Params](#cosmwasm.wasm.v1.Params) | | | -| `codes` | [Code](#cosmwasm.wasm.v1.Code) | repeated | | -| `contracts` | [Contract](#cosmwasm.wasm.v1.Contract) | repeated | | -| `sequences` | [Sequence](#cosmwasm.wasm.v1.Sequence) | repeated | | - - - - - - - - -### Sequence -Sequence key and value of an id generation counter - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `id_key` | [bytes](#bytes) | | | -| `value` | [uint64](#uint64) | | | - - - - - - - - - - - - - - - - -

Top

- -## cosmwasm/wasm/v1/ibc.proto - - - - - -### MsgIBCCloseChannel -MsgIBCCloseChannel port and channel need to be owned by the contract - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `channel` | [string](#string) | | | - - - - - - - - -### MsgIBCSend -MsgIBCSend - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `channel` | [string](#string) | | the channel by which the packet will be sent | -| `timeout_height` | [uint64](#uint64) | | Timeout height relative to the current block height. The timeout is disabled when set to 0. | -| `timeout_timestamp` | [uint64](#uint64) | | Timeout timestamp (in nanoseconds) relative to the current block timestamp. The timeout is disabled when set to 0. | -| `data` | [bytes](#bytes) | | Data is the payload to transfer. We must not make assumption what format or content is in here. | - - - - - - - - - - - - - - - - -

Top

- -## cosmwasm/wasm/v1/proposal.proto - - - - - -### AccessConfigUpdate -AccessConfigUpdate contains the code id and the access config to be -applied. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_id` | [uint64](#uint64) | | CodeID is the reference to the stored WASM code to be updated | -| `instantiate_permission` | [AccessConfig](#cosmwasm.wasm.v1.AccessConfig) | | InstantiatePermission to apply to the set of code ids | - - - - - - - - -### ClearAdminProposal -ClearAdminProposal gov proposal content type to clear the admin of a -contract. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `contract` | [string](#string) | | Contract is the address of the smart contract | - - - - - - - - -### ExecuteContractProposal -ExecuteContractProposal gov proposal content type to call execute on a -contract. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `run_as` | [string](#string) | | RunAs is the address that is passed to the contract's environment as sender | -| `contract` | [string](#string) | | Contract is the address of the smart contract | -| `msg` | [bytes](#bytes) | | Msg json encoded message to be passed to the contract as execute | -| `funds` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Funds coins that are transferred to the contract on instantiation | - - - - - - - - -### InstantiateContract2Proposal -InstantiateContract2Proposal gov proposal content type to instantiate -contract 2 - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `run_as` | [string](#string) | | RunAs is the address that is passed to the contract's enviroment as sender | -| `admin` | [string](#string) | | Admin is an optional address that can execute migrations | -| `code_id` | [uint64](#uint64) | | CodeID is the reference to the stored WASM code | -| `label` | [string](#string) | | Label is optional metadata to be stored with a constract instance. | -| `msg` | [bytes](#bytes) | | Msg json encode message to be passed to the contract on instantiation | -| `funds` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Funds coins that are transferred to the contract on instantiation | -| `salt` | [bytes](#bytes) | | Salt is an arbitrary value provided by the sender. Size can be 1 to 64. | -| `fix_msg` | [bool](#bool) | | FixMsg include the msg value into the hash for the predictable address. Default is false | - - - - - - - - -### InstantiateContractProposal -InstantiateContractProposal gov proposal content type to instantiate a -contract. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `run_as` | [string](#string) | | RunAs is the address that is passed to the contract's environment as sender | -| `admin` | [string](#string) | | Admin is an optional address that can execute migrations | -| `code_id` | [uint64](#uint64) | | CodeID is the reference to the stored WASM code | -| `label` | [string](#string) | | Label is optional metadata to be stored with a constract instance. | -| `msg` | [bytes](#bytes) | | Msg json encoded message to be passed to the contract on instantiation | -| `funds` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Funds coins that are transferred to the contract on instantiation | - - - - - - - - -### MigrateContractProposal -MigrateContractProposal gov proposal content type to migrate a contract. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text - -Note: skipping 3 as this was previously used for unneeded run_as | -| `contract` | [string](#string) | | Contract is the address of the smart contract | -| `code_id` | [uint64](#uint64) | | CodeID references the new WASM code | -| `msg` | [bytes](#bytes) | | Msg json encoded message to be passed to the contract on migration | - - - - - - - - -### PinCodesProposal -PinCodesProposal gov proposal content type to pin a set of code ids in the -wasmvm cache. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `code_ids` | [uint64](#uint64) | repeated | CodeIDs references the new WASM codes | - - - - - - - - -### StoreAndInstantiateContractProposal -StoreAndInstantiateContractProposal gov proposal content type to store -and instantiate the contract. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `run_as` | [string](#string) | | RunAs is the address that is passed to the contract's environment as sender | -| `wasm_byte_code` | [bytes](#bytes) | | WASMByteCode can be raw or gzip compressed | -| `instantiate_permission` | [AccessConfig](#cosmwasm.wasm.v1.AccessConfig) | | InstantiatePermission to apply on contract creation, optional | -| `unpin_code` | [bool](#bool) | | UnpinCode code on upload, optional | -| `admin` | [string](#string) | | Admin is an optional address that can execute migrations | -| `label` | [string](#string) | | Label is optional metadata to be stored with a constract instance. | -| `msg` | [bytes](#bytes) | | Msg json encoded message to be passed to the contract on instantiation | -| `funds` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Funds coins that are transferred to the contract on instantiation | -| `source` | [string](#string) | | Source is the URL where the code is hosted | -| `builder` | [string](#string) | | Builder is the docker image used to build the code deterministically, used for smart contract verification | -| `code_hash` | [bytes](#bytes) | | CodeHash is the SHA256 sum of the code outputted by builder, used for smart contract verification | - - - - - - - - -### StoreCodeProposal -StoreCodeProposal gov proposal content type to submit WASM code to the system - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `run_as` | [string](#string) | | RunAs is the address that is passed to the contract's environment as sender | -| `wasm_byte_code` | [bytes](#bytes) | | WASMByteCode can be raw or gzip compressed | -| `instantiate_permission` | [AccessConfig](#cosmwasm.wasm.v1.AccessConfig) | | InstantiatePermission to apply on contract creation, optional | -| `unpin_code` | [bool](#bool) | | UnpinCode code on upload, optional | -| `source` | [string](#string) | | Source is the URL where the code is hosted | -| `builder` | [string](#string) | | Builder is the docker image used to build the code deterministically, used for smart contract verification | -| `code_hash` | [bytes](#bytes) | | CodeHash is the SHA256 sum of the code outputted by builder, used for smart contract verification | - - - - - - - - -### SudoContractProposal -SudoContractProposal gov proposal content type to call sudo on a contract. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `contract` | [string](#string) | | Contract is the address of the smart contract | -| `msg` | [bytes](#bytes) | | Msg json encoded message to be passed to the contract as sudo | - - - - - - - - -### UnpinCodesProposal -UnpinCodesProposal gov proposal content type to unpin a set of code ids in -the wasmvm cache. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `code_ids` | [uint64](#uint64) | repeated | CodeIDs references the WASM codes | - - - - - - - - -### UpdateAdminProposal -UpdateAdminProposal gov proposal content type to set an admin for a contract. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `new_admin` | [string](#string) | | NewAdmin address to be set | -| `contract` | [string](#string) | | Contract is the address of the smart contract | - - - - - - - - -### UpdateInstantiateConfigProposal -UpdateInstantiateConfigProposal gov proposal content type to update -instantiate config to a set of code ids. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `title` | [string](#string) | | Title is a short summary | -| `description` | [string](#string) | | Description is a human readable text | -| `access_config_updates` | [AccessConfigUpdate](#cosmwasm.wasm.v1.AccessConfigUpdate) | repeated | AccessConfigUpdate contains the list of code ids and the access config to be applied. | - - - - - - - - - - - - - - - - -

Top

- -## cosmwasm/wasm/v1/query.proto - - - - - -### CodeInfoResponse -CodeInfoResponse contains code meta data from CodeInfo - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_id` | [uint64](#uint64) | | id for legacy support | -| `creator` | [string](#string) | | | -| `data_hash` | [bytes](#bytes) | | | -| `instantiate_permission` | [AccessConfig](#cosmwasm.wasm.v1.AccessConfig) | | | - - - - - - - - -### QueryAllContractStateRequest -QueryAllContractStateRequest is the request type for the -Query/AllContractState RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `address` | [string](#string) | | address is the address of the contract | -| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. | - - - - - - - - -### QueryAllContractStateResponse -QueryAllContractStateResponse is the response type for the -Query/AllContractState RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `models` | [Model](#cosmwasm.wasm.v1.Model) | repeated | | -| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. | - - - - - - - - -### QueryCodeRequest -QueryCodeRequest is the request type for the Query/Code RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_id` | [uint64](#uint64) | | grpc-gateway_out does not support Go style CodID | - - - - - - - - -### QueryCodeResponse -QueryCodeResponse is the response type for the Query/Code RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_info` | [CodeInfoResponse](#cosmwasm.wasm.v1.CodeInfoResponse) | | | -| `data` | [bytes](#bytes) | | | - - - - - - - - -### QueryCodesRequest -QueryCodesRequest is the request type for the Query/Codes RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. | - - - - - - - - -### QueryCodesResponse -QueryCodesResponse is the response type for the Query/Codes RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_infos` | [CodeInfoResponse](#cosmwasm.wasm.v1.CodeInfoResponse) | repeated | | -| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. | - - - - - - - - -### QueryContractHistoryRequest -QueryContractHistoryRequest is the request type for the Query/ContractHistory -RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `address` | [string](#string) | | address is the address of the contract to query | -| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. | - - - - - - - - -### QueryContractHistoryResponse -QueryContractHistoryResponse is the response type for the -Query/ContractHistory RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `entries` | [ContractCodeHistoryEntry](#cosmwasm.wasm.v1.ContractCodeHistoryEntry) | repeated | | -| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. | - - - - - - - - -### QueryContractInfoRequest -QueryContractInfoRequest is the request type for the Query/ContractInfo RPC -method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `address` | [string](#string) | | address is the address of the contract to query | - - - - - - - - -### QueryContractInfoResponse -QueryContractInfoResponse is the response type for the Query/ContractInfo RPC -method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `address` | [string](#string) | | address is the address of the contract | -| `contract_info` | [ContractInfo](#cosmwasm.wasm.v1.ContractInfo) | | | - - - - - - - - -### QueryContractsByCodeRequest -QueryContractsByCodeRequest is the request type for the Query/ContractsByCode -RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_id` | [uint64](#uint64) | | grpc-gateway_out does not support Go style CodID | -| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. | - - - - - - - - -### QueryContractsByCodeResponse -QueryContractsByCodeResponse is the response type for the -Query/ContractsByCode RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `contracts` | [string](#string) | repeated | contracts are a set of contract addresses | -| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. | - - - - - - - - -### QueryContractsByCreatorRequest -QueryContractsByCreatorRequest is the request type for the -Query/ContractsByCreator RPC method. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `creator_address` | [string](#string) | | CreatorAddress is the address of contract creator | -| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | Pagination defines an optional pagination for the request. | - - - - - - - - -### QueryContractsByCreatorResponse -QueryContractsByCreatorResponse is the response type for the -Query/ContractsByCreator RPC method. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `contract_addresses` | [string](#string) | repeated | ContractAddresses result set | -| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | Pagination defines the pagination in the response. | - - - - - - - - -### 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](#cosmwasm.wasm.v1.Params) | | params defines the parameters of the module. | - - - - - - - - -### QueryPinnedCodesRequest -QueryPinnedCodesRequest is the request type for the Query/PinnedCodes -RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `pagination` | [cosmos.base.query.v1beta1.PageRequest](#cosmos.base.query.v1beta1.PageRequest) | | pagination defines an optional pagination for the request. | - - - - - - - - -### QueryPinnedCodesResponse -QueryPinnedCodesResponse is the response type for the -Query/PinnedCodes RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_ids` | [uint64](#uint64) | repeated | | -| `pagination` | [cosmos.base.query.v1beta1.PageResponse](#cosmos.base.query.v1beta1.PageResponse) | | pagination defines the pagination in the response. | - - - - - - - - -### QueryRawContractStateRequest -QueryRawContractStateRequest is the request type for the -Query/RawContractState RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `address` | [string](#string) | | address is the address of the contract | -| `query_data` | [bytes](#bytes) | | | - - - - - - - - -### QueryRawContractStateResponse -QueryRawContractStateResponse is the response type for the -Query/RawContractState RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `data` | [bytes](#bytes) | | Data contains the raw store data | - - - - - - - - -### QuerySmartContractStateRequest -QuerySmartContractStateRequest is the request type for the -Query/SmartContractState RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `address` | [string](#string) | | address is the address of the contract | -| `query_data` | [bytes](#bytes) | | QueryData contains the query data passed to the contract | - - - - - - - - -### QuerySmartContractStateResponse -QuerySmartContractStateResponse is the response type for the -Query/SmartContractState RPC method - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `data` | [bytes](#bytes) | | Data contains the json data returned from the smart contract | - - - - - - - - - - - - - - -### Query -Query provides defines the gRPC querier service - -| Method Name | Request Type | Response Type | Description | HTTP Verb | Endpoint | -| ----------- | ------------ | ------------- | ------------| ------- | -------- | -| `ContractInfo` | [QueryContractInfoRequest](#cosmwasm.wasm.v1.QueryContractInfoRequest) | [QueryContractInfoResponse](#cosmwasm.wasm.v1.QueryContractInfoResponse) | ContractInfo gets the contract meta data | GET|/cosmwasm/wasm/v1/contract/{address}| -| `ContractHistory` | [QueryContractHistoryRequest](#cosmwasm.wasm.v1.QueryContractHistoryRequest) | [QueryContractHistoryResponse](#cosmwasm.wasm.v1.QueryContractHistoryResponse) | ContractHistory gets the contract code history | GET|/cosmwasm/wasm/v1/contract/{address}/history| -| `ContractsByCode` | [QueryContractsByCodeRequest](#cosmwasm.wasm.v1.QueryContractsByCodeRequest) | [QueryContractsByCodeResponse](#cosmwasm.wasm.v1.QueryContractsByCodeResponse) | ContractsByCode lists all smart contracts for a code id | GET|/cosmwasm/wasm/v1/code/{code_id}/contracts| -| `AllContractState` | [QueryAllContractStateRequest](#cosmwasm.wasm.v1.QueryAllContractStateRequest) | [QueryAllContractStateResponse](#cosmwasm.wasm.v1.QueryAllContractStateResponse) | AllContractState gets all raw store data for a single contract | GET|/cosmwasm/wasm/v1/contract/{address}/state| -| `RawContractState` | [QueryRawContractStateRequest](#cosmwasm.wasm.v1.QueryRawContractStateRequest) | [QueryRawContractStateResponse](#cosmwasm.wasm.v1.QueryRawContractStateResponse) | RawContractState gets single key from the raw store data of a contract | GET|/cosmwasm/wasm/v1/contract/{address}/raw/{query_data}| -| `SmartContractState` | [QuerySmartContractStateRequest](#cosmwasm.wasm.v1.QuerySmartContractStateRequest) | [QuerySmartContractStateResponse](#cosmwasm.wasm.v1.QuerySmartContractStateResponse) | SmartContractState get smart query result from the contract | GET|/cosmwasm/wasm/v1/contract/{address}/smart/{query_data}| -| `Code` | [QueryCodeRequest](#cosmwasm.wasm.v1.QueryCodeRequest) | [QueryCodeResponse](#cosmwasm.wasm.v1.QueryCodeResponse) | Code gets the binary code and metadata for a singe wasm code | GET|/cosmwasm/wasm/v1/code/{code_id}| -| `Codes` | [QueryCodesRequest](#cosmwasm.wasm.v1.QueryCodesRequest) | [QueryCodesResponse](#cosmwasm.wasm.v1.QueryCodesResponse) | Codes gets the metadata for all stored wasm codes | GET|/cosmwasm/wasm/v1/code| -| `PinnedCodes` | [QueryPinnedCodesRequest](#cosmwasm.wasm.v1.QueryPinnedCodesRequest) | [QueryPinnedCodesResponse](#cosmwasm.wasm.v1.QueryPinnedCodesResponse) | PinnedCodes gets the pinned code ids | GET|/cosmwasm/wasm/v1/codes/pinned| -| `Params` | [QueryParamsRequest](#cosmwasm.wasm.v1.QueryParamsRequest) | [QueryParamsResponse](#cosmwasm.wasm.v1.QueryParamsResponse) | Params gets the module params | GET|/cosmwasm/wasm/v1/codes/params| -| `ContractsByCreator` | [QueryContractsByCreatorRequest](#cosmwasm.wasm.v1.QueryContractsByCreatorRequest) | [QueryContractsByCreatorResponse](#cosmwasm.wasm.v1.QueryContractsByCreatorResponse) | ContractsByCreator gets the contracts by creator | GET|/cosmwasm/wasm/v1/contracts/creator/{creator_address}| - - - - - - -

Top

- -## cosmwasm/wasm/v1/tx.proto - - - - - -### MsgClearAdmin -MsgClearAdmin removes any admin stored for a smart contract - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | Sender is the that actor that signed the messages | -| `contract` | [string](#string) | | Contract is the address of the smart contract | - - - - - - - - -### MsgClearAdminResponse -MsgClearAdminResponse returns empty data - - - - - - - - -### MsgExecuteContract -MsgExecuteContract submits the given message data to a smart contract - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | Sender is the that actor that signed the messages | -| `contract` | [string](#string) | | Contract is the address of the smart contract | -| `msg` | [bytes](#bytes) | | Msg json encoded message to be passed to the contract | -| `funds` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Funds coins that are transferred to the contract on execution | - - - - - - - - -### MsgExecuteContractResponse -MsgExecuteContractResponse returns execution result data. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `data` | [bytes](#bytes) | | Data contains bytes to returned from the contract | - - - - - - - - -### MsgInstantiateContract -MsgInstantiateContract create a new smart contract instance for the given -code id. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | Sender is the that actor that signed the messages | -| `admin` | [string](#string) | | Admin is an optional address that can execute migrations | -| `code_id` | [uint64](#uint64) | | CodeID is the reference to the stored WASM code | -| `label` | [string](#string) | | Label is optional metadata to be stored with a contract instance. | -| `msg` | [bytes](#bytes) | | Msg json encoded message to be passed to the contract on instantiation | -| `funds` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Funds coins that are transferred to the contract on instantiation | - - - - - - - - -### MsgInstantiateContract2 -MsgInstantiateContract2 create a new smart contract instance for the given -code id with a predicable address. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | Sender is the that actor that signed the messages | -| `admin` | [string](#string) | | Admin is an optional address that can execute migrations | -| `code_id` | [uint64](#uint64) | | CodeID is the reference to the stored WASM code | -| `label` | [string](#string) | | Label is optional metadata to be stored with a contract instance. | -| `msg` | [bytes](#bytes) | | Msg json encoded message to be passed to the contract on instantiation | -| `funds` | [cosmos.base.v1beta1.Coin](#cosmos.base.v1beta1.Coin) | repeated | Funds coins that are transferred to the contract on instantiation | -| `salt` | [bytes](#bytes) | | Salt is an arbitrary value provided by the sender. Size can be 1 to 64. | -| `fix_msg` | [bool](#bool) | | FixMsg include the msg value into the hash for the predictable address. Default is false | - - - - - - - - -### MsgInstantiateContract2Response -MsgInstantiateContract2Response return instantiation result data - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `address` | [string](#string) | | Address is the bech32 address of the new contract instance. | -| `data` | [bytes](#bytes) | | Data contains bytes to returned from the contract | - - - - - - - - -### MsgInstantiateContractResponse -MsgInstantiateContractResponse return instantiation result data - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `address` | [string](#string) | | Address is the bech32 address of the new contract instance. | -| `data` | [bytes](#bytes) | | Data contains bytes to returned from the contract | - - - - - - - - -### MsgMigrateContract -MsgMigrateContract runs a code upgrade/ downgrade for a smart contract - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | Sender is the that actor that signed the messages | -| `contract` | [string](#string) | | Contract is the address of the smart contract | -| `code_id` | [uint64](#uint64) | | CodeID references the new WASM code | -| `msg` | [bytes](#bytes) | | Msg json encoded message to be passed to the contract on migration | - - - - - - - - -### MsgMigrateContractResponse -MsgMigrateContractResponse returns contract migration result data. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `data` | [bytes](#bytes) | | Data contains same raw bytes returned as data from the wasm contract. (May be empty) | - - - - - - - - -### MsgStoreCode -MsgStoreCode submit Wasm code to the system - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | Sender is the that actor that signed the messages | -| `wasm_byte_code` | [bytes](#bytes) | | WASMByteCode can be raw or gzip compressed | -| `instantiate_permission` | [AccessConfig](#cosmwasm.wasm.v1.AccessConfig) | | InstantiatePermission access control to apply on contract creation, optional | - - - - - - - - -### MsgStoreCodeResponse -MsgStoreCodeResponse returns store result data. - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `code_id` | [uint64](#uint64) | | CodeID is the reference to the stored WASM code | -| `checksum` | [bytes](#bytes) | | Checksum is the sha256 hash of the stored code | - - - - - - - - -### MsgUpdateAdmin -MsgUpdateAdmin sets a new admin for a smart contract - - -| Field | Type | Label | Description | -| ----- | ---- | ----- | ----------- | -| `sender` | [string](#string) | | Sender is the that actor that signed the messages | -| `new_admin` | [string](#string) | | NewAdmin address to be set | -| `contract` | [string](#string) | | Contract is the address of the smart contract | - - - - - - - - -### MsgUpdateAdminResponse -MsgUpdateAdminResponse returns empty data - - - - - - - - - - - - - - -### Msg -Msg defines the wasm Msg service. - -| Method Name | Request Type | Response Type | Description | HTTP Verb | Endpoint | -| ----------- | ------------ | ------------- | ------------| ------- | -------- | -| `StoreCode` | [MsgStoreCode](#cosmwasm.wasm.v1.MsgStoreCode) | [MsgStoreCodeResponse](#cosmwasm.wasm.v1.MsgStoreCodeResponse) | StoreCode to submit Wasm code to the system | | -| `InstantiateContract` | [MsgInstantiateContract](#cosmwasm.wasm.v1.MsgInstantiateContract) | [MsgInstantiateContractResponse](#cosmwasm.wasm.v1.MsgInstantiateContractResponse) | InstantiateContract creates a new smart contract instance for the given code id. | | -| `InstantiateContract2` | [MsgInstantiateContract2](#cosmwasm.wasm.v1.MsgInstantiateContract2) | [MsgInstantiateContract2Response](#cosmwasm.wasm.v1.MsgInstantiateContract2Response) | InstantiateContract2 creates a new smart contract instance for the given code id with a predictable address | | -| `ExecuteContract` | [MsgExecuteContract](#cosmwasm.wasm.v1.MsgExecuteContract) | [MsgExecuteContractResponse](#cosmwasm.wasm.v1.MsgExecuteContractResponse) | Execute submits the given message data to a smart contract | | -| `MigrateContract` | [MsgMigrateContract](#cosmwasm.wasm.v1.MsgMigrateContract) | [MsgMigrateContractResponse](#cosmwasm.wasm.v1.MsgMigrateContractResponse) | Migrate runs a code upgrade/ downgrade for a smart contract | | -| `UpdateAdmin` | [MsgUpdateAdmin](#cosmwasm.wasm.v1.MsgUpdateAdmin) | [MsgUpdateAdminResponse](#cosmwasm.wasm.v1.MsgUpdateAdminResponse) | UpdateAdmin sets a new admin for a smart contract | | -| `ClearAdmin` | [MsgClearAdmin](#cosmwasm.wasm.v1.MsgClearAdmin) | [MsgClearAdminResponse](#cosmwasm.wasm.v1.MsgClearAdminResponse) | ClearAdmin removes any admin stored for a smart contract | | - - - - - -## 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/go.mod b/go.mod index 241614e..48f1e7c 100644 --- a/go.mod +++ b/go.mod @@ -1,142 +1,185 @@ module github.com/terpnetwork/terp-core -go 1.19 +go 1.20 require ( - github.com/CosmWasm/wasmvm v1.2.0 - github.com/cosmos/cosmos-proto v1.0.0-beta.1 - github.com/cosmos/cosmos-sdk v0.45.11 - github.com/cosmos/gogoproto v1.4.3 - github.com/cosmos/iavl v0.19.4 - github.com/cosmos/ibc-go/v4 v4.2.0 - github.com/cosmos/interchain-accounts v0.2.4 + github.com/CosmWasm/wasmvm v1.2.1 + github.com/cometbft/cometbft v0.37.0 + github.com/cometbft/cometbft-db v0.7.0 + github.com/cosmos/cosmos-proto v1.0.0-beta.2 + github.com/cosmos/cosmos-sdk v0.47.1 + github.com/cosmos/gogogateway v1.2.0 // indirect + github.com/cosmos/gogoproto v1.4.7 + github.com/cosmos/iavl v0.20.0 + github.com/cosmos/ibc-go/v7 v7.0.0 + github.com/cosmos/ics23/go v0.9.1-0.20221207100636-b1abd8678aab // indirect github.com/docker/distribution v2.8.1+incompatible - github.com/dvsekhvalnov/jose2go v1.5.0 - github.com/gogo/protobuf v1.3.3 - github.com/golang/protobuf v1.5.2 + github.com/dvsekhvalnov/jose2go v1.5.0 // indirect + github.com/golang/protobuf v1.5.3 github.com/google/gofuzz v1.2.0 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.14.0 - github.com/rakyll/statik v0.1.7 + github.com/rakyll/statik v0.1.7 // indirect github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa github.com/spf13/cast v1.5.0 github.com/spf13/cobra v1.6.1 github.com/spf13/pflag v1.0.5 - github.com/stretchr/testify v1.8.1 - github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 - github.com/tendermint/tendermint v0.34.24 - github.com/tendermint/tm-db v0.6.7 - google.golang.org/genproto v0.0.0-20230209215440-0dfe4f8abfcc - google.golang.org/grpc v1.51.0 + github.com/stretchr/testify v1.8.2 + github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d + google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44 + google.golang.org/grpc v1.53.0 gopkg.in/yaml.v2 v2.4.0 ) require ( - filippo.io/edwards25519 v1.0.0-beta.2 // indirect + cosmossdk.io/api v0.3.1 + cosmossdk.io/core v0.5.1 + cosmossdk.io/errors v1.0.0-beta.7 + cosmossdk.io/math v1.0.0 + cosmossdk.io/tools/rosetta v0.2.1 + github.com/spf13/viper v1.15.0 +) + +require ( + cloud.google.com/go v0.110.0 // indirect + cloud.google.com/go/compute v1.18.0 // indirect + cloud.google.com/go/compute/metadata v0.2.3 // indirect + cloud.google.com/go/iam v0.12.0 // indirect + cloud.google.com/go/storage v1.29.0 // indirect + cosmossdk.io/depinject v1.0.0-alpha.3 // 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/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect - github.com/Workiva/go-datastructures v1.0.53 // indirect github.com/armon/go-metrics v0.4.1 // indirect + github.com/aws/aws-sdk-go v1.44.203 // indirect github.com/beorn7/perks v1.0.1 // indirect - github.com/bgentry/speakeasy v0.1.0 // indirect - github.com/btcsuite/btcd v0.22.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.1.2 // indirect - github.com/coinbase/rosetta-sdk-go v0.7.0 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/chzyer/readline v1.5.1 // indirect + github.com/cockroachdb/apd/v2 v2.0.2 // indirect + github.com/coinbase/rosetta-sdk-go/types v1.0.0 // indirect github.com/confio/ics23/go v0.9.0 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect - github.com/cosmos/gorocksdb v1.2.0 // indirect - github.com/cosmos/ledger-cosmos-go v0.11.1 // indirect - github.com/cosmos/ledger-go v0.9.3 // indirect - github.com/creachadair/taskgroup v0.3.2 // indirect + github.com/cosmos/ledger-cosmos-go v0.12.1 // 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/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.0 // indirect + github.com/dgraph-io/ristretto v0.1.1 // indirect github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect - github.com/dustin/go-humanize v1.0.1-0.20200219035652-afde56e7acac // indirect - github.com/felixge/httpsnoop v1.0.1 // indirect + github.com/dustin/go-humanize v1.0.1 // 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.5.1 // indirect + github.com/go-logfmt/logfmt v0.6.0 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect - github.com/gogo/gateway v1.1.0 // indirect - github.com/golang/glog v1.0.0 // indirect + github.com/gogo/googleapis v1.4.1 // indirect + github.com/gogo/protobuf v1.3.2 // 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/snappy v0.0.4 // 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/uuid v1.3.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect + github.com/googleapis/gax-go/v2 v2.7.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 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.0 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect - github.com/hashicorp/golang-lru v0.5.4 // 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.0.0-20210204194344-59a8610d2b87 // indirect - github.com/improbable-eng/grpc-web v0.14.1 // indirect - github.com/inconshreveable/mousetrap v1.0.1 // indirect + github.com/hdevalence/ed25519consensus v0.1.0 // indirect + github.com/huandu/skiplist v1.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 github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.15.11 // indirect - github.com/lib/pq v1.10.6 // indirect + github.com/json-iterator/go v1.1.12 // indirect + 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/magiconair/properties v1.8.6 // indirect - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.16 // indirect - github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/manifoldco/promptui v0.9.0 // indirect + github.com/mattn/go-isatty v0.0.17 // 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 + 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/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect github.com/mtibben/percent v0.2.1 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/pelletier/go-toml v1.9.5 // indirect - github.com/pelletier/go-toml/v2 v2.0.5 // indirect - github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect + github.com/pelletier/go-toml/v2 v2.0.6 // indirect + github.com/petermattis/goid v0.0.0-20221215004737-a150e88a970d // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_model v0.3.0 // indirect - github.com/prometheus/common v0.37.0 // indirect - github.com/prometheus/procfs v0.8.0 // indirect + github.com/prometheus/common v0.40.0 // indirect + github.com/prometheus/procfs v0.9.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/regen-network/cosmos-proto v0.3.1 // indirect - github.com/rs/cors v1.8.2 // indirect - github.com/rs/zerolog v1.27.0 // indirect + github.com/rs/cors v1.8.3 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect - github.com/spf13/afero v1.9.2 // indirect + github.com/spf13/afero v1.9.3 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect - github.com/spf13/viper v1.14.0 // indirect - github.com/subosito/gotenv v1.4.1 // indirect - github.com/tendermint/btcd v0.1.1 // indirect - github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 // 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/zondax/hid v0.9.0 // indirect - go.etcd.io/bbolt v1.3.6 // indirect - golang.org/x/crypto v0.6.0 // indirect - golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e // indirect - golang.org/x/net v0.6.0 // indirect - golang.org/x/sys v0.5.0 // indirect - golang.org/x/term v0.5.0 // indirect - golang.org/x/text v0.7.0 // indirect - golang.org/x/tools v0.3.0 // indirect - google.golang.org/protobuf v1.28.2-0.20220831092852-f930b1dc76e8 // indirect + github.com/tidwall/btree v1.6.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 + golang.org/x/crypto v0.7.0 // indirect + golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect + golang.org/x/net v0.8.0 // indirect + golang.org/x/oauth2 v0.5.0 // indirect + golang.org/x/sys v0.6.0 // indirect + golang.org/x/term v0.6.0 // indirect + golang.org/x/text v0.8.0 // indirect + golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect + google.golang.org/api v0.110.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/protobuf v1.29.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect nhooyr.io/websocket v1.8.6 // indirect + pgregory.net/rapid v0.5.5 // indirect + sigs.k8s.io/yaml v1.3.0 // indirect ) replace ( - github.com/confio/ics23/go => github.com/cosmos/cosmos-sdk/ics23/go v0.8.0 + github.com/99designs/keyring => github.com/cosmos/keyring v1.2.0 + // dgrijalva/jwt-go is deprecated and doesn't receive security updates. + // See: https://github.com/cosmos/cosmos-sdk/issues/13134 + github.com/dgrijalva/jwt-go => github.com/golang-jwt/jwt/v4 v4.4.2 // Fix upstream GHSA-h395-qcrw-5vmq vulnerability. - // TODO Remove it: https://github.com/cosmos/cosmos-sdk/issues/10409 - github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.7.0 - // latest grpc doesn't work with with our modified proto compiler, so we need to enforce - // the following version across all dependencies. - github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1 - google.golang.org/grpc => google.golang.org/grpc v1.33.2 + // See: https://github.com/cosmos/cosmos-sdk/issues/10409 + github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.8.1 + + // pin version! 126854af5e6d has issues with the store so that queries fail + github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 ) diff --git a/go.sum b/go.sum index 3da056b..0db49ef 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,4 @@ +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= @@ -16,54 +17,202 @@ cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHOb 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.0 h1:Zc8gqp3+a9/Eyph2KDmcGaPtbKRIoqq4YTlL4NMD0Ys= +cloud.google.com/go v0.110.0/go.mod h1:SJnCLqQ0FCFGSZMUNUf84MV3Aia54kn7pi8st7tMzaY= +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.18.0 h1:FEigFqoDbys2cvFkZ9Fjq4gnHBP55anJ0yQyau2f9oY= +cloud.google.com/go/compute v1.18.0/go.mod h1:1X7yHxec2Ga+Ss6jPyjxRxpu2uu7PLgsOVXvgU0yacs= +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 v0.12.0 h1:DRtTY29b75ciH6Ov1PHb4/iat2CLCvrOm40Q0a6DFpE= +cloud.google.com/go/iam v0.12.0/go.mod h1:knyHGviacl11zrtZUoDuYpDgLjvr28sLQaG0YB2GYAY= +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.3.0 h1:NjljC+FYPV3uh5/OwWT6pVU+doBqMg2x/rZlE+CamDs= +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.29.0 h1:6weCgzRvMg7lzuUurI4697AqIRPU1SvzHhynwpW31jI= +cloud.google.com/go/storage v1.29.0/go.mod h1:4puEjyTKnku6gfKoTfNOU/W+a9JyuVNxjpS5GBrB8h4= +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.5.1 h1:vQVtFrIYOQJDV3f7rw4pjjVqc1id4+mE0L9hHP66pyI= +cosmossdk.io/core v0.5.1/go.mod h1:KZtwHCLjcFuo0nmDc24Xy6CRNEL9Vl/MeimQ2aC7NLE= +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/math v1.0.0 h1:ro9w7eKx23om2tZz/VM2Pf+z2WAbGX1yDQQOJ6iGeJw= +cosmossdk.io/math v1.0.0/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-beta.2 h1:/BZRNzm8N4K4eWfK28dL4yescorxtO7YG1yun8fy+pI= -filippo.io/edwards25519 v1.0.0-beta.2/go.mod h1:X+pm78QAUPtFLi1z9PYIlS/bdDnvbCOGKtZ+ACWEf7o= +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.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o= -github.com/99designs/keyring v1.2.1/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA= -github.com/Azure/azure-pipeline-go v0.2.1/go.mod h1:UGSo8XybXnIGZ3epmeBw7Jdz+HiUVpqIlpz/HKHylF4= -github.com/Azure/azure-pipeline-go v0.2.2/go.mod h1:4rQ/NZncSvGqNkkOsNpOU1tgoNuIlp9AfUH5G1tvCHc= -github.com/Azure/azure-storage-blob-go v0.7.0/go.mod h1:f9YQKtsG1nMisotuTPpO0tjNuEjKRYAcJU8/ydDI++4= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= -github.com/Azure/go-autorest/autorest v0.9.0/go.mod h1:xyHB1BMZT0cuDHU7I0+g046+BFDTQ8rEZB0s4Yfa6bI= -github.com/Azure/go-autorest/autorest/adal v0.5.0/go.mod h1:8Z9fGy2MpX0PvDjB1pEgQTmVqjGhiHBW7RJJEciWzS0= -github.com/Azure/go-autorest/autorest/adal v0.8.0/go.mod h1:Z6vX6WXXuyieHAXwMj0S6HY6e6wcHn37qQMBQlvY3lc= -github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= -github.com/Azure/go-autorest/autorest/date v0.2.0/go.mod h1:vcORJHLJEh643/Ioh9+vPmf1Ij9AEBM5FuBIXLmIy0g= -github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= -github.com/Azure/go-autorest/autorest/mocks v0.2.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= -github.com/Azure/go-autorest/autorest/mocks v0.3.0/go.mod h1:a8FDP3DYzQ4RYfVAxAN3SVSiiO77gL2j2ronKKP0syM= -github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= -github.com/Azure/go-autorest/tracing v0.5.0/go.mod h1:r/s2XiOKccPW3HrqB+W0TQzfbtp2fGCgRFtBroKn4Dk= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d h1:nalkkPQcITbvhmL4+C4cKA87NW0tfm3Kl9VXRoPywFg= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d/go.mod h1:URdX5+vg25ts3aCh8H5IFZybJYKWhJHYMTnf+ULtoC4= -github.com/CosmWasm/wasmvm v1.2.0 h1:pNCp175id+r/dSa4Ii5zoTkmauOoeipkvepvEJM1bao= -github.com/CosmWasm/wasmvm v1.2.0/go.mod h1:OIhXFPi9BbcEL1USBj4OIrBTtSSds+9eEql56fsdyfE= +github.com/CosmWasm/wasmvm v1.2.1 h1:si0tRsRDdUShV0k51Wn6zRKlmj3/WWP9Yr4cLmDTf+8= +github.com/CosmWasm/wasmvm v1.2.1/go.mod h1:vW/E3h8j9xBQs9bCoijDuawKo9kCtxOaS8N8J7KFtkc= github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= -github.com/DataDog/zstd v1.4.1/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= -github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= 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/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= @@ -71,26 +220,19 @@ 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/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= -github.com/VictoriaMetrics/fastcache v1.5.7/go.mod h1:ptDBkNMQI4RtmVo8VS/XwRY6RoTu1dAWCbrk+6WsEM8= 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/Workiva/go-datastructures v1.0.53 h1:J6Y/52yX10Xc5JjXmGtWoSSxs3mZnGSaq37xZZh7Yig= -github.com/Workiva/go-datastructures v1.0.53/go.mod h1:1yZL+zfsztete+ePzZz/Zb1/t5BnDuE2Ya2MMGhzP6A= -github.com/Zilliqa/gozilliqa-sdk v1.2.1-0.20201201074141-dd0ecada1be6/go.mod h1:eSYp2T6f0apnuW8TzhV3f6Aff2SE8Dwio++U4ha4yEM= github.com/adlio/schema v1.3.3 h1:oBJn8I02PyTB466pZO1UZEn1TV5XLlifBSyMrmHl/1I= -github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= 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/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= 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/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847/go.mod h1:D/tb0zPVXnP7fmsLZjtdUhSsumbK/ij54UXjjVgMGxQ= 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= @@ -99,150 +241,163 @@ github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+ 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/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= -github.com/aws/aws-sdk-go v1.25.48/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= 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/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/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= +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/btcsuite/btcd v0.0.0-20171128150713-2e60448ffcc6/go.mod h1:Dmm/EzmjnCiweXmzRIAiUWCInVmPgjkzgv5k4tVyXiQ= -github.com/btcsuite/btcd v0.0.0-20190115013929-ed77733ec07d/go.mod h1:d3C0AkH6BRcvO8T0UEPu53cnw4IbV63x1bEjildYhO0= -github.com/btcsuite/btcd v0.0.0-20190315201642-aa6e0f35703c/go.mod h1:DrZx5ec/dmnfpw9KyYoQyYo7d0KEvTkk/5M/vbZjAr8= -github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= -github.com/btcsuite/btcd v0.21.0-beta/go.mod h1:ZSWyehm27aAuS9bvkATT+Xte3hjHZ+MRgMY/8NJ7K94= -github.com/btcsuite/btcd v0.22.1 h1:CnwP9LM/M9xuRrGSCGeMVs9iv09uMqwsVX7EeIpgV2c= -github.com/btcsuite/btcd v0.22.1/go.mod h1:wqgTSL29+50LRkmOVknEdmt8ZojIzhuWvgu/iptuN7Y= +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/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= -github.com/btcsuite/btcutil v0.0.0-20180706230648-ab6388e0c60a/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= -github.com/btcsuite/btcutil v0.0.0-20190207003914-4c204d697803/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= -github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= -github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts= -github.com/btcsuite/btcutil v1.0.3-0.20201208143702-a53e38424cce h1:YtWJF7RHm2pYCvA5t0RPmAaLUhREsKuKd+SLhxFbFeQ= -github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= -github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= -github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I= -github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= -github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= -github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= -github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= 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/cp v0.1.0/go.mod h1:SOGHArjBr4JWaSDEVpWpo/hNg6RoKrls6Oh40hiwW+s= 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.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= -github.com/cespare/xxhash/v2 v2.1.2/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/cloudflare/cloudflare-go v0.10.2-0.20190916151808-a80f83b9add9/go.mod h1:1MxXX1Ux4x6mqPmjkUgTP1CdXIBXKX7T+Jk9Gxrmx+U= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 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/v2 v2.0.2/go.mod h1:DDxRlzC2lo3/vSlmSoS7JkqbbrARPuFOGr0B9pvN3Gw= +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 v0.7.0 h1:lmTO/JEpCvZgpbkOITL95rA80CPKb5CtMzLaqF2mCNg= -github.com/coinbase/rosetta-sdk-go v0.7.0/go.mod h1:7nD3oBPIiHqhRprqvMgPoGxe/nyq3yftRmpsy29coWE= +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.0 h1:M005vBaSaugvYYmNZwJOopynQSjwLoDTwflnQ/I/eYk= +github.com/cometbft/cometbft v0.37.0/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/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.3.3-0.20220203105225-a9a7ef127534/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.1 h1:iDL5qh++NoXxG8hSy93FdYJut4XfgbShIocllGaXx/0= -github.com/cosmos/cosmos-proto v1.0.0-beta.1/go.mod h1:8k2GNZghi5sDRFw/scPL8gMSowT1vDA+5ouxL8GjaUE= -github.com/cosmos/cosmos-sdk v0.45.11 h1:Pc44fFEkai0KXFND5Ys/2ZJkfVdstMIBzKBN8MY7Ll0= -github.com/cosmos/cosmos-sdk v0.45.11/go.mod h1:45z8Q1Ah4iypFycu2Kl4kBPIsQKUiND8G2CUX+HTtPM= -github.com/cosmos/cosmos-sdk/ics23/go v0.8.0 h1:iKclrn3YEOwk4jQHT2ulgzuXyxmzmPczUalMwW4XH9k= -github.com/cosmos/cosmos-sdk/ics23/go v0.8.0/go.mod h1:2a4dBq88TUoqoWAU5eu0lGvpFP3wWDPgdHPargtyw30= +github.com/cosmos/cosmos-proto v1.0.0-beta.2 h1:X3OKvWgK9Gsejo0F1qs5l8Qn6xJV/AzgIWR2wZ8Nua8= +github.com/cosmos/cosmos-proto v1.0.0-beta.2/go.mod h1:+XRCLJ14pr5HFEHIUcn51IKXD1Fy3rkEQqt4WqmN4V0= +github.com/cosmos/cosmos-sdk v0.47.1 h1:HnaCYtaAMWZp1SdlwwE1mPJ8kFlZ/TuEJ/ciNXH6Uno= +github.com/cosmos/cosmos-sdk v0.47.1/go.mod h1:14tO5KQaTrl2q3OxBnDRfue7TRN9zkXS0cLutrSqkOo= 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/gogoproto v1.4.3 h1:RP3yyVREh9snv/lsOvmsAPQt8f44LgL281X0IOIhhcI= -github.com/cosmos/gogoproto v1.4.3/go.mod h1:0hLIG5TR7IvV1fme1HCFKjfzW9X2x0Mo+RooWXCnOWU= -github.com/cosmos/gorocksdb v1.2.0 h1:d0l3jJG8M4hBouIZq0mDUHZ+zjOx044J3nGRskwTb4Y= -github.com/cosmos/gorocksdb v1.2.0/go.mod h1:aaKvKItm514hKfNJpUJXnnOWeBnk2GL4+Qw9NHizILw= -github.com/cosmos/iavl v0.19.4 h1:t82sN+Y0WeqxDLJRSpNd8YFX5URIrT+p8n6oJbJ2Dok= -github.com/cosmos/iavl v0.19.4/go.mod h1:X9PKD3J0iFxdmgNLa7b2LYWdsGd90ToV5cAONApkEPw= -github.com/cosmos/ibc-go/v4 v4.2.0 h1:Fx/kKq/uvawrAxk6ZrQ6sEIgffLRU5Cs/AUnvpPBrHI= -github.com/cosmos/ibc-go/v4 v4.2.0/go.mod h1:57qWScDtfCx3FOMLYmBIKPbOLE6xiVhrgxHAQmbWYXM= -github.com/cosmos/interchain-accounts v0.2.4 h1:7UrroFQsCRSp17980mk6anx4YteveIJVkU+a0wlsHQI= -github.com/cosmos/interchain-accounts v0.2.4/go.mod h1:jeiJEb0zg609G0oCrCG0r6Guhb7YbA1uFiwww/1YgZE= -github.com/cosmos/ledger-cosmos-go v0.11.1 h1:9JIYsGnXP613pb2vPjFeMMjBI5lEDsEaF6oYorTy6J4= -github.com/cosmos/ledger-cosmos-go v0.11.1/go.mod h1:J8//BsAGTo3OC/vDLjMRFLW6q0WAaXvHnVc7ZmE8iUY= -github.com/cosmos/ledger-go v0.9.2/go.mod h1:oZJ2hHAZROdlHiwTg4t7kP+GKIIkBT+o6c9QWFanOyI= -github.com/cosmos/ledger-go v0.9.3 h1:WGyZK4ikuLIkbxJm3lEr1tdQYDdTdveTwoVla7hqfhQ= -github.com/cosmos/ledger-go v0.9.3/go.mod h1:oZJ2hHAZROdlHiwTg4t7kP+GKIIkBT+o6c9QWFanOyI= +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.7 h1:RzYKVnsEC7UIkDnhTIkqEB7LnIQbsySvmNEqPCiPevk= +github.com/cosmos/gogoproto v1.4.7/go.mod h1:gxGePp9qedovvl/StQL2BIJ6qlIBn1+9YxR0IulGBKA= +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.0 h1:j4kyywlG0hhDmT9FmSaR5iCIka7Pz7kJTxGWY1nlV9Q= +github.com/cosmos/ibc-go/v7 v7.0.0/go.mod h1:BFh8nKWjr5zeR2OZfhkzdgDzj1+KjRn3aJLpwapStj8= +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/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/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.3.2 h1:zlfutDS+5XG40AOxcHDSThxKzns8Tnr9jnr6VqkYlkM= -github.com/creachadair/taskgroup v0.3.2/go.mod h1:wieWwecHVzsidg2CsUnFinW1faVN4+kq+TDlRJQ0Wbk= +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/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +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 v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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 v0.0.0-20180603214616-504e848d77ea/go.mod h1:93vsz/8Wt4joVM7c2AVqh+YRMiUSc14yDtF28KmMOgQ= -github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= +github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= +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.2/go.mod h1:26P/7fbL4kUZVEVKLAKXkBXKOydDmM2p1e+NhhnBCAE= 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.0.3/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= -github.com/dgraph-io/ristretto v0.1.0 h1:Jv3CGQHp9OjuMBSne1485aDpUkTKEcUqF+jm/LuerPI= -github.com/dgraph-io/ristretto v0.1.0/go.mod h1:fux0lOrBhrVCJd3lcTHsIJhq1T2rokOu6v9Vcb3Q9ug= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgraph-io/ristretto v0.1.1 h1:6CWw5tJNgpegArSHpNHJKldNeq03FQCwYvfMVWajOK8= +github.com/dgraph-io/ristretto v0.1.1/go.mod h1:S1GPSBCYCIhmVNfcth17y2zZtQT6wzkzgwUve0VDWWA= 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/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/dlclark/regexp2 v1.2.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/docker/distribution v2.8.1+incompatible h1:Q50tZOPR6T/hjNsyc9g8/syEs6bk8XXApsHjKukMl68= github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v1.4.2-0.20180625184442-8e610b2b55bf/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= -github.com/dop251/goja v0.0.0-20200721192441-a695b0cdd498/go.mod h1:Mw6PkjjMXWbTj+nnj4s3QPXq1jaT0s5pC0iFD4+BOAA= 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-0.20200219035652-afde56e7acac h1:opbrjaN/L8gg6Xh5D04Tem+8xVcz6ajZlGCs49mQgyg= -github.com/dustin/go-humanize v1.0.1-0.20200219035652-afde56e7acac/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/dvyukov/go-fuzz v0.0.0-20200318091601-be3528f3a813/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw= 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 v0.0.0-20160512033002-935e0e8a636c/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= 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.9.25/go.mod h1:vMkFiYLHI4tgPw4k2j4MHKoovchFE8plZ0M9VMk4/oM= 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.3.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= -github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ= github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/fjl/memsize v0.0.0-20180418122429-ca190fb6ffbc/go.mod h1:VvhXpOYNQvB+uIk2RvXzuaQtkQJzzIx6lSBe1xv7hi0= +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= @@ -251,12 +406,11 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= -github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff/go.mod h1:x7DCsMOv1taUwEWCzT4cmDeAkigA5/QCwUodaVOe8Ww= 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.7.0 h1:jGB9xAJQ12AIGNB4HguylppmDK1Am9ppF7XnGXXJuoU= -github.com/gin-gonic/gin v1.7.0/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY= +github.com/gin-gonic/gin v1.8.1 h1:4+fr/el88TOO3ewCmQr8cx/CtZ/umlIRIs5M4NTNjf8= +github.com/gin-gonic/gin v1.8.1/go.mod h1:ji8BvRH1azfM+SYow9zQ6SZMvR8qOMZHmsCuWR9tTTk= 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= @@ -265,24 +419,20 @@ github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2 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.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= -github.com/go-kit/log v0.2.0/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= 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.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA= -github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= -github.com/go-ole/go-ole v1.2.1/go.mod h1:7FAglXiTm7HKlQRDeOQ6ZNUHidzCWXuZWq/1dTyBNF8= +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-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 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= -github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/go-sourcemap/sourcemap v2.1.2+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= +github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU= +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/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= @@ -291,25 +441,41 @@ 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/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= -github.com/gogo/gateway v1.1.0 h1:u0SuhL9+Il+UbjM9VIE3ntfRujKbvVpFvNB4HbjeVQ0= -github.com/gogo/gateway v1.1.0/go.mod h1:S7rR8FRQyG3QFESeSv4l2WnsyzlCLG0CzBbUUo/mbic= +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/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= +github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/glog v1.0.0 h1:nfP3RFugxnNRyKgeWd4oI1nYvXpxrx8ck8ZrcizshdQ= -github.com/golang/glog v1.0.0/go.mod h1:EWib/APOK0SL3dFbYqvxE3UYd8E6s1ouQ7iEp/0LWV4= +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= @@ -326,11 +492,11 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD 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.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= +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.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.3-0.20201103224600-674baa8c7fc3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= @@ -346,17 +512,24 @@ github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ 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.1.1-0.20200604201612-c04b05f3adfa/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +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= @@ -369,12 +542,33 @@ github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hf 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-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/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.1.1/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.7.0 h1:IcsPKeInNvYi7eqSaDjiZqDDKu5rsmunY0Y1YupQSSQ= +github.com/googleapis/gax-go/v2 v2.7.0/go.mod h1:TEop28CZZQ2y+c0VxMUmu1lV+fQx57QpBWsYpwqHJx8= +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= @@ -385,17 +579,14 @@ github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2z 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-0.20190629185528-ae1634f6a989/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/graph-gophers/graphql-go v0.0.0-20191115155744-f33e81362277/go.mod h1:9CQHMSxwO4MprSdzoIEobiHpoLtHm77vfxsvsIN5Vuc= 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.8.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= 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= @@ -411,6 +602,10 @@ github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyN 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.0 h1:bzrYP+qu/gMrL1au7/aDvkoOVGUJpeKBgbqRHACAFDY= +github.com/hashicorp/go-getter v1.7.0/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= @@ -418,117 +613,113 @@ github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iP 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.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= -github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +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.0.0-20210204194344-59a8610d2b87 h1:uUjLpLt6bVvZ72SQc/B4dXcPBw4Vgd7soowdRl52qEM= -github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87/go.mod h1:XGsKKeXxeRr95aEOgipvluMPlgjr7dGlk9ZTWOjcUcg= -github.com/holiman/uint256 v1.1.1/go.mod h1:y4ga/t+u+Xwd7CpDgZESaRcWy0I7XMlTMA25ApIH5Jw= +github.com/hdevalence/ed25519consensus v0.1.0 h1:jtBwzzcHuTmFrQN6xQZn6CQEO/V9f7HsjsjeEZ6auqU= +github.com/hdevalence/ed25519consensus v0.1.0/go.mod h1:w3BHWjwJbFU29IRHL1Iqkw3sus+7FctEyM4RqDxYNzo= 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/huin/goupnp v1.0.0/go.mod h1:n9v9KO1tAxYH82qOn+UTIFQDmx5n1Zxd/ClZDMX7Bnc= -github.com/huin/goutil v0.0.0-20170803182201-1ca381bf3150/go.mod h1:PpLOETDnJ0o3iZrZfqZzyLl6l7F3c6L1oWn7OICBi6o= 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.14.1 h1:NrN4PY71A6tAz2sKDvC5JCauENWp0ykG8Oq1H3cpFvw= -github.com/improbable-eng/grpc-web v0.14.1/go.mod h1:zEjGHa8DAlkoOXmswrNvhUGEYQA9UI7DhrGeHR1DMGU= +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 h1:U3uMjPSQEBMNp1lFxmllqCPM6P5u/Xq7Pgzkat/bFNc= github.com/inconshreveable/mousetrap v1.0.1/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -github.com/influxdata/influxdb v1.2.3-0.20180221223340-01288bdb0883/go.mod h1:qZna6X/4elxqT3yI9iZYdZrWWdeFOOprn86kgg4+IzY= +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/jackpal/go-nat-pmp v1.0.2-0.20160603034137-1fa385a6f458/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc= -github.com/jedisct1/go-minisign v0.0.0-20190909160543-45766022959e/go.mod h1:G1CVv03EnqU1wYL2dFwXxW2An0az9JTl/ZsqXQeBlkU= -github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= -github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jhump/protoreflect v1.12.1-0.20220721211354-060cc04fc18b h1:izTof8BKh/nE1wrKOrloNA5q4odOarjf+Xpe+4qow98= 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/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= 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.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 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.1.1-0.20170430222011-975b5c4c7c21/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= 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/karalabe/usb v0.0.0-20190919080040-51dc0efba356/go.mod h1:Od972xHfMJowv7NGVDiWVxk2zxnWgjLlJzE+F4F7AGU= +github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= 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/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= 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 h1:Lcadnb3RKGin4FYM/orgq0qde+nc15E5Cbqg4B9Sx9c= 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/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.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +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/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/lib/pq v1.10.6 h1:jbk+ZieJ0D7EVGJYpL9QTz7/YW6UHbmdnZWYyK5cdBs= -github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= +github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= +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/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/lucasjones/reggen v0.0.0-20180717132126-cdb49ff09d77/go.mod h1:5ELEyG+X8f+meRWHuqUOewBOhvHkl7M76pdGEansxW4= +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.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= -github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +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.0/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -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-ieproxy v0.0.0-20190610004146-91bb50d98149/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= -github.com/mattn/go-ieproxy v0.0.0-20190702010315-6dee0af9227d/go.mod h1:31jz6HNzdxOmlERGGEc4v/dMssOfmp2p5bT/okiKFFc= 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.5-0.20180830101745-3fb116b82035/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 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= +github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.3/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= -github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI= -github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= +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-20210601165009-122bf33a46e0 h1:QRUSJEgZn2Snx0EmT/QLXibWjSUDjKWvXIT19NBVp94= @@ -537,13 +728,15 @@ github.com/minio/highwayhash v1.0.2 h1:Aak5U0nElisjDCfPSG79Tgzkn2gl66NxOMspRrKnA github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= 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.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 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/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -559,8 +752,6 @@ github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRW 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/naoina/go-stringutil v0.1.0/go.mod h1:XJ2SJL9jCtBh+P9q5btrd/Ylo8XwT/h1USek5+NqSA0= -github.com/naoina/toml v0.1.2-0.20170918210437-9fafd6967416/go.mod h1:NBIhNtsFMo3G2szEBne+bO4gS192HuIYRqfvOWb4i1E= 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= @@ -568,27 +759,21 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE 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/neilotoole/errgroup v0.1.5/go.mod h1:Q2nLGf+594h0CLBs/Mbg6qOr7GtqDK7C2S41udRnToE= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= 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/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= -github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= -github.com/olekukonko/tablewriter v0.0.2-0.20190409134802-7e037d187b0c/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.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= -github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= 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 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +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= @@ -603,25 +788,22 @@ github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJ 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/otiai10/copy v1.6.0 h1:IinKAryFFuPONZ7cm6T6E2QX/vcJwSnlaA5lfoaXIiQ= 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 v0.0.0-20170112150404-1b00554d8222/go.mod h1:VyrYX9gd7irzKovcSS6BIIEwPRkP2Wm2m9ufcdFSJ34= 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.5 h1:ipoSadvV8oGUjnUbMub59IDPPwfxF694nG/jwbMiyQg= -github.com/pelletier/go-toml/v2 v2.0.5/go.mod h1:OMHamSCAODeSsVrwwvcJOaoN0LIUIaFVNZzmWyNfXas= +github.com/pelletier/go-toml/v2 v2.0.1/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= +github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= +github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= -github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0= -github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ= github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= -github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= +github.com/petermattis/goid v0.0.0-20221215004737-a150e88a970d h1:htwtWgtQo8YS6JFWWi2DNgY0RwSGJ1ruMoxY6CUUclk= +github.com/petermattis/goid v0.0.0-20221215004737-a150e88a970d/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/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 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= @@ -637,8 +819,6 @@ 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.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= @@ -649,50 +829,37 @@ github.com/prometheus/client_model v0.1.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6T 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.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= 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.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= -github.com/prometheus/common v0.32.1/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= -github.com/prometheus/common v0.37.0 h1:ccBbHCgIiT9uSoFY0vX8H3zsNR5eLt17/RQLUvn8pXE= -github.com/prometheus/common v0.37.0/go.mod h1:phzohg0JFMnBEFGxTDbfu3QyL5GI8gTQJFhYO5B3mfA= +github.com/prometheus/common v0.40.0 h1:Afz7EVRqGg2Mqqf4JuF9vdvp1pi220m55Pi9T2JnO4Q= +github.com/prometheus/common v0.40.0/go.mod h1:L65ZJPSmfn/UBWLQIHV7dBrKFidB/wPlF1y5TlSt9OE= 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.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.8.0 h1:ODq8ZFEaYeCaZOJlZZdJA2AbQR98dSHSM1KW/You5mo= -github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4= -github.com/prometheus/tsdb v0.6.2-0.20190402121629-4f204dcbc150/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= +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/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/cosmos-proto v0.3.1 h1:rV7iM4SSFAagvy8RiyhiACbWEGotmqzywPxOvwMdxcg= -github.com/regen-network/cosmos-proto v0.3.1/go.mod h1:jO0sVX6a1B36nmE8C9xBFXpNwWejXC7QqCOnH3O0+YM= -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/rjeczalik/notify v0.9.1/go.mod h1:rKwnCoCGeuQnwBtTSPL9Dad03Vh2n40ePRrjvIXnJho= +github.com/regen-network/gocuke v0.6.2 h1:pHviZ0kKAq2U2hN2q3smKNxct6hS0mGByFMHGnWA97M= 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.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= -github.com/rs/cors v0.0.0-20160617231935-a62a804a8a00/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +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.2 h1:KCooALfAYGs415Cwu5ABvv9n9509fSiG5SQJn/AQo4U= -github.com/rs/cors v1.8.2/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= -github.com/rs/xhandler v0.0.0-20160618193221-ed27b6fd6521/go.mod h1:RvLn4FgxWubrpZHtQLnOf6EwhN2hEMusxZOhcW9H3UQ= -github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.27.0 h1:1T7qCieN22GVc8S4Q2yuexzBb1EqjbgjSH9RohbMjKs= -github.com/rs/zerolog v1.27.0/go.mod h1:7frBqO0oezxmnO7GF86FY++uy8I0Tk/If5ni1G9Qc0U= +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/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= @@ -701,8 +868,6 @@ github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0 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/segmentio/fasthash v1.0.3/go.mod h1:waKX8l2N8yckOgmSsXJi7x1ZfdKZ4x7KRMzBtS3oedY= -github.com/shirou/gopsutil v2.20.5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= 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= @@ -719,8 +884,8 @@ github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasO 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.2 h1:j49Hj62F0n+DaZ1dDCvhABaPNSGNkt32oRFxI33IEMw= -github.com/spf13/afero v1.9.2/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= +github.com/spf13/afero v1.9.3 h1:41FoI0fD7OR7mGcKE/aOiLkGreyf8ifIOQmJANWogMk= +github.com/spf13/afero v1.9.3/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.5.0 h1:rj3WzYc11XZaIZMPKmwP96zkFEnnAmV8s6XbB2aY32w= github.com/spf13/cast v1.5.0/go.mod h1:SpXXQ5YoyJw6s3/6cMTQuxvgRl3PCJiyaX9p6b155UU= @@ -736,11 +901,8 @@ github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn 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.14.0 h1:Rg7d3Lo706X9tHsJMUjdiwMpHB7W8WnSVOssIY+JElU= -github.com/spf13/viper v1.14.0/go.mod h1:WT//axPky3FdvXHzGw33dNdXXXfFQqmEalje+egj8As= -github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4/go.mod h1:RZLeN1LMWmRsyYjvAu+I6Dm9QmlDaIIt+Y+4Kd7Tp+Q= -github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570/go.mod h1:8OR4w3TdeIHIh1g6EMY5p0gVNOovcWC+1vpc7naMuAw= -github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3/go.mod h1:hpGUWaI9xL8pRQCTXQgocU38Qw1g0Us7n5PxxTwTCYU= +github.com/spf13/viper v1.15.0 h1:js3yy885G8xwJa6iOISGFwd+qlUo5AvyXb7CiihdtiU= +github.com/spf13/viper v1.15.0/go.mod h1:fFcTBJxvhhzSJiZy8n+PeW6t8l+KeT/uTARa0jHOQLA= 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= @@ -757,55 +919,46 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ 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.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs= -github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= -github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca/go.mod h1:u2MKkTVTVJWe5D1rCvame8WqhBd88EuIwODJZ1VHCPM= +github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +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/tendermint/btcd v0.1.1 h1:0VcxPfflS2zZ3RiOAHkBiFUcPvbtRj5O7zHmcJWHV7s= -github.com/tendermint/btcd v0.1.1/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrnDD5pN+U= -github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 h1:hqAk8riJvK4RMWx1aInLzndwxKalgi5rTqgfXxOxbEI= -github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk= +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/tendermint/tendermint v0.34.24 h1:879MKKJWYYPJEMMKME+DWUTY4V9f/FBpnZDI82ky+4k= -github.com/tendermint/tendermint v0.34.24/go.mod h1:rXVrl4OYzmIa1I91av3iLv2HS0fGSiucyW9J4aMTpKI= -github.com/tendermint/tm-db v0.6.7 h1:fE00Cbl0jayAoqlExN6oyQJ7fR/ZtoVOmvPJ//+shu8= -github.com/tendermint/tm-db v0.6.7/go.mod h1:byQDzFkZV1syXr/ReXS808NxA2xvyuuVgXOJ/088L6I= -github.com/tidwall/gjson v1.6.7/go.mod h1:zeFuBCIqD4sN/gmqBzZ4j7Jd6UcA2Fc56x7QFsv+8fI= -github.com/tidwall/match v1.0.3/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= -github.com/tidwall/pretty v1.0.2/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= -github.com/tidwall/sjson v1.1.4/go.mod h1:wXpKXu8CtDjKAZ+3DrKY5ROCorDFahq8l0tey/Lx1fg= -github.com/tinylib/msgp v1.1.5/go.mod h1:eQsjooMTnV42mHu917E26IogZ2930nFyBQdofk10Udg= +github.com/tidwall/btree v1.6.0 h1:LDZfKfQIBHGHWSwckhXI0RPSXzlo+KYdjK7FWSqOzzg= +github.com/tidwall/btree v1.6.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/ttacon/chalk v0.0.0-20160626202418-22c06c80ed31/go.mod h1:onvgF043R+lC5RZ8IT9rBXDaEDnpnw/Cl+HFiw+v/7Q= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= -github.com/tyler-smith/go-bip39 v1.0.1-0.20181017060643-dbb3b84ba2ef/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs= -github.com/tyler-smith/go-bip39 v1.0.2/go.mod h1:sJ5fKU0s6JVwZjjcUEX2zFOnvq0ASQ2K9Zr6cf67kNs= -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 v1.2.7 h1:qYhyWUUd6WbiM+C6JZAUkIJt/1WrjzNHY9+KCIjVqTo= +github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= -github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= -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/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY= +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/vmihailenco/msgpack/v5 v5.1.4/go.mod h1:C5gboKD0TJPqWDTVTtrQNfRbiBwHZGo8UTqP/9/XvLI= -github.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= -github.com/wsddn/go-ecdh v0.0.0-20161211032359-48726bab9208/go.mod h1:IotVbo4F+mw0EzQ08zFqg7pK3FebNXpaMsRy2RT+Ees= 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/ybbus/jsonrpc v2.1.2+incompatible/go.mod h1:XJrh1eMSzdIYFbM08flv0wp5G35eRniyeGut1z+LSiE= 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/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8= -github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= +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.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU= -go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= +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= @@ -815,6 +968,10 @@ 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= @@ -823,31 +980,26 @@ go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+ 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= -golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/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-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 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-20190909091759-094676da4a83/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-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/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-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20211108221036-ceb1ce70b4fa/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc= -golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= +golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= +golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= 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-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4= 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= @@ -856,10 +1008,11 @@ golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= -golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e h1:+WEEuIdZHnUeJJmEUjyYC2gfUMj69yZXw17EnHg/otA= -golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e/go.mod h1:Kr81I6Kryrl9sr8s2FK3vxD90NdsKWRuOIl2O4CvYbA= +golang.org/x/exp v0.0.0-20230321023759-10a507213a29 h1:ooxPy7fPvB4kwsA2h+iBNHkAbp/4JxTSwCmvdjEYmug= +golang.org/x/exp v0.0.0-20230321023759-10a507213a29/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= 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= @@ -870,23 +1023,23 @@ golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRu 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/mobile v0.0.0-20200801112145-973feb4309de/go.mod h1:skQtrUTUwhdJvXM/2KKJzY8pDgNr9I/FOMqDVRPBUS4= 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.1.1-0.20191209134235-331c550502dd/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 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.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA= -golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= golang.org/x/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-20181011144130-49bb7cea24b1/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= @@ -921,18 +1074,31 @@ golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200904194848-62affa334b73/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-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +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-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.6.0 h1:L4ZwwTvKW9gr0ZMS1yrHD9GZhIuVjOBBnaKH+SPQK0Q= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +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.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= 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= @@ -942,8 +1108,24 @@ golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ 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.5.0 h1:HuArIo48skDwlrvM3sEdHXElYslAMsf3KwRkkW4MC4s= +golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= 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= @@ -954,7 +1136,12 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ 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/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= @@ -984,7 +1171,6 @@ golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7w 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= @@ -1002,36 +1188,60 @@ golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7w 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-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200824131525-c12d262b63d8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200923182605-d9f96fdee20d/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-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/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-20210603081109-ebe580a85c40/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-20210927094055-39ccf1dd6fa6/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-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-20220114195835-da31bd327af9/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-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.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= -golang.org/x/sys v0.5.0/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 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= +golang.org/x/sys v0.6.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.5.0 h1:n2a8QNdAb0sZNpU9R1ALUXBbY+w51fCQDN+7EdxNBsY= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw= +golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= 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= @@ -1041,13 +1251,18 @@ 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.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 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/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +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-20181030221726-6c7e314b6563/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= @@ -1072,7 +1287,6 @@ golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtn 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-20200117012304-6edc0a871e69/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= @@ -1093,7 +1307,6 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc 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-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= 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= @@ -1101,13 +1314,22 @@ golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4f 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.3.0 h1:SrNbZl6ECOS1qFzgTdQfWXZM9XBkiA6tkFrH9YSTPHM= -golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k= +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.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= 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= @@ -1128,12 +1350,45 @@ google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz513 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.110.0 h1:l+rh0KYUooe9JGbGVx71tbFo4SMbMTXK3I3ia2QSEeU= +google.golang.org/api v0.110.0/go.mod h1:7FC4Vvx1Mooxh8C5HWjzZHcavuS2f6pmJpZx60ca7iI= +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= @@ -1157,7 +1412,6 @@ google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfG 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= @@ -1176,11 +1430,120 @@ google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6D 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-20230209215440-0dfe4f8abfcc h1:ijGwO+0vL2hJt5gaygqP2j6PfflOBrRot0IczKbmtio= -google.golang.org/genproto v0.0.0-20230209215440-0dfe4f8abfcc/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= -google.golang.org/grpc v1.33.2 h1:EQyQC3sa8M+p6Ulc8yy9SWSS2GVwyRc83gAbG8lrl4o= +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-20230216225411-c8e22ba71e44 h1:EfLuoKW5WfkgVdDy7dTK8qSbH37AX5mj/MFh+bGPz14= +google.golang.org/genproto v0.0.0-20230216225411-c8e22ba71e44/go.mod h1:8B0gmkoRebU8ukX6HP+4wrVQUY1+6PkQ44BSyIlflHA= +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.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= +google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= +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= @@ -1193,26 +1556,28 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj 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.28.2-0.20220831092852-f930b1dc76e8 h1:KR8+MyP7/qOlV+8Af01LtjL04bu7on42eVsxT4EyBQk= -google.golang.org/protobuf v1.28.2-0.20220831092852-f930b1dc76e8/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +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.29.1 h1:7QBf+IK2gx70Ap/hDsOmam3GE0v9HicjfEdAxE62UoM= +google.golang.org/protobuf v1.29.1/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 h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= 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/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 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/go.mod h1:5AcXVHNjg+BDxry382+8OKon8SEWiKktQR07RKPsv1c= -gopkg.in/olebedev/go-duktape.v3 v3.0.0-20200619000410-60c24ae608a6/go.mod h1:uAJfkITjFhyEEuUfm7bsmCZRbW5WRq8s9EY8HZ6hCns= 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/urfave/cli.v1 v1.20.0/go.mod h1:vuBzUtMdQeixQj8LVd+/98pzhxNGQoyuPBlsXHOQNO0= 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= @@ -1228,7 +1593,9 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C 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/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= +gotest.tools/v3 v3.4.0 h1:ZazjZUfuVeZGLAmlKKuyv3IKP5orXcwtOwDQH6YVr6o= +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= @@ -1238,8 +1605,12 @@ honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9 honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= nhooyr.io/websocket v1.8.6/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/proto/Dockerfile b/proto/Dockerfile new file mode 100644 index 0000000..f5e6f16 --- /dev/null +++ b/proto/Dockerfile @@ -0,0 +1,39 @@ +# 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.yaml b/proto/buf.gen.gogo.yaml new file mode 100644 index 0000000..4e8fb72 --- /dev/null +++ b/proto/buf.gen.gogo.yaml @@ -0,0 +1,8 @@ +version: v1 +plugins: + - name: gocosmos + out: .. + opt: plugins=grpc,Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/struct.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/wrappers.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types,Mcosmos/orm/v1alpha1/orm.proto=github.com/cosmos/cosmos-sdk/api/cosmos/orm/v1alpha1 + - name: grpc-gateway + out: .. + opt: logtostderr=true,allow_colon_final_segments=true diff --git a/proto/buf.lock b/proto/buf.lock index 3d4ba2f..9de2779 100644 --- a/proto/buf.lock +++ b/proto/buf.lock @@ -8,12 +8,12 @@ deps: - remote: buf.build owner: cosmos repository: cosmos-sdk - commit: 8cb30a2c4de74dc9bd8d260b1e75e176 + commit: 954f7b05f38440fc8250134b15adec47 - remote: buf.build owner: cosmos repository: gogo-proto - commit: 6652e3443c3b4504bb3bf82e73a7e409 + commit: 34d970b699f84aa382f3c29773a60836 - remote: buf.build owner: googleapis repository: googleapis - commit: 8d7204855ec14631a499bd7393ce1970 + commit: 75b4300737fb4efca0831636be94e517 diff --git a/proto/buf.md b/proto/buf.md index 3307dc3..d81eb01 100644 --- a/proto/buf.md +++ b/proto/buf.md @@ -1,3 +1,18 @@ # 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/buf.yaml b/proto/buf.yaml index 98cb5e1..cae10f0 100644 --- a/proto/buf.yaml +++ b/proto/buf.yaml @@ -1,14 +1,10 @@ -# Generated by "buf config migrate-v1beta1". Edit as necessary, and -# remove this comment when you're finished. -# -# This module represents the "proto" root found in -# the previous configuration. version: v1 name: buf.build/terpnetwork/terp-core deps: + - buf.build/cosmos/cosmos-sdk:v0.47.0 - buf.build/cosmos/cosmos-proto - - buf.build/cosmos/cosmos-sdk:8cb30a2c4de74dc9bd8d260b1e75e176 #v0.46.x - buf.build/cosmos/gogo-proto + - buf.build/googleapis/googleapis breaking: use: - FILE @@ -23,4 +19,5 @@ lint: - SERVICE_SUFFIX - PACKAGE_VERSION_SUFFIX - RPC_REQUEST_STANDARD_NAME - - PACKAGE_DIRECTORY_MATCH + ignore: + - tendermint \ No newline at end of file diff --git a/proto/cosmwasm/tokenfactory/v1beta1/authority_metadata.proto b/proto/cosmwasm/tokenfactory/v1beta1/authority_metadata.proto new file mode 100644 index 0000000..602c2be --- /dev/null +++ b/proto/cosmwasm/tokenfactory/v1beta1/authority_metadata.proto @@ -0,0 +1,17 @@ +syntax = "proto3"; +package cosmwasm.tokenfactory.v1beta1; + +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; + +option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; + +// 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. +message DenomAuthorityMetadata { + option (gogoproto.equal) = true; + + // Can be empty for no admin, or a valid terp 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/cosmwasm/tokenfactory/v1beta1/genesis.proto new file mode 100644 index 0000000..6b0e646 --- /dev/null +++ b/proto/cosmwasm/tokenfactory/v1beta1/genesis.proto @@ -0,0 +1,32 @@ +syntax = "proto3"; +package cosmwasm.tokenfactory.v1beta1; + +import "gogoproto/gogo.proto"; +import "cosmwasm/tokenfactory/v1beta1/authority_metadata.proto"; +import "cosmwasm/tokenfactory/v1beta1/params.proto"; + +option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; + +// GenesisState defines the tokenfactory module's genesis state. +message GenesisState { + // params defines the paramaters of the module. + Params params = 1 [ (gogoproto.nullable) = false ]; + + repeated GenesisDenom factory_denoms = 2 [ + (gogoproto.moretags) = "yaml:\"factory_denoms\"", + (gogoproto.nullable) = false + ]; +} + +// GenesisDenom defines a tokenfactory denom that is defined within genesis +// state. The structure contains DenomAuthorityMetadata which defines the +// denom's admin. +message GenesisDenom { + option (gogoproto.equal) = true; + + string denom = 1 [ (gogoproto.moretags) = "yaml:\"denom\"" ]; + DenomAuthorityMetadata authority_metadata = 2 [ + (gogoproto.moretags) = "yaml:\"authority_metadata\"", + (gogoproto.nullable) = false + ]; +} \ No newline at end of file diff --git a/proto/cosmwasm/tokenfactory/v1beta1/params.proto b/proto/cosmwasm/tokenfactory/v1beta1/params.proto new file mode 100644 index 0000000..4042174 --- /dev/null +++ b/proto/cosmwasm/tokenfactory/v1beta1/params.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; +package cosmwasm.tokenfactory.v1beta1; + +import "gogoproto/gogo.proto"; +import "cosmwasm/tokenfactory/v1beta1/authority_metadata.proto"; +import "cosmos_proto/cosmos.proto"; +import "cosmos/base/v1beta1/coin.proto"; + +option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; + +// Params defines the parameters for the tokenfactory module. +message Params { + repeated cosmos.base.v1beta1.Coin denom_creation_fee = 1 [ + (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", + (gogoproto.moretags) = "yaml:\"denom_creation_fee\"", + (gogoproto.nullable) = false + ]; +} \ No newline at end of file diff --git a/proto/cosmwasm/tokenfactory/v1beta1/query.proto b/proto/cosmwasm/tokenfactory/v1beta1/query.proto new file mode 100644 index 0000000..78d7185 --- /dev/null +++ b/proto/cosmwasm/tokenfactory/v1beta1/query.proto @@ -0,0 +1,71 @@ +syntax = "proto3"; +package cosmwasm.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"; + +option go_package = "github.com/terpnetwork/terp-core/x/tokenfactory/types"; + +// Query defines the gRPC querier service. +service Query { + // Params defines a gRPC query method that returns the tokenfactory module's + // parameters. + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/cosmwasm/tokenfactory/v1beta1/params"; + } + + // DenomAuthorityMetadata defines a gRPC query method for fetching + // DenomAuthorityMetadata for a particular denom. + rpc DenomAuthorityMetadata(QueryDenomAuthorityMetadataRequest) + returns (QueryDenomAuthorityMetadataResponse) { + option (google.api.http).get = + "/cosmwasm/tokenfactory/v1beta1/denoms/{denom}/authority_metadata"; + } + + // DenomsFromCreator defines a gRPC query method for fetching all + // denominations created by a specific admin/creator. + rpc DenomsFromCreator(QueryDenomsFromCreatorRequest) + returns (QueryDenomsFromCreatorResponse) { + option (google.api.http).get = + "/cosmwasm/tokenfactory/v1beta1/denoms_from_creator/{creator}"; + } +} + +// 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 ]; +} + +// QueryDenomAuthorityMetadataRequest defines the request structure for the +// DenomAuthorityMetadata gRPC query. +message QueryDenomAuthorityMetadataRequest { + string denom = 1 [ (gogoproto.moretags) = "yaml:\"denom\"" ]; +} + +// QueryDenomAuthorityMetadataResponse defines the response structure for the +// DenomAuthorityMetadata gRPC query. +message QueryDenomAuthorityMetadataResponse { + DenomAuthorityMetadata authority_metadata = 1 [ + (gogoproto.moretags) = "yaml:\"authority_metadata\"", + (gogoproto.nullable) = false + ]; +} + +// QueryDenomsFromCreatorRequest defines the request structure for the +// DenomsFromCreator gRPC query. +message QueryDenomsFromCreatorRequest { + string creator = 1 [ (gogoproto.moretags) = "yaml:\"creator\"" ]; +} + +// QueryDenomsFromCreatorRequest defines the response structure for the +// 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/cosmwasm/tokenfactory/v1beta1/tx.proto new file mode 100644 index 0000000..8744ecc --- /dev/null +++ b/proto/cosmwasm/tokenfactory/v1beta1/tx.proto @@ -0,0 +1,115 @@ +syntax = "proto3"; +package cosmwasm.tokenfactory.v1beta1; + +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; +import "cosmos/bank/v1beta1/bank.proto"; + +option go_package = "github.com/terpnetwork/terp-core/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); + + // ForceTransfer is deactivated for now because we need to think through edge + // cases rpc ForceTransfer(MsgForceTransfer) returns + // (MsgForceTransferResponse); +} + +// 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. +message MsgCreateDenom { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + // subdenom can be up to 44 "alphanumeric" characters long. + string subdenom = 2 [ (gogoproto.moretags) = "yaml:\"subdenom\"" ]; +} + +// MsgCreateDenomResponse is the return value of MsgCreateDenom +// It returns the full string of the newly created denom. +message MsgCreateDenomResponse { + string new_token_denom = 1 + [ (gogoproto.moretags) = "yaml:\"new_token_denom\"" ]; +} + +// 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 +message MsgMint { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + cosmos.base.v1beta1.Coin amount = 2 [ + (gogoproto.moretags) = "yaml:\"amount\"", + (gogoproto.nullable) = false + ]; +} +// 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 +// a token. For now, we only support burning from the sender account. +message MsgBurn { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + cosmos.base.v1beta1.Coin amount = 2 [ + (gogoproto.moretags) = "yaml:\"amount\"", + (gogoproto.nullable) = false + ]; +} +// 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 +// adminship of a denom to a new account +message MsgChangeAdmin { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + string denom = 2 [ (gogoproto.moretags) = "yaml:\"denom\"" ]; + string new_admin = 3 [ (gogoproto.moretags) = "yaml:\"new_admin\"" ]; +} + +// MsgChangeAdminResponse defines the response structure for an executed +// 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. +message MsgSetDenomMetadata { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + cosmos.bank.v1beta1.Metadata metadata = 2 [ + (gogoproto.moretags) = "yaml:\"metadata\"", + (gogoproto.nullable) = false + ]; +} + +// MsgSetDenomMetadataResponse defines the response structure for an executed +// MsgSetDenomMetadata message. +message MsgSetDenomMetadataResponse {} \ No newline at end of file diff --git a/proto/cosmwasm/wasm/v1/authz.proto b/proto/cosmwasm/wasm/v1/authz.proto index 80e050a..ce10a3d 100644 --- a/proto/cosmwasm/wasm/v1/authz.proto +++ b/proto/cosmwasm/wasm/v1/authz.proto @@ -5,94 +5,114 @@ 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: terpd 0.2.0 +// Since: wasmd 0.30 message ContractExecutionAuthorization { - option (cosmos_proto.implements_interface) = "Authorization"; + 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 ]; + repeated ContractGrant grants = 1 + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; } // ContractMigrationAuthorization defines authorization for wasm contract -// migration. Since: terpd 0.2.0 +// migration. Since: wasmd 0.30 message ContractMigrationAuthorization { - option (cosmos_proto.implements_interface) = "Authorization"; + 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 ]; + repeated ContractGrant grants = 1 + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; } // ContractGrant a granted permission for a single contract -// Since: terpd 0.2.0 +// 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) = "ContractAuthzLimitX" ]; + 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) = "ContractAuthzFilterX" ]; + [ (cosmos_proto.accepts_interface) = + "cosmwasm.wasm.v1.ContractAuthzFilterX" ]; } // MaxCallsLimit limited number of calls to the contract. No funds transferable. -// Since: terpd 0.2.0 +// Since: wasmd 0.30 message MaxCallsLimit { - option (cosmos_proto.implements_interface) = "ContractAuthzLimitX"; + 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: terpd 0.2.0 +// Since: wasmd 0.30 message MaxFundsLimit { - option (cosmos_proto.implements_interface) = "ContractAuthzLimitX"; + 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: terpd 0.2.0 +// Since: wasmd 0.30 message CombinedLimit { - option (cosmos_proto.implements_interface) = "ContractAuthzLimitX"; + 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: terpd 0.2.0 +// Since: wasmd 0.30 message AllowAllMessagesFilter { - option (cosmos_proto.implements_interface) = "ContractAuthzFilterX"; + 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: terpd 0.2.0 +// Since: wasmd 0.30 message AcceptedMessageKeysFilter { - option (cosmos_proto.implements_interface) = "ContractAuthzFilterX"; + 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; @@ -100,10 +120,12 @@ message AcceptedMessageKeysFilter { // AcceptedMessagesFilter accept only the specific raw contract messages to be // executed. -// Since: terpd 0.2.0 +// Since: wasmd 0.30 message AcceptedMessagesFilter { - option (cosmos_proto.implements_interface) = "ContractAuthzFilterX"; + 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 index b1bdd94..e0fc371 100644 --- a/proto/cosmwasm/wasm/v1/genesis.proto +++ b/proto/cosmwasm/wasm/v1/genesis.proto @@ -3,20 +3,27 @@ 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 ]; - repeated Code codes = 2 - [ (gogoproto.nullable) = false, (gogoproto.jsontag) = "codes,omitempty" ]; + 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" ]; } @@ -24,7 +31,8 @@ message GenesisState { // Code struct encompasses CodeInfo and CodeBytes message Code { uint64 code_id = 1 [ (gogoproto.customname) = "CodeID" ]; - CodeInfo code_info = 2 [ (gogoproto.nullable) = false ]; + CodeInfo code_info = 2 + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; bytes code_bytes = 3; // Pinned to wasmvm cache bool pinned = 4; @@ -33,10 +41,12 @@ message Code { // Contract struct encompasses ContractAddress, ContractInfo, and ContractState message Contract { string contract_address = 1; - ContractInfo contract_info = 2 [ (gogoproto.nullable) = false ]; - repeated Model contract_state = 3 [ (gogoproto.nullable) = false ]; + 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 ]; + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; } // Sequence key and value of an id generation counter diff --git a/proto/cosmwasm/wasm/v1/ibc.proto b/proto/cosmwasm/wasm/v1/ibc.proto index a1b00f2..196387b 100644 --- a/proto/cosmwasm/wasm/v1/ibc.proto +++ b/proto/cosmwasm/wasm/v1/ibc.proto @@ -25,7 +25,13 @@ message MsgIBCSend { 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 index f1c2f55..dfd5b4c 100644 --- a/proto/cosmwasm/wasm/v1/proposal.proto +++ b/proto/cosmwasm/wasm/v1/proposal.proto @@ -2,16 +2,26 @@ 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; -// StoreCodeProposal gov proposal content type to submit WASM code to the system +// 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 @@ -36,9 +46,15 @@ message StoreCodeProposal { bytes code_hash = 11; } -// InstantiateContractProposal gov proposal content type to instantiate a -// contract. +// 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 @@ -56,13 +72,20 @@ message InstantiateContractProposal { // 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" ]; } -// InstantiateContract2Proposal gov proposal content type to instantiate -// contract 2 +// 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 @@ -80,6 +103,7 @@ message InstantiateContract2Proposal { // 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. @@ -89,8 +113,15 @@ message InstantiateContract2Proposal { bool fix_msg = 10; } -// MigrateContractProposal gov proposal content type to migrate a contract. +// 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 @@ -105,8 +136,15 @@ message MigrateContractProposal { bytes msg = 6 [ (gogoproto.casttype) = "RawContractMessage" ]; } -// SudoContractProposal gov proposal content type to call sudo on a contract. +// 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 @@ -117,9 +155,15 @@ message SudoContractProposal { bytes msg = 4 [ (gogoproto.casttype) = "RawContractMessage" ]; } -// ExecuteContractProposal gov proposal content type to call execute on a -// contract. +// 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 @@ -137,8 +181,15 @@ message ExecuteContractProposal { ]; } -// UpdateAdminProposal gov proposal content type to set an admin for a contract. +// 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 @@ -149,9 +200,15 @@ message UpdateAdminProposal { string contract = 4; } -// ClearAdminProposal gov proposal content type to clear the admin of a -// contract. +// 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 @@ -160,9 +217,15 @@ message ClearAdminProposal { string contract = 3; } -// PinCodesProposal gov proposal content type to pin a set of code ids in the -// wasmvm cache. +// 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 @@ -174,9 +237,15 @@ message PinCodesProposal { ]; } -// UnpinCodesProposal gov proposal content type to unpin a set of code ids in -// the wasmvm cache. +// 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 @@ -194,12 +263,19 @@ 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 ]; + AccessConfig instantiate_permission = 2 + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; } -// UpdateInstantiateConfigProposal gov proposal content type to update -// instantiate config to a set of code ids. +// 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 @@ -207,12 +283,18 @@ message UpdateInstantiateConfigProposal { // AccessConfigUpdate contains the list of code ids and the access config // to be applied. repeated AccessConfigUpdate access_config_updates = 3 - [ (gogoproto.nullable) = false ]; + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; } -// StoreAndInstantiateContractProposal gov proposal content type to store -// and instantiate the contract. +// 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 @@ -234,6 +316,7 @@ message StoreAndInstantiateContractProposal { // 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 diff --git a/proto/cosmwasm/wasm/v1/query.proto b/proto/cosmwasm/wasm/v1/query.proto index bff876c..5a2039b 100644 --- a/proto/cosmwasm/wasm/v1/query.proto +++ b/proto/cosmwasm/wasm/v1/query.proto @@ -5,6 +5,7 @@ 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; @@ -88,6 +89,7 @@ message QueryContractInfoResponse { ContractInfo contract_info = 2 [ (gogoproto.embed) = true, (gogoproto.nullable) = false, + (amino.dont_omitempty) = true, (gogoproto.jsontag) = "" ]; } @@ -105,7 +107,7 @@ message QueryContractHistoryRequest { // Query/ContractHistory RPC method message QueryContractHistoryResponse { repeated ContractCodeHistoryEntry entries = 1 - [ (gogoproto.nullable) = false ]; + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; // pagination defines the pagination in the response. cosmos.base.query.v1beta1.PageResponse pagination = 2; } @@ -140,7 +142,8 @@ message QueryAllContractStateRequest { // QueryAllContractStateResponse is the response type for the // Query/AllContractState RPC method message QueryAllContractStateResponse { - repeated Model models = 1 [ (gogoproto.nullable) = false ]; + 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; } @@ -192,10 +195,11 @@ message CodeInfoResponse { string creator = 2; bytes data_hash = 3 [ (gogoproto.casttype) = - "github.com/tendermint/tendermint/libs/bytes.HexBytes" ]; + "github.com/cometbft/cometbft/libs/bytes.HexBytes" ]; // Used in v1beta1 reserved 4, 5; - AccessConfig instantiate_permission = 6 [ (gogoproto.nullable) = false ]; + AccessConfig instantiate_permission = 6 + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; } // QueryCodeResponse is the response type for the Query/Code RPC method @@ -214,7 +218,8 @@ message QueryCodesRequest { // QueryCodesResponse is the response type for the Query/Codes RPC method message QueryCodesResponse { - repeated CodeInfoResponse code_infos = 1 [ (gogoproto.nullable) = false ]; + 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; } @@ -229,8 +234,7 @@ message QueryPinnedCodesRequest { // QueryPinnedCodesResponse is the response type for the // Query/PinnedCodes RPC method message QueryPinnedCodesResponse { - repeated uint64 code_ids = 1 - [ (gogoproto.nullable) = false, (gogoproto.customname) = "CodeIDs" ]; + repeated uint64 code_ids = 1 [ (gogoproto.customname) = "CodeIDs" ]; // pagination defines the pagination in the response. cosmos.base.query.v1beta1.PageResponse pagination = 2; } @@ -241,7 +245,8 @@ 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 ]; + Params params = 1 + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ]; } // QueryContractsByCreatorRequest is the request type for the diff --git a/proto/cosmwasm/wasm/v1/tx.proto b/proto/cosmwasm/wasm/v1/tx.proto index 671c9b0..79a9930 100644 --- a/proto/cosmwasm/wasm/v1/tx.proto +++ b/proto/cosmwasm/wasm/v1/tx.proto @@ -2,8 +2,11 @@ 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; @@ -28,11 +31,43 @@ service Msg { 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 { - // Sender is the that actor that signed the messages + 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" ]; @@ -53,6 +88,9 @@ message MsgStoreCodeResponse { // 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 @@ -66,13 +104,25 @@ message MsgInstantiateContract { // 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 @@ -86,6 +136,7 @@ message MsgInstantiateContract2 { // 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. @@ -95,14 +146,6 @@ message MsgInstantiateContract2 { bool fix_msg = 8; } -// 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; -} - // MsgInstantiateContract2Response return instantiation result data message MsgInstantiateContract2Response { // Address is the bech32 address of the new contract instance. @@ -113,6 +156,9 @@ message MsgInstantiateContract2Response { // 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 @@ -122,6 +168,7 @@ message MsgExecuteContract { // 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" ]; } @@ -134,6 +181,9 @@ message MsgExecuteContractResponse { // 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 @@ -153,6 +203,9 @@ message MsgMigrateContractResponse { // 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 @@ -166,7 +219,10 @@ message MsgUpdateAdminResponse {} // MsgClearAdmin removes any admin stored for a smart contract message MsgClearAdmin { - // Sender is the that actor that signed the messages + 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; @@ -174,3 +230,162 @@ message MsgClearAdmin { // 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 index b136fe8..1161023 100644 --- a/proto/cosmwasm/wasm/v1/types.proto +++ b/proto/cosmwasm/wasm/v1/types.proto @@ -4,6 +4,7 @@ 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; @@ -53,6 +54,7 @@ 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 @@ -68,8 +70,8 @@ message CodeInfo { // Used in v1beta1 reserved 3, 4; // InstantiateConfig access control to apply on contract creation, optional - AccessConfig instantiate_config = 5 [ (gogoproto.nullable) = false ]; -} + AccessConfig instantiate_config = 5 + [ (gogoproto.nullable) = false, (amino.dont_omitempty) = true ];} // ContractInfo stores a WASM contract instance message ContractInfo { @@ -90,7 +92,8 @@ message ContractInfo { // Extension is an extension point to store custom metadata within the // persistence model. google.protobuf.Any extension = 7 - [ (cosmos_proto.accepts_interface) = "ContractInfoExtension" ]; + [ (cosmos_proto.accepts_interface) = + "cosmwasm.wasm.v1.ContractInfoExtension" ]; } // ContractCodeHistoryOperationType actions that caused a code change diff --git a/scripts/protocgen.sh b/scripts/protocgen.sh index bb26f69..b3c03de 100755 --- a/scripts/protocgen.sh +++ b/scripts/protocgen.sh @@ -27,4 +27,4 @@ cd .. # move proto files to the right places cp -r github.com/terpnetwork/terp-core/* ./ -rm -rf github.com +rm -rf github.com \ No newline at end of file diff --git a/startnode.sh b/startnode.sh deleted file mode 100644 index 9ecd614..0000000 --- a/startnode.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/sh - -# create users -rm -rf $HOME/.terp -terpd config chain-id johnson-1 -terpd config keyring-backend test -terpd config output json -yes | terpd keys add validator -yes | terpd keys add creator -yes | terpd keys add investor -yes | terpd keys add funder --pubkey "{\"@type\":\"/cosmos.crypto.secp256k1.PubKey\",\"key\":\"AtObiFVE4s+9+RX5SP8TN9r2mxpoaT4eGj9CJfK7VRzN\"}" -VALIDATOR=$(terpd keys show validator -a) -TENDER=$(terpd keys show creator -a) -FARMER=$(terpd keys show investor -a) -BREEDER=$(terpd keys show funder -a) - -# setup chain -terpd init stargaze --chain-id johnson-1 -# modify config for development -config="$HOME/.terp/config/config.toml" -if [ "$(uname)" = "Linux" ]; then - sed -i "s/cors_allowed_origins = \[\]/cors_allowed_origins = [\"*\"]/g" $config -else - sed -i '' "s/cors_allowed_origins = \[\]/cors_allowed_origins = [\"*\"]/g" $config -fi - - -terpd add-genesis-account $VALIDATOR 10000000000000000stake -terpd add-genesis-account $CREATOR 10000000000000000stake -terpd add-genesis-account $INVESTOR 10000000000000000stake -terpd add-genesis-account $FUNDER 10000000000000000stake -terpd gentx validator 10000000000stake --chain-id johnson-1 --keyring-backend test -terpd collect-gentxs -terpd validate-genesis -terpd start \ No newline at end of file diff --git a/tests/e2e/gov_test.go b/tests/e2e/gov_test.go new file mode 100644 index 0000000..4054637 --- /dev/null +++ b/tests/e2e/gov_test.go @@ -0,0 +1,135 @@ +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 index 5eae037..0fb4882 100644 --- a/tests/e2e/grants_test.go +++ b/tests/e2e/grants_test.go @@ -5,6 +5,7 @@ import ( "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" @@ -13,6 +14,7 @@ import ( "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" ) @@ -26,9 +28,9 @@ func TestGrants(t *testing.T) { // - balance A reduced (on success) // - balance B not touched - chain := ibctesting.NewCoordinator(t, 1).GetChain(ibctesting.GetChainID(0)) - codeID := chain.StoreCodeFile("../../x/wasm/keeper/testdata/reflect_1_1.wasm").CodeID - contractAddr := chain.InstantiateContract(codeID, []byte(`{}`)) + coord := ibctesting.NewCoordinator(t, 1) + chain := coord.GetChain(ibctesting.GetChainID(1)) + contractAddr := e2e.InstantiateReflectContract(t, chain) require.NotEmpty(t, contractAddr) granterAddr := chain.SenderAccount.GetAddress() @@ -48,7 +50,7 @@ func TestGrants(t *testing.T) { filter types.ContractAuthzFilterX transferAmount sdk.Coin senderKey cryptotypes.PrivKey - expErr *sdkerrors.Error + expErr *errorsmod.Error }{ "in limits and filter": { limit: types.NewMaxFundsLimit(myAmount), @@ -75,7 +77,7 @@ func TestGrants(t *testing.T) { filter: types.NewAllowAllMessagesFilter(), senderKey: otherPrivKey, transferAmount: myAmount, - expErr: sdkerrors.ErrUnauthorized, + expErr: authz.ErrNoAuthorizationFound, }, } for name, spec := range specs { @@ -84,7 +86,8 @@ func TestGrants(t *testing.T) { grant, err := types.NewContractGrant(contractAddr, spec.limit, spec.filter) require.NoError(t, err) authorization := types.NewContractExecutionAuthorization(*grant) - grantMsg, err := authz.NewMsgGrant(granterAddr, granteeAddr, authorization, time.Now().Add(time.Hour)) + 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) @@ -103,7 +106,7 @@ func TestGrants(t *testing.T) { // then if spec.expErr != nil { - require.ErrorIs(t, gotErr, spec.expErr) + 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 diff --git a/tests/e2e/group_test.go b/tests/e2e/group_test.go new file mode 100644 index 0000000..1b2fc7e --- /dev/null +++ b/tests/e2e/group_test.go @@ -0,0 +1,71 @@ +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 index 69e6ea4..685880f 100644 --- a/tests/e2e/ibc_fees_test.go +++ b/tests/e2e/ibc_fees_test.go @@ -9,11 +9,11 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" - ibcfee "github.com/cosmos/ibc-go/v4/modules/apps/29-fee/types" - ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v4/testing" + 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" @@ -30,8 +30,8 @@ func TestIBCFeesTransfer(t *testing.T) { // then the relayer's payee is receiving the fee(s) on success marshaler := app.MakeEncodingConfig().Marshaler coord := wasmibctesting.NewCoordinator(t, 2) - chainA := coord.GetChain(ibctesting.GetChainID(0)) - chainB := coord.GetChain(ibctesting.GetChainID(1)) + 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()) @@ -61,7 +61,7 @@ func TestIBCFeesTransfer(t *testing.T) { // 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())) + 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) @@ -86,7 +86,7 @@ func TestIBCFeesTransfer(t *testing.T) { 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())) + 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) @@ -113,8 +113,8 @@ func TestIBCFeesWasm(t *testing.T) { // then the relayer's payee is receiving the fee(s) on success marshaler := app.MakeEncodingConfig().Marshaler coord := wasmibctesting.NewCoordinator(t, 2) - chainA := coord.GetChain(ibctesting.GetChainID(0)) - chainB := coord.GetChain(ibctesting.GetChainID(1)) + 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()) @@ -192,7 +192,7 @@ func TestIBCFeesWasm(t *testing.T) { 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())) + 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) diff --git a/tests/e2e/ica_test.go b/tests/e2e/ica_test.go index 7259e5d..c77605b 100644 --- a/tests/e2e/ica_test.go +++ b/tests/e2e/ica_test.go @@ -3,15 +3,17 @@ 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" - hosttypes "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/host/types" - icatypes "github.com/cosmos/ibc-go/v4/modules/apps/27-interchain-accounts/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v4/testing" - intertxtypes "github.com/cosmos/interchain-accounts/x/inter-tx/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" @@ -26,18 +28,19 @@ func TestICA(t *testing.T) { // 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(0)) + 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(1)) + controllerChain := coord.GetChain(ibctesting.GetChainID(2)) path := wasmibctesting.NewPath(controllerChain, hostChain) coord.SetupConnections(path) ownerAddr := sdk.AccAddress(controllerChain.SenderPrivKey.PubKey().Address()) - msg := intertxtypes.NewMsgRegisterAccount(ownerAddr.String(), path.EndpointA.ConnectionID, "") + 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 @@ -48,28 +51,35 @@ func TestICA(t *testing.T) { Order: channeltypes.ORDERED, } path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{ - PortID: icatypes.PortID, + PortID: icatypes.HostPortID, Version: icatypes.Version, Order: channeltypes.ORDERED, } coord.CreateChannels(path) // assert ICA exists on controller - icaRsp, err := controllerChain.App.InterTxKeeper.InterchainAccount(sdk.WrapSDKContext(controllerChain.GetContext()), &intertxtypes.QueryInterchainAccountRequest{ + 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.InterchainAccountAddress) + 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)) - msg2, err := intertxtypes.NewMsgSubmitTx(payloadMsg, path.EndpointA.ConnectionID, ownerAddr.String()) + rawPayloadData, err := icatypes.SerializeCosmosTx(controllerChain.Codec, []proto.Message{payloadMsg}) require.NoError(t, err) - res, err = controllerChain.SendMsgs(msg2) + 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)) diff --git a/tests/e2e/reflect_helper.go b/tests/e2e/reflect_helper.go new file mode 100644 index 0000000..0eccc8b --- /dev/null +++ b/tests/e2e/reflect_helper.go @@ -0,0 +1,72 @@ +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 { + t.Helper() + 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 { + t.Helper() + 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 { + t.Helper() + 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) { + t.Helper() + 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/testutil/keeper/terp.go b/testutil/keeper/terp.go deleted file mode 100644 index d99a609..0000000 --- a/testutil/keeper/terp.go +++ /dev/null @@ -1,52 +0,0 @@ -package keeper - -import ( - "testing" - - "github.com/cosmos/cosmos-sdk/codec" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - typesparams "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - tmdb "github.com/tendermint/tm-db" - "github.com/terpnetwork/terp-core/x/terp/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func TerpKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { - storeKey := sdk.NewKVStoreKey(types.StoreKey) - memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) - - db := tmdb.NewMemDB() - stateStore := store.NewCommitMultiStore(db) - stateStore.MountStoreWithDB(storeKey, sdk.StoreTypeIAVL, db) - stateStore.MountStoreWithDB(memStoreKey, sdk.StoreTypeMemory, nil) - require.NoError(t, stateStore.LoadLatestVersion()) - - registry := codectypes.NewInterfaceRegistry() - cdc := codec.NewProtoCodec(registry) - - paramsSubspace := typesparams.NewSubspace(cdc, - types.Amino, - storeKey, - memStoreKey, - "BcnaParams", - ) - k := keeper.NewKeeper( - cdc, - storeKey, - memStoreKey, - paramsSubspace, - ) - - ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) - - // Initialize params - k.SetParams(ctx, types.DefaultParams()) - - return k, ctx -} diff --git a/testutil/network/network.go b/testutil/network/network.go deleted file mode 100644 index ed054ca..0000000 --- a/testutil/network/network.go +++ /dev/null @@ -1,78 +0,0 @@ -package network - -import ( - "fmt" - "testing" - "time" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/crypto/hd" - "github.com/cosmos/cosmos-sdk/crypto/keyring" - servertypes "github.com/cosmos/cosmos-sdk/server/types" - "github.com/cosmos/cosmos-sdk/simapp" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - "github.com/cosmos/cosmos-sdk/testutil/network" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - tmrand "github.com/tendermint/tendermint/libs/rand" - tmdb "github.com/tendermint/tm-db" - - "github.com/terpnetwork/terp-core/app" -) - -type ( - Network = network.Network - Config = network.Config -) - -// New creates instance with fully configured cosmos network. -// Accepts optional config, that will be used in place of the DefaultConfig() if provided. -func New(t *testing.T, configs ...network.Config) *network.Network { - if len(configs) > 1 { - panic("at most one config should be provided") - } - var cfg network.Config - if len(configs) == 0 { - cfg = DefaultConfig() - } else { - cfg = configs[0] - } - net := network.New(t, cfg) - t.Cleanup(net.Cleanup) - return net -} - -// DefaultConfig will initialize config for the network with custom application, -// genesis and single validator. All other parameters are inherited from cosmos-sdk/testutil/network.DefaultConfig -func DefaultConfig() network.Config { - encoding := app.MakeEncodingConfig() - return network.Config{ - Codec: encoding.Marshaler, - TxConfig: encoding.TxConfig, - LegacyAmino: encoding.Amino, - InterfaceRegistry: encoding.InterfaceRegistry, - AccountRetriever: authtypes.AccountRetriever{}, - AppConstructor: func(val network.Validator) servertypes.Application { - return app.New( - val.Ctx.Logger, tmdb.NewMemDB(), nil, true, map[int64]bool{}, val.Ctx.Config.RootDir, 0, - encoding, - simapp.EmptyAppOptions{}, - baseapp.SetPruning(storetypes.NewPruningOptionsFromString(val.AppConfig.Pruning)), - baseapp.SetMinGasPrices(val.AppConfig.MinGasPrices), - ) - }, - GenesisState: app.ModuleBasics.DefaultGenesis(encoding.Marshaler), - TimeoutCommit: 2 * time.Second, - ChainID: "chain-" + tmrand.NewRand().Str(6), - NumValidators: 1, - BondDenom: sdk.DefaultBondDenom, - MinGasPrices: fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), - AccountTokens: sdk.TokensFromConsensusPower(1000, sdk.DefaultPowerReduction), - StakingTokens: sdk.TokensFromConsensusPower(500, sdk.DefaultPowerReduction), - BondedTokens: sdk.TokensFromConsensusPower(100, sdk.DefaultPowerReduction), - PruningStrategy: storetypes.PruningOptionNothing, - CleanupDir: true, - SigningAlgo: string(hd.Secp256k1Type), - KeyringOptions: []keyring.Option{}, - } -} diff --git a/testutil/nullify/nullify.go b/testutil/nullify/nullify.go deleted file mode 100644 index 3b968c0..0000000 --- a/testutil/nullify/nullify.go +++ /dev/null @@ -1,57 +0,0 @@ -// 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/testutil/sample/sample.go b/testutil/sample/sample.go deleted file mode 100644 index 98f2153..0000000 --- a/testutil/sample/sample.go +++ /dev/null @@ -1,13 +0,0 @@ -package sample - -import ( - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - sdk "github.com/cosmos/cosmos-sdk/types" -) - -// AccAddress returns a sample account address -func AccAddress() string { - pk := ed25519.GenPrivKey().PubKey() - addr := pk.Address() - return sdk.AccAddress(addr).String() -} diff --git a/x/terp/client/cli/query.go b/x/terp/client/cli/query.go deleted file mode 100644 index 3534976..0000000 --- a/x/terp/client/cli/query.go +++ /dev/null @@ -1,35 +0,0 @@ -package cli - -import ( - "fmt" - // "strings" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - // "github.com/cosmos/cosmos-sdk/client/flags" - // sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/terpnetwork/terp-core/x/terp/types" -) - -// GetQueryCmd returns the cli query commands for this module -func GetQueryCmd(queryRoute string) *cobra.Command { - // Group terp queries under a subcommand - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand(CmdQueryParams()) - cmd.AddCommand(CmdListTerpid()) - cmd.AddCommand(CmdShowTerpid()) - cmd.AddCommand(CmdListSupplychain()) - cmd.AddCommand(CmdShowSupplychain()) - // this line is used by starport scaffolding # 1 - - return cmd -} diff --git a/x/terp/client/cli/query_params.go b/x/terp/client/cli/query_params.go deleted file mode 100644 index ac43fff..0000000 --- a/x/terp/client/cli/query_params.go +++ /dev/null @@ -1,34 +0,0 @@ -package cli - -import ( - "context" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/spf13/cobra" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func CmdQueryParams() *cobra.Command { - cmd := &cobra.Command{ - Use: "params", - Short: "shows the parameters of the module", - Args: cobra.NoArgs, - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - queryClient := types.NewQueryClient(clientCtx) - - res, err := queryClient.Params(context.Background(), &types.QueryParamsRequest{}) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} diff --git a/x/terp/client/cli/query_supplychain.go b/x/terp/client/cli/query_supplychain.go deleted file mode 100644 index 4532fa1..0000000 --- a/x/terp/client/cli/query_supplychain.go +++ /dev/null @@ -1,77 +0,0 @@ -package cli - -import ( - "context" - "strconv" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/spf13/cobra" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func CmdListSupplychain() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-supplychain", - Short: "list all supplychain", - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - params := &types.QueryAllSupplychainRequest{ - Pagination: pageReq, - } - - res, err := queryClient.SupplychainAll(context.Background(), params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, cmd.Use) - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdShowSupplychain() *cobra.Command { - cmd := &cobra.Command{ - Use: "show-supplychain [id]", - Short: "shows a supplychain", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - queryClient := types.NewQueryClient(clientCtx) - - id, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - params := &types.QueryGetSupplychainRequest{ - Id: id, - } - - res, err := queryClient.Supplychain(context.Background(), params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} diff --git a/x/terp/client/cli/query_supplychain_test.go b/x/terp/client/cli/query_supplychain_test.go deleted file mode 100644 index 6c75adc..0000000 --- a/x/terp/client/cli/query_supplychain_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package cli_test - -import ( - "fmt" - "testing" - - "github.com/cosmos/cosmos-sdk/client/flags" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - "github.com/stretchr/testify/require" - tmcli "github.com/tendermint/tendermint/libs/cli" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/terpnetwork/terp-core/testutil/network" - "github.com/terpnetwork/terp-core/testutil/nullify" - "github.com/terpnetwork/terp-core/x/terp/client/cli" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func networkWithSupplychainObjects(t *testing.T, n int) (*network.Network, []types.Supplychain) { - t.Helper() - cfg := network.DefaultConfig() - state := types.GenesisState{} - require.NoError(t, cfg.Codec.UnmarshalJSON(cfg.GenesisState[types.ModuleName], &state)) - - for i := 0; i < n; i++ { - supplychain := types.Supplychain{ - Id: uint64(i), - } - nullify.Fill(&supplychain) - state.SupplychainList = append(state.SupplychainList, supplychain) - } - buf, err := cfg.Codec.MarshalJSON(&state) - require.NoError(t, err) - cfg.GenesisState[types.ModuleName] = buf - return network.New(t, cfg), state.SupplychainList -} - -func TestShowSupplychain(t *testing.T) { - net, objs := networkWithSupplychainObjects(t, 2) - - ctx := net.Validators[0].ClientCtx - common := []string{ - fmt.Sprintf("--%s=json", tmcli.OutputFlag), - } - for _, tc := range []struct { - desc string - id string - args []string - err error - obj types.Supplychain - }{ - { - desc: "found", - id: fmt.Sprintf("%d", objs[0].Id), - args: common, - obj: objs[0], - }, - { - desc: "not found", - id: "not_found", - args: common, - err: status.Error(codes.NotFound, "not found"), - }, - } { - tc := tc - t.Run(tc.desc, func(t *testing.T) { - args := []string{tc.id} - args = append(args, tc.args...) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdShowSupplychain(), args) - if tc.err != nil { - stat, ok := status.FromError(tc.err) - require.True(t, ok) - require.ErrorIs(t, stat.Err(), tc.err) - } else { - require.NoError(t, err) - var resp types.QueryGetSupplychainResponse - require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.NotNil(t, resp.Supplychain) - require.Equal(t, - nullify.Fill(&tc.obj), - nullify.Fill(&resp.Supplychain), - ) - } - }) - } -} - -func TestListSupplychain(t *testing.T) { - net, objs := networkWithSupplychainObjects(t, 5) - - ctx := net.Validators[0].ClientCtx - request := func(next []byte, offset, limit uint64, total bool) []string { - args := []string{ - fmt.Sprintf("--%s=json", tmcli.OutputFlag), - } - if next == nil { - args = append(args, fmt.Sprintf("--%s=%d", flags.FlagOffset, offset)) - } else { - args = append(args, fmt.Sprintf("--%s=%s", flags.FlagPageKey, next)) - } - args = append(args, fmt.Sprintf("--%s=%d", flags.FlagLimit, limit)) - if total { - args = append(args, fmt.Sprintf("--%s", flags.FlagCountTotal)) - } - return args - } - t.Run("ByOffset", func(t *testing.T) { - step := 2 - for i := 0; i < len(objs); i += step { - args := request(nil, uint64(i), uint64(step), false) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListSupplychain(), args) - require.NoError(t, err) - var resp types.QueryAllSupplychainResponse - require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.LessOrEqual(t, len(resp.Supplychain), step) - require.Subset(t, - nullify.Fill(objs), - nullify.Fill(resp.Supplychain), - ) - } - }) - t.Run("ByKey", func(t *testing.T) { - step := 2 - var next []byte - for i := 0; i < len(objs); i += step { - args := request(next, 0, uint64(step), false) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListSupplychain(), args) - require.NoError(t, err) - var resp types.QueryAllSupplychainResponse - require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.LessOrEqual(t, len(resp.Supplychain), step) - require.Subset(t, - nullify.Fill(objs), - nullify.Fill(resp.Supplychain), - ) - next = resp.Pagination.NextKey - } - }) - t.Run("Total", func(t *testing.T) { - args := request(nil, 0, uint64(len(objs)), true) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListSupplychain(), args) - require.NoError(t, err) - var resp types.QueryAllSupplychainResponse - require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.NoError(t, err) - require.Equal(t, len(objs), int(resp.Pagination.Total)) - require.ElementsMatch(t, - nullify.Fill(objs), - nullify.Fill(resp.Supplychain), - ) - }) -} diff --git a/x/terp/client/cli/query_terpid.go b/x/terp/client/cli/query_terpid.go deleted file mode 100644 index dcc2ed1..0000000 --- a/x/terp/client/cli/query_terpid.go +++ /dev/null @@ -1,77 +0,0 @@ -package cli - -import ( - "context" - "strconv" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/spf13/cobra" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func CmdListTerpid() *cobra.Command { - cmd := &cobra.Command{ - Use: "list-terpid", - Short: "list all terpid", - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - pageReq, err := client.ReadPageRequest(cmd.Flags()) - if err != nil { - return err - } - - queryClient := types.NewQueryClient(clientCtx) - - params := &types.QueryAllTerpidRequest{ - Pagination: pageReq, - } - - res, err := queryClient.TerpidAll(context.Background(), params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddPaginationFlagsToCmd(cmd, cmd.Use) - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} - -func CmdShowTerpid() *cobra.Command { - cmd := &cobra.Command{ - Use: "show-terpid [id]", - Short: "shows a terpid", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx := client.GetClientContextFromCmd(cmd) - - queryClient := types.NewQueryClient(clientCtx) - - id, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - params := &types.QueryGetTerpidRequest{ - Id: id, - } - - res, err := queryClient.Terpid(context.Background(), params) - if err != nil { - return err - } - - return clientCtx.PrintProto(res) - }, - } - - flags.AddQueryFlagsToCmd(cmd) - - return cmd -} diff --git a/x/terp/client/cli/query_terpid_test.go b/x/terp/client/cli/query_terpid_test.go deleted file mode 100644 index b786ebb..0000000 --- a/x/terp/client/cli/query_terpid_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package cli_test - -import ( - "fmt" - "testing" - - "github.com/cosmos/cosmos-sdk/client/flags" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - "github.com/stretchr/testify/require" - tmcli "github.com/tendermint/tendermint/libs/cli" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - "github.com/terpnetwork/terp-core/testutil/network" - "github.com/terpnetwork/terp-core/testutil/nullify" - "github.com/terpnetwork/terp-core/x/terp/client/cli" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func networkWithTerpidObjects(t *testing.T, n int) (*network.Network, []types.Terpid) { - t.Helper() - cfg := network.DefaultConfig() - state := types.GenesisState{} - require.NoError(t, cfg.Codec.UnmarshalJSON(cfg.GenesisState[types.ModuleName], &state)) - - for i := 0; i < n; i++ { - terpid := types.Terpid{ - Id: uint64(i), - } - nullify.Fill(&terpid) - state.TerpidList = append(state.TerpidList, terpid) - } - buf, err := cfg.Codec.MarshalJSON(&state) - require.NoError(t, err) - cfg.GenesisState[types.ModuleName] = buf - return network.New(t, cfg), state.TerpidList -} - -func TestShowTerpid(t *testing.T) { - net, objs := networkWithTerpidObjects(t, 2) - - ctx := net.Validators[0].ClientCtx - common := []string{ - fmt.Sprintf("--%s=json", tmcli.OutputFlag), - } - for _, tc := range []struct { - desc string - id string - args []string - err error - obj types.Terpid - }{ - { - desc: "found", - id: fmt.Sprintf("%d", objs[0].Id), - args: common, - obj: objs[0], - }, - { - desc: "not found", - id: "not_found", - args: common, - err: status.Error(codes.NotFound, "not found"), - }, - } { - tc := tc - t.Run(tc.desc, func(t *testing.T) { - args := []string{tc.id} - args = append(args, tc.args...) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdShowTerpid(), args) - if tc.err != nil { - stat, ok := status.FromError(tc.err) - require.True(t, ok) - require.ErrorIs(t, stat.Err(), tc.err) - } else { - require.NoError(t, err) - var resp types.QueryGetTerpidResponse - require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.NotNil(t, resp.Terpid) - require.Equal(t, - nullify.Fill(&tc.obj), - nullify.Fill(&resp.Terpid), - ) - } - }) - } -} - -func TestListTerpid(t *testing.T) { - net, objs := networkWithTerpidObjects(t, 5) - - ctx := net.Validators[0].ClientCtx - request := func(next []byte, offset, limit uint64, total bool) []string { - args := []string{ - fmt.Sprintf("--%s=json", tmcli.OutputFlag), - } - if next == nil { - args = append(args, fmt.Sprintf("--%s=%d", flags.FlagOffset, offset)) - } else { - args = append(args, fmt.Sprintf("--%s=%s", flags.FlagPageKey, next)) - } - args = append(args, fmt.Sprintf("--%s=%d", flags.FlagLimit, limit)) - if total { - args = append(args, fmt.Sprintf("--%s", flags.FlagCountTotal)) - } - return args - } - t.Run("ByOffset", func(t *testing.T) { - step := 2 - for i := 0; i < len(objs); i += step { - args := request(nil, uint64(i), uint64(step), false) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListTerpid(), args) - require.NoError(t, err) - var resp types.QueryAllTerpidResponse - require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.LessOrEqual(t, len(resp.Terpid), step) - require.Subset(t, - nullify.Fill(objs), - nullify.Fill(resp.Terpid), - ) - } - }) - t.Run("ByKey", func(t *testing.T) { - step := 2 - var next []byte - for i := 0; i < len(objs); i += step { - args := request(next, 0, uint64(step), false) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListTerpid(), args) - require.NoError(t, err) - var resp types.QueryAllTerpidResponse - require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.LessOrEqual(t, len(resp.Terpid), step) - require.Subset(t, - nullify.Fill(objs), - nullify.Fill(resp.Terpid), - ) - next = resp.Pagination.NextKey - } - }) - t.Run("Total", func(t *testing.T) { - args := request(nil, 0, uint64(len(objs)), true) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdListTerpid(), args) - require.NoError(t, err) - var resp types.QueryAllTerpidResponse - require.NoError(t, net.Config.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.NoError(t, err) - require.Equal(t, len(objs), int(resp.Pagination.Total)) - require.ElementsMatch(t, - nullify.Fill(objs), - nullify.Fill(resp.Terpid), - ) - }) -} diff --git a/x/terp/client/cli/tx.go b/x/terp/client/cli/tx.go deleted file mode 100644 index 78e5b83..0000000 --- a/x/terp/client/cli/tx.go +++ /dev/null @@ -1,40 +0,0 @@ -package cli - -import ( - "fmt" - "time" - - "github.com/spf13/cobra" - - "github.com/cosmos/cosmos-sdk/client" - // "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -var DefaultRelativePacketTimeoutTimestamp = uint64((time.Duration(10) * time.Minute).Nanoseconds()) - -const ( - flagPacketTimeoutTimestamp = "packet-timeout-timestamp" //nolint:unused,deadcode,varcheck // remove this if it does nothing - listSeparator = "," //nolint:unused,deadcode,varcheck // remove this if it does nothing -) - -// GetTxCmd returns the transaction commands for this module -func GetTxCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: types.ModuleName, - Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), - DisableFlagParsing: true, - SuggestionsMinimumDistance: 2, - RunE: client.ValidateCmd, - } - - cmd.AddCommand(CmdCreateTerpid()) - cmd.AddCommand(CmdUpdateTerpid()) - cmd.AddCommand(CmdDeleteTerpid()) - cmd.AddCommand(CmdCreateSupplychain()) - cmd.AddCommand(CmdUpdateSupplychain()) - cmd.AddCommand(CmdDeleteSupplychain()) - // this line is used by starport scaffolding # 1 - - return cmd -} diff --git a/x/terp/client/cli/tx_supplychain.go b/x/terp/client/cli/tx_supplychain.go deleted file mode 100644 index 74b66dd..0000000 --- a/x/terp/client/cli/tx_supplychain.go +++ /dev/null @@ -1,106 +0,0 @@ -package cli - -import ( - "strconv" - - "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/terp/types" -) - -func CmdCreateSupplychain() *cobra.Command { - cmd := &cobra.Command{ - Use: "create-supplychain [product] [info] [supplyinfo] [supplyextra]", - Short: "Create a new supplychain", - Args: cobra.ExactArgs(4), - RunE: func(cmd *cobra.Command, args []string) (err error) { - argProduct := args[0] - argInfo := args[1] - argSupplyinfo := args[2] - argSupplyextra := args[3] - - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := types.NewMsgCreateSupplychain(clientCtx.GetFromAddress().String(), argProduct, argInfo, argSupplyinfo, argSupplyextra) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func CmdUpdateSupplychain() *cobra.Command { - cmd := &cobra.Command{ - Use: "update-supplychain [id] [product] [info] [supplyinfo] [supplyextra]", - Short: "Update a supplychain", - Args: cobra.ExactArgs(5), - RunE: func(cmd *cobra.Command, args []string) (err error) { - id, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - argProduct := args[1] - - argInfo := args[2] - - argSupplyinfo := args[3] - - argSupplyextra := args[4] - - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := types.NewMsgUpdateSupplychain(clientCtx.GetFromAddress().String(), id, argProduct, argInfo, argSupplyinfo, argSupplyextra) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func CmdDeleteSupplychain() *cobra.Command { - cmd := &cobra.Command{ - Use: "delete-supplychain [id]", - Short: "Delete a supplychain by id", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - id, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := types.NewMsgDeleteSupplychain(clientCtx.GetFromAddress().String(), id) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} diff --git a/x/terp/client/cli/tx_supplychain_test.go b/x/terp/client/cli/tx_supplychain_test.go deleted file mode 100644 index 5feb9e7..0000000 --- a/x/terp/client/cli/tx_supplychain_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package cli_test - -import ( - "fmt" - "testing" - - "github.com/cosmos/cosmos-sdk/client/flags" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/testutil/network" - "github.com/terpnetwork/terp-core/x/terp/client/cli" -) - -func TestCreateSupplychain(t *testing.T) { - net := network.New(t) - val := net.Validators[0] - ctx := val.ClientCtx - - fields := []string{"xyz", "xyz", "xyz", "xyz"} - for _, tc := range []struct { - desc string - args []string - err error - code uint32 - }{ - { - desc: "valid", - args: []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(net.Config.BondDenom, sdk.NewInt(10))).String()), - }, - }, - } { - t.Run(tc.desc, func(t *testing.T) { - args := []string{} - args = append(args, fields...) - args = append(args, tc.args...) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdCreateSupplychain(), args) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - var resp sdk.TxResponse - require.NoError(t, ctx.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.Equal(t, tc.code, resp.Code) - } - }) - } -} - -func TestUpdateSupplychain(t *testing.T) { - net := network.New(t) - - val := net.Validators[0] - ctx := val.ClientCtx - - fields := []string{"xyz", "xyz", "xyz", "xyz"} - common := []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(net.Config.BondDenom, sdk.NewInt(10))).String()), - } - args := []string{} - args = append(args, fields...) - args = append(args, common...) - _, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdCreateSupplychain(), args) - require.NoError(t, err) - - for _, tc := range []struct { - desc string - id string - args []string - code uint32 - err error - }{ - { - desc: "valid", - id: "0", - args: common, - }, - { - desc: "key not found", - id: "1", - args: common, - code: sdkerrors.ErrKeyNotFound.ABCICode(), - }, - } { - t.Run(tc.desc, func(t *testing.T) { - args := []string{tc.id} - args = append(args, fields...) - args = append(args, tc.args...) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdUpdateSupplychain(), args) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - var resp sdk.TxResponse - require.NoError(t, ctx.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.Equal(t, tc.code, resp.Code) - } - }) - } -} - -func TestDeleteSupplychain(t *testing.T) { - net := network.New(t) - - val := net.Validators[0] - ctx := val.ClientCtx - - fields := []string{"xyz", "xyz", "xyz", "xyz"} - common := []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(net.Config.BondDenom, sdk.NewInt(10))).String()), - } - args := []string{} - args = append(args, fields...) - args = append(args, common...) - _, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdCreateSupplychain(), args) - require.NoError(t, err) - - for _, tc := range []struct { - desc string - id string - args []string - code uint32 - err error - }{ - { - desc: "valid", - id: "0", - args: common, - }, - { - desc: "key not found", - id: "1", - args: common, - code: sdkerrors.ErrKeyNotFound.ABCICode(), - }, - } { - t.Run(tc.desc, func(t *testing.T) { - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdDeleteSupplychain(), append([]string{tc.id}, tc.args...)) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - var resp sdk.TxResponse - require.NoError(t, ctx.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.Equal(t, tc.code, resp.Code) - } - }) - } -} diff --git a/x/terp/client/cli/tx_terpid.go b/x/terp/client/cli/tx_terpid.go deleted file mode 100644 index 5a7bdd7..0000000 --- a/x/terp/client/cli/tx_terpid.go +++ /dev/null @@ -1,100 +0,0 @@ -package cli - -import ( - "strconv" - - "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/terp/types" -) - -func CmdCreateTerpid() *cobra.Command { - cmd := &cobra.Command{ - Use: "create-terpid [terpid] [address]", - Short: "Create a new terpid", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) (err error) { - argTerpid := args[0] - argAddress := args[1] - - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := types.NewMsgCreateTerpid(clientCtx.GetFromAddress().String(), argTerpid, argAddress) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func CmdUpdateTerpid() *cobra.Command { - cmd := &cobra.Command{ - Use: "update-terpid [id] [terpid] [address]", - Short: "Update a terpid", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) (err error) { - id, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - argTerpid := args[1] - - argAddress := args[2] - - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := types.NewMsgUpdateTerpid(clientCtx.GetFromAddress().String(), id, argTerpid, argAddress) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} - -func CmdDeleteTerpid() *cobra.Command { - cmd := &cobra.Command{ - Use: "delete-terpid [id]", - Short: "Delete a terpid by id", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - id, err := strconv.ParseUint(args[0], 10, 64) - if err != nil { - return err - } - - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return err - } - - msg := types.NewMsgDeleteTerpid(clientCtx.GetFromAddress().String(), id) - if err := msg.ValidateBasic(); err != nil { - return err - } - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - } - - flags.AddTxFlagsToCmd(cmd) - - return cmd -} diff --git a/x/terp/client/cli/tx_terpid_test.go b/x/terp/client/cli/tx_terpid_test.go deleted file mode 100644 index c7898d3..0000000 --- a/x/terp/client/cli/tx_terpid_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package cli_test - -import ( - "fmt" - "testing" - - "github.com/cosmos/cosmos-sdk/client/flags" - clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/testutil/network" - "github.com/terpnetwork/terp-core/x/terp/client/cli" -) - -func TestCreateTerpid(t *testing.T) { - net := network.New(t) - val := net.Validators[0] - ctx := val.ClientCtx - - fields := []string{"xyz", "xyz"} - for _, tc := range []struct { - desc string - args []string - err error - code uint32 - }{ - { - desc: "valid", - args: []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(net.Config.BondDenom, sdk.NewInt(10))).String()), - }, - }, - } { - t.Run(tc.desc, func(t *testing.T) { - args := []string{} - args = append(args, fields...) - args = append(args, tc.args...) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdCreateTerpid(), args) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - var resp sdk.TxResponse - require.NoError(t, ctx.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.Equal(t, tc.code, resp.Code) - } - }) - } -} - -func TestUpdateTerpid(t *testing.T) { - net := network.New(t) - - val := net.Validators[0] - ctx := val.ClientCtx - - fields := []string{"xyz", "xyz"} - common := []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(net.Config.BondDenom, sdk.NewInt(10))).String()), - } - args := []string{} - args = append(args, fields...) - args = append(args, common...) - _, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdCreateTerpid(), args) - require.NoError(t, err) - - for _, tc := range []struct { - desc string - id string - args []string - code uint32 - err error - }{ - { - desc: "valid", - id: "0", - args: common, - }, - { - desc: "key not found", - id: "1", - args: common, - code: sdkerrors.ErrKeyNotFound.ABCICode(), - }, - } { - t.Run(tc.desc, func(t *testing.T) { - args := []string{tc.id} - args = append(args, fields...) - args = append(args, tc.args...) - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdUpdateTerpid(), args) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - var resp sdk.TxResponse - require.NoError(t, ctx.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.Equal(t, tc.code, resp.Code) - } - }) - } -} - -func TestDeleteTerpid(t *testing.T) { - net := network.New(t) - - val := net.Validators[0] - ctx := val.ClientCtx - - fields := []string{"xyz", "xyz"} - common := []string{ - fmt.Sprintf("--%s=%s", flags.FlagFrom, val.Address.String()), - fmt.Sprintf("--%s=true", flags.FlagSkipConfirmation), - fmt.Sprintf("--%s=%s", flags.FlagBroadcastMode, flags.BroadcastBlock), - fmt.Sprintf("--%s=%s", flags.FlagFees, sdk.NewCoins(sdk.NewCoin(net.Config.BondDenom, sdk.NewInt(10))).String()), - } - args := []string{} - args = append(args, fields...) - args = append(args, common...) - _, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdCreateTerpid(), args) - require.NoError(t, err) - - for _, tc := range []struct { - desc string - id string - args []string - code uint32 - err error - }{ - { - desc: "valid", - id: "0", - args: common, - }, - { - desc: "key not found", - id: "1", - args: common, - code: sdkerrors.ErrKeyNotFound.ABCICode(), - }, - } { - t.Run(tc.desc, func(t *testing.T) { - out, err := clitestutil.ExecTestCLICmd(ctx, cli.CmdDeleteTerpid(), append([]string{tc.id}, tc.args...)) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - var resp sdk.TxResponse - require.NoError(t, ctx.Codec.UnmarshalJSON(out.Bytes(), &resp)) - require.Equal(t, tc.code, resp.Code) - } - }) - } -} diff --git a/x/terp/genesis.go b/x/terp/genesis.go deleted file mode 100644 index 692e9f4..0000000 --- a/x/terp/genesis.go +++ /dev/null @@ -1,42 +0,0 @@ -package terp - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/terp/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -// InitGenesis initializes the capability module's state from a provided genesis -// state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { - // Set all the terpid - for _, elem := range genState.TerpidList { - k.SetTerpid(ctx, elem) - } - - // Set terpid count - k.SetTerpidCount(ctx, genState.TerpidCount) - // Set all the supplychain - for _, elem := range genState.SupplychainList { - k.SetSupplychain(ctx, elem) - } - - // Set supplychain count - k.SetSupplychainCount(ctx, genState.SupplychainCount) - // this line is used by starport scaffolding # genesis/module/init - k.SetParams(ctx, genState.Params) -} - -// ExportGenesis returns the capability module's exported genesis. -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { - genesis := types.DefaultGenesis() - genesis.Params = k.GetParams(ctx) - - genesis.TerpidList = k.GetAllTerpid(ctx) - genesis.TerpidCount = k.GetTerpidCount(ctx) - genesis.SupplychainList = k.GetAllSupplychain(ctx) - genesis.SupplychainCount = k.GetSupplychainCount(ctx) - // this line is used by starport scaffolding # genesis/module/export - - return genesis -} diff --git a/x/terp/genesis_test.go b/x/terp/genesis_test.go deleted file mode 100644 index d224b2f..0000000 --- a/x/terp/genesis_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package terp_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - keepertest "github.com/terpnetwork/terp-core/testutil/keeper" - "github.com/terpnetwork/terp-core/testutil/nullify" - "github.com/terpnetwork/terp-core/x/terp" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func TestGenesis(t *testing.T) { - genesisState := types.GenesisState{ - Params: types.DefaultParams(), - - TerpidList: []types.Terpid{ - { - Id: 0, - }, - { - Id: 1, - }, - }, - TerpidCount: 2, - SupplychainList: []types.Supplychain{ - { - Id: 0, - }, - { - Id: 1, - }, - }, - SupplychainCount: 2, - // this line is used by starport scaffolding # genesis/test/state - } - - k, ctx := keepertest.TerpKeeper(t) - terp.InitGenesis(ctx, *k, genesisState) - got := terp.ExportGenesis(ctx, *k) - require.NotNil(t, got) - - nullify.Fill(&genesisState) - nullify.Fill(got) - - require.ElementsMatch(t, genesisState.TerpidList, got.TerpidList) - require.Equal(t, genesisState.TerpidCount, got.TerpidCount) - require.ElementsMatch(t, genesisState.SupplychainList, got.SupplychainList) - require.Equal(t, genesisState.SupplychainCount, got.SupplychainCount) - // this line is used by starport scaffolding # genesis/test/assert -} diff --git a/x/terp/handler.go b/x/terp/handler.go deleted file mode 100644 index 156b769..0000000 --- a/x/terp/handler.go +++ /dev/null @@ -1,50 +0,0 @@ -package terp - -import ( - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/terpnetwork/terp-core/x/terp/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -// NewHandler ... -func NewHandler(k keeper.Keeper) sdk.Handler { - msgServer := keeper.NewMsgServerImpl(k) - - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - - switch msg := msg.(type) { - case *types.MsgCreateTerpid: - res, err := msgServer.CreateTerpid(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgUpdateTerpid: - res, err := msgServer.UpdateTerpid(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgDeleteTerpid: - res, err := msgServer.DeleteTerpid(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgCreateSupplychain: - res, err := msgServer.CreateSupplychain(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgUpdateSupplychain: - res, err := msgServer.UpdateSupplychain(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - case *types.MsgDeleteSupplychain: - res, err := msgServer.DeleteSupplychain(sdk.WrapSDKContext(ctx), msg) - return sdk.WrapServiceResult(ctx, res, err) - - // this line is used by starport scaffolding # 1 - default: - errMsg := fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg) - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) - } - } -} diff --git a/x/terp/keeper/grpc_query.go b/x/terp/keeper/grpc_query.go deleted file mode 100644 index 0c2c4f6..0000000 --- a/x/terp/keeper/grpc_query.go +++ /dev/null @@ -1,7 +0,0 @@ -package keeper - -import ( - "github.com/terpnetwork/terp-core/x/terp/types" -) - -var _ types.QueryServer = Keeper{} diff --git a/x/terp/keeper/grpc_query_params.go b/x/terp/keeper/grpc_query_params.go deleted file mode 100644 index 1e7594c..0000000 --- a/x/terp/keeper/grpc_query_params.go +++ /dev/null @@ -1,19 +0,0 @@ -package keeper - -import ( - "context" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/terp/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -func (k Keeper) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - ctx := sdk.UnwrapSDKContext(c) - - return &types.QueryParamsResponse{Params: k.GetParams(ctx)}, nil -} diff --git a/x/terp/keeper/grpc_query_params_test.go b/x/terp/keeper/grpc_query_params_test.go deleted file mode 100644 index 284f55d..0000000 --- a/x/terp/keeper/grpc_query_params_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - testkeeper "github.com/terpnetwork/terp-core/testutil/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func TestParamsQuery(t *testing.T) { - keeper, ctx := testkeeper.TerpKeeper(t) - wctx := sdk.WrapSDKContext(ctx) - params := types.DefaultParams() - keeper.SetParams(ctx, params) - - response, err := keeper.Params(wctx, &types.QueryParamsRequest{}) - require.NoError(t, err) - require.Equal(t, &types.QueryParamsResponse{Params: params}, response) -} diff --git a/x/terp/keeper/grpc_query_supplychain.go b/x/terp/keeper/grpc_query_supplychain.go deleted file mode 100644 index 325430a..0000000 --- a/x/terp/keeper/grpc_query_supplychain.go +++ /dev/null @@ -1,54 +0,0 @@ -package keeper - -import ( - "context" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/terpnetwork/terp-core/x/terp/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -func (k Keeper) SupplychainAll(c context.Context, req *types.QueryAllSupplychainRequest) (*types.QueryAllSupplychainResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - var supplychains []types.Supplychain - ctx := sdk.UnwrapSDKContext(c) - - store := ctx.KVStore(k.storeKey) - supplychainStore := prefix.NewStore(store, types.KeyPrefix(types.SupplychainKey)) - - pageRes, err := query.Paginate(supplychainStore, req.Pagination, func(key []byte, value []byte) error { - var supplychain types.Supplychain - if err := k.cdc.Unmarshal(value, &supplychain); err != nil { - return err - } - - supplychains = append(supplychains, supplychain) - return nil - }) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - return &types.QueryAllSupplychainResponse{Supplychain: supplychains, Pagination: pageRes}, nil -} - -func (k Keeper) Supplychain(c context.Context, req *types.QueryGetSupplychainRequest) (*types.QueryGetSupplychainResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - ctx := sdk.UnwrapSDKContext(c) - supplychain, found := k.GetSupplychain(ctx, req.Id) - if !found { - return nil, sdkerrors.ErrKeyNotFound - } - - return &types.QueryGetSupplychainResponse{Supplychain: supplychain}, nil -} diff --git a/x/terp/keeper/grpc_query_supplychain_test.go b/x/terp/keeper/grpc_query_supplychain_test.go deleted file mode 100644 index 110863f..0000000 --- a/x/terp/keeper/grpc_query_supplychain_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/stretchr/testify/require" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - keepertest "github.com/terpnetwork/terp-core/testutil/keeper" - "github.com/terpnetwork/terp-core/testutil/nullify" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func TestSupplychainQuerySingle(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - wctx := sdk.WrapSDKContext(ctx) - msgs := createNSupplychain(keeper, ctx, 2) - for _, tc := range []struct { - desc string - request *types.QueryGetSupplychainRequest - response *types.QueryGetSupplychainResponse - err error - }{ - { - desc: "First", - request: &types.QueryGetSupplychainRequest{Id: msgs[0].Id}, - response: &types.QueryGetSupplychainResponse{Supplychain: msgs[0]}, - }, - { - desc: "Second", - request: &types.QueryGetSupplychainRequest{Id: msgs[1].Id}, - response: &types.QueryGetSupplychainResponse{Supplychain: msgs[1]}, - }, - { - desc: "KeyNotFound", - request: &types.QueryGetSupplychainRequest{Id: uint64(len(msgs))}, - err: sdkerrors.ErrKeyNotFound, - }, - { - desc: "InvalidRequest", - err: status.Error(codes.InvalidArgument, "invalid request"), - }, - } { - t.Run(tc.desc, func(t *testing.T) { - response, err := keeper.Supplychain(wctx, tc.request) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - require.Equal(t, - nullify.Fill(tc.response), - nullify.Fill(response), - ) - } - }) - } -} - -func TestSupplychainQueryPaginated(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - wctx := sdk.WrapSDKContext(ctx) - msgs := createNSupplychain(keeper, ctx, 5) - - request := func(next []byte, offset, limit uint64, total bool) *types.QueryAllSupplychainRequest { - return &types.QueryAllSupplychainRequest{ - Pagination: &query.PageRequest{ - Key: next, - Offset: offset, - Limit: limit, - CountTotal: total, - }, - } - } - t.Run("ByOffset", func(t *testing.T) { - step := 2 - for i := 0; i < len(msgs); i += step { - resp, err := keeper.SupplychainAll(wctx, request(nil, uint64(i), uint64(step), false)) - require.NoError(t, err) - require.LessOrEqual(t, len(resp.Supplychain), step) - require.Subset(t, - nullify.Fill(msgs), - nullify.Fill(resp.Supplychain), - ) - } - }) - t.Run("ByKey", func(t *testing.T) { - step := 2 - var next []byte - for i := 0; i < len(msgs); i += step { - resp, err := keeper.SupplychainAll(wctx, request(next, 0, uint64(step), false)) - require.NoError(t, err) - require.LessOrEqual(t, len(resp.Supplychain), step) - require.Subset(t, - nullify.Fill(msgs), - nullify.Fill(resp.Supplychain), - ) - next = resp.Pagination.NextKey - } - }) - t.Run("Total", func(t *testing.T) { - resp, err := keeper.SupplychainAll(wctx, request(nil, 0, 0, true)) - require.NoError(t, err) - require.Equal(t, len(msgs), int(resp.Pagination.Total)) - require.ElementsMatch(t, - nullify.Fill(msgs), - nullify.Fill(resp.Supplychain), - ) - }) - t.Run("InvalidRequest", func(t *testing.T) { - _, err := keeper.SupplychainAll(wctx, nil) - require.ErrorIs(t, err, status.Error(codes.InvalidArgument, "invalid request")) - }) -} diff --git a/x/terp/keeper/grpc_query_terpid.go b/x/terp/keeper/grpc_query_terpid.go deleted file mode 100644 index f830129..0000000 --- a/x/terp/keeper/grpc_query_terpid.go +++ /dev/null @@ -1,54 +0,0 @@ -package keeper - -import ( - "context" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/terpnetwork/terp-core/x/terp/types" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -func (k Keeper) TerpidAll(c context.Context, req *types.QueryAllTerpidRequest) (*types.QueryAllTerpidResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - var terpids []types.Terpid - ctx := sdk.UnwrapSDKContext(c) - - store := ctx.KVStore(k.storeKey) - terpidStore := prefix.NewStore(store, types.KeyPrefix(types.TerpidKey)) - - pageRes, err := query.Paginate(terpidStore, req.Pagination, func(key []byte, value []byte) error { - var terpid types.Terpid - if err := k.cdc.Unmarshal(value, &terpid); err != nil { - return err - } - - terpids = append(terpids, terpid) - return nil - }) - if err != nil { - return nil, status.Error(codes.Internal, err.Error()) - } - - return &types.QueryAllTerpidResponse{Terpid: terpids, Pagination: pageRes}, nil -} - -func (k Keeper) Terpid(c context.Context, req *types.QueryGetTerpidRequest) (*types.QueryGetTerpidResponse, error) { - if req == nil { - return nil, status.Error(codes.InvalidArgument, "invalid request") - } - - ctx := sdk.UnwrapSDKContext(c) - terpid, found := k.GetTerpid(ctx, req.Id) - if !found { - return nil, sdkerrors.ErrKeyNotFound - } - - return &types.QueryGetTerpidResponse{Terpid: terpid}, nil -} diff --git a/x/terp/keeper/grpc_query_terpid_test.go b/x/terp/keeper/grpc_query_terpid_test.go deleted file mode 100644 index 0c56c10..0000000 --- a/x/terp/keeper/grpc_query_terpid_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/types/query" - "github.com/stretchr/testify/require" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - - keepertest "github.com/terpnetwork/terp-core/testutil/keeper" - "github.com/terpnetwork/terp-core/testutil/nullify" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func TestTerpidQuerySingle(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - wctx := sdk.WrapSDKContext(ctx) - msgs := createNTerpid(keeper, ctx, 2) - for _, tc := range []struct { - desc string - request *types.QueryGetTerpidRequest - response *types.QueryGetTerpidResponse - err error - }{ - { - desc: "First", - request: &types.QueryGetTerpidRequest{Id: msgs[0].Id}, - response: &types.QueryGetTerpidResponse{Terpid: msgs[0]}, - }, - { - desc: "Second", - request: &types.QueryGetTerpidRequest{Id: msgs[1].Id}, - response: &types.QueryGetTerpidResponse{Terpid: msgs[1]}, - }, - { - desc: "KeyNotFound", - request: &types.QueryGetTerpidRequest{Id: uint64(len(msgs))}, - err: sdkerrors.ErrKeyNotFound, - }, - { - desc: "InvalidRequest", - err: status.Error(codes.InvalidArgument, "invalid request"), - }, - } { - t.Run(tc.desc, func(t *testing.T) { - response, err := keeper.Terpid(wctx, tc.request) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - require.Equal(t, - nullify.Fill(tc.response), - nullify.Fill(response), - ) - } - }) - } -} - -func TestTerpidQueryPaginated(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - wctx := sdk.WrapSDKContext(ctx) - msgs := createNTerpid(keeper, ctx, 5) - - request := func(next []byte, offset, limit uint64, total bool) *types.QueryAllTerpidRequest { - return &types.QueryAllTerpidRequest{ - Pagination: &query.PageRequest{ - Key: next, - Offset: offset, - Limit: limit, - CountTotal: total, - }, - } - } - t.Run("ByOffset", func(t *testing.T) { - step := 2 - for i := 0; i < len(msgs); i += step { - resp, err := keeper.TerpidAll(wctx, request(nil, uint64(i), uint64(step), false)) - require.NoError(t, err) - require.LessOrEqual(t, len(resp.Terpid), step) - require.Subset(t, - nullify.Fill(msgs), - nullify.Fill(resp.Terpid), - ) - } - }) - t.Run("ByKey", func(t *testing.T) { - step := 2 - var next []byte - for i := 0; i < len(msgs); i += step { - resp, err := keeper.TerpidAll(wctx, request(next, 0, uint64(step), false)) - require.NoError(t, err) - require.LessOrEqual(t, len(resp.Terpid), step) - require.Subset(t, - nullify.Fill(msgs), - nullify.Fill(resp.Terpid), - ) - next = resp.Pagination.NextKey - } - }) - t.Run("Total", func(t *testing.T) { - resp, err := keeper.TerpidAll(wctx, request(nil, 0, 0, true)) - require.NoError(t, err) - require.Equal(t, len(msgs), int(resp.Pagination.Total)) - require.ElementsMatch(t, - nullify.Fill(msgs), - nullify.Fill(resp.Terpid), - ) - }) - t.Run("InvalidRequest", func(t *testing.T) { - _, err := keeper.TerpidAll(wctx, nil) - require.ErrorIs(t, err, status.Error(codes.InvalidArgument, "invalid request")) - }) -} diff --git a/x/terp/keeper/keeper.go b/x/terp/keeper/keeper.go deleted file mode 100644 index f5690c8..0000000 --- a/x/terp/keeper/keeper.go +++ /dev/null @@ -1,44 +0,0 @@ -package keeper - -import ( - "fmt" - - "github.com/tendermint/tendermint/libs/log" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -type ( - Keeper struct { - cdc codec.BinaryCodec - storeKey sdk.StoreKey - memKey sdk.StoreKey - paramstore paramtypes.Subspace - } -) - -func NewKeeper( - cdc codec.BinaryCodec, - storeKey, - memKey sdk.StoreKey, - ps paramtypes.Subspace, -) *Keeper { - // set KeyTable if it has not already been set - if !ps.HasKeyTable() { - ps = ps.WithKeyTable(types.ParamKeyTable()) - } - - return &Keeper{ - cdc: cdc, - storeKey: storeKey, - memKey: memKey, - paramstore: ps, - } -} - -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} diff --git a/x/terp/keeper/msg_server.go b/x/terp/keeper/msg_server.go deleted file mode 100644 index ad744f3..0000000 --- a/x/terp/keeper/msg_server.go +++ /dev/null @@ -1,17 +0,0 @@ -package keeper - -import ( - "github.com/terpnetwork/terp-core/x/terp/types" -) - -type msgServer struct { - Keeper -} - -// NewMsgServerImpl returns an implementation of the MsgServer interface -// for the provided Keeper. -func NewMsgServerImpl(keeper Keeper) types.MsgServer { - return &msgServer{Keeper: keeper} -} - -var _ types.MsgServer = msgServer{} diff --git a/x/terp/keeper/msg_server_supplychain.go b/x/terp/keeper/msg_server_supplychain.go deleted file mode 100644 index b8174c5..0000000 --- a/x/terp/keeper/msg_server_supplychain.go +++ /dev/null @@ -1,78 +0,0 @@ -package keeper - -import ( - "context" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func (k msgServer) CreateSupplychain(goCtx context.Context, msg *types.MsgCreateSupplychain) (*types.MsgCreateSupplychainResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - supplychain := types.Supplychain{ - Creator: msg.Creator, - Product: msg.Product, - Info: msg.Info, - Supplyinfo: msg.Supplyinfo, - Supplyextra: msg.Supplyextra, - } - - id := k.AppendSupplychain( - ctx, - supplychain, - ) - - return &types.MsgCreateSupplychainResponse{ - Id: id, - }, nil -} - -func (k msgServer) UpdateSupplychain(goCtx context.Context, msg *types.MsgUpdateSupplychain) (*types.MsgUpdateSupplychainResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - supplychain := types.Supplychain{ - Creator: msg.Creator, - Id: msg.Id, - Product: msg.Product, - Info: msg.Info, - Supplyinfo: msg.Supplyinfo, - Supplyextra: msg.Supplyextra, - } - - // Checks that the element exists - val, found := k.GetSupplychain(ctx, msg.Id) - if !found { - return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn't exist", msg.Id)) - } - - // Checks if the msg creator is the same as the current owner - if msg.Creator != val.Creator { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "incorrect owner") - } - - k.SetSupplychain(ctx, supplychain) - - return &types.MsgUpdateSupplychainResponse{}, nil -} - -func (k msgServer) DeleteSupplychain(goCtx context.Context, msg *types.MsgDeleteSupplychain) (*types.MsgDeleteSupplychainResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - // Checks that the element exists - val, found := k.GetSupplychain(ctx, msg.Id) - if !found { - return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn't exist", msg.Id)) - } - - // Checks if the msg creator is the same as the current owner - if msg.Creator != val.Creator { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "incorrect owner") - } - - k.RemoveSupplychain(ctx, msg.Id) - - return &types.MsgDeleteSupplychainResponse{}, nil -} diff --git a/x/terp/keeper/msg_server_supplychain_test.go b/x/terp/keeper/msg_server_supplychain_test.go deleted file mode 100644 index cb7bca3..0000000 --- a/x/terp/keeper/msg_server_supplychain_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func TestSupplychainMsgServerCreate(t *testing.T) { - srv, ctx := setupMsgServer(t) - creator := "A" - for i := 0; i < 5; i++ { - resp, err := srv.CreateSupplychain(ctx, &types.MsgCreateSupplychain{Creator: creator}) - require.NoError(t, err) - require.Equal(t, i, int(resp.Id)) - } -} - -func TestSupplychainMsgServerUpdate(t *testing.T) { - creator := "A" - - for _, tc := range []struct { - desc string - request *types.MsgUpdateSupplychain - err error - }{ - { - desc: "Completed", - request: &types.MsgUpdateSupplychain{Creator: creator}, - }, - { - desc: "Unauthorized", - request: &types.MsgUpdateSupplychain{Creator: "B"}, - err: sdkerrors.ErrUnauthorized, - }, - { - desc: "Unauthorized", - request: &types.MsgUpdateSupplychain{Creator: creator, Id: 10}, - err: sdkerrors.ErrKeyNotFound, - }, - } { - t.Run(tc.desc, func(t *testing.T) { - srv, ctx := setupMsgServer(t) - _, err := srv.CreateSupplychain(ctx, &types.MsgCreateSupplychain{Creator: creator}) - require.NoError(t, err) - - _, err = srv.UpdateSupplychain(ctx, tc.request) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestSupplychainMsgServerDelete(t *testing.T) { - creator := "A" - - for _, tc := range []struct { - desc string - request *types.MsgDeleteSupplychain - err error - }{ - { - desc: "Completed", - request: &types.MsgDeleteSupplychain{Creator: creator}, - }, - { - desc: "Unauthorized", - request: &types.MsgDeleteSupplychain{Creator: "B"}, - err: sdkerrors.ErrUnauthorized, - }, - { - desc: "KeyNotFound", - request: &types.MsgDeleteSupplychain{Creator: creator, Id: 10}, - err: sdkerrors.ErrKeyNotFound, - }, - } { - t.Run(tc.desc, func(t *testing.T) { - srv, ctx := setupMsgServer(t) - - _, err := srv.CreateSupplychain(ctx, &types.MsgCreateSupplychain{Creator: creator}) - require.NoError(t, err) - _, err = srv.DeleteSupplychain(ctx, tc.request) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/x/terp/keeper/msg_server_terpid.go b/x/terp/keeper/msg_server_terpid.go deleted file mode 100644 index b9a25e6..0000000 --- a/x/terp/keeper/msg_server_terpid.go +++ /dev/null @@ -1,74 +0,0 @@ -package keeper - -import ( - "context" - "fmt" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func (k msgServer) CreateTerpid(goCtx context.Context, msg *types.MsgCreateTerpid) (*types.MsgCreateTerpidResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - terpid := types.Terpid{ - Creator: msg.Creator, - Terpid: msg.Terpid, - Address: msg.Address, - } - - id := k.AppendTerpid( - ctx, - terpid, - ) - - return &types.MsgCreateTerpidResponse{ - Id: id, - }, nil -} - -func (k msgServer) UpdateTerpid(goCtx context.Context, msg *types.MsgUpdateTerpid) (*types.MsgUpdateTerpidResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - terpid := types.Terpid{ - Creator: msg.Creator, - Id: msg.Id, - Terpid: msg.Terpid, - Address: msg.Address, - } - - // Checks that the element exists - val, found := k.GetTerpid(ctx, msg.Id) - if !found { - return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn't exist", msg.Id)) - } - - // Checks if the msg creator is the same as the current owner - if msg.Creator != val.Creator { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "incorrect owner") - } - - k.SetTerpid(ctx, terpid) - - return &types.MsgUpdateTerpidResponse{}, nil -} - -func (k msgServer) DeleteTerpid(goCtx context.Context, msg *types.MsgDeleteTerpid) (*types.MsgDeleteTerpidResponse, error) { - ctx := sdk.UnwrapSDKContext(goCtx) - - // Checks that the element exists - val, found := k.GetTerpid(ctx, msg.Id) - if !found { - return nil, sdkerrors.Wrap(sdkerrors.ErrKeyNotFound, fmt.Sprintf("key %d doesn't exist", msg.Id)) - } - - // Checks if the msg creator is the same as the current owner - if msg.Creator != val.Creator { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "incorrect owner") - } - - k.RemoveTerpid(ctx, msg.Id) - - return &types.MsgDeleteTerpidResponse{}, nil -} diff --git a/x/terp/keeper/msg_server_terpid_test.go b/x/terp/keeper/msg_server_terpid_test.go deleted file mode 100644 index 387b1d8..0000000 --- a/x/terp/keeper/msg_server_terpid_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func TestTerpidMsgServerCreate(t *testing.T) { - srv, ctx := setupMsgServer(t) - creator := "A" - for i := 0; i < 5; i++ { - resp, err := srv.CreateTerpid(ctx, &types.MsgCreateTerpid{Creator: creator}) - require.NoError(t, err) - require.Equal(t, i, int(resp.Id)) - } -} - -func TestTerpidMsgServerUpdate(t *testing.T) { - creator := "A" - - for _, tc := range []struct { - desc string - request *types.MsgUpdateTerpid - err error - }{ - { - desc: "Completed", - request: &types.MsgUpdateTerpid{Creator: creator}, - }, - { - desc: "Unauthorized", - request: &types.MsgUpdateTerpid{Creator: "B"}, - err: sdkerrors.ErrUnauthorized, - }, - { - desc: "Unauthorized", - request: &types.MsgUpdateTerpid{Creator: creator, Id: 10}, - err: sdkerrors.ErrKeyNotFound, - }, - } { - t.Run(tc.desc, func(t *testing.T) { - srv, ctx := setupMsgServer(t) - _, err := srv.CreateTerpid(ctx, &types.MsgCreateTerpid{Creator: creator}) - require.NoError(t, err) - - _, err = srv.UpdateTerpid(ctx, tc.request) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestTerpidMsgServerDelete(t *testing.T) { - creator := "A" - - for _, tc := range []struct { - desc string - request *types.MsgDeleteTerpid - err error - }{ - { - desc: "Completed", - request: &types.MsgDeleteTerpid{Creator: creator}, - }, - { - desc: "Unauthorized", - request: &types.MsgDeleteTerpid{Creator: "B"}, - err: sdkerrors.ErrUnauthorized, - }, - { - desc: "KeyNotFound", - request: &types.MsgDeleteTerpid{Creator: creator, Id: 10}, - err: sdkerrors.ErrKeyNotFound, - }, - } { - t.Run(tc.desc, func(t *testing.T) { - srv, ctx := setupMsgServer(t) - - _, err := srv.CreateTerpid(ctx, &types.MsgCreateTerpid{Creator: creator}) - require.NoError(t, err) - _, err = srv.DeleteTerpid(ctx, tc.request) - if tc.err != nil { - require.ErrorIs(t, err, tc.err) - } else { - require.NoError(t, err) - } - }) - } -} diff --git a/x/terp/keeper/msg_server_test.go b/x/terp/keeper/msg_server_test.go deleted file mode 100644 index 173606d..0000000 --- a/x/terp/keeper/msg_server_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package keeper_test - -import ( - "context" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - keepertest "github.com/terpnetwork/terp-core/testutil/keeper" - "github.com/terpnetwork/terp-core/x/terp/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func setupMsgServer(t testing.TB) (types.MsgServer, context.Context) { - k, ctx := keepertest.TerpKeeper(t) - return keeper.NewMsgServerImpl(*k), sdk.WrapSDKContext(ctx) -} diff --git a/x/terp/keeper/params.go b/x/terp/keeper/params.go deleted file mode 100644 index b788c26..0000000 --- a/x/terp/keeper/params.go +++ /dev/null @@ -1,16 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -// GetParams get all parameters as types.Params -func (k Keeper) GetParams(ctx sdk.Context) types.Params { - return types.NewParams() -} - -// SetParams set the params -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramstore.SetParamSet(ctx, ¶ms) -} diff --git a/x/terp/keeper/params_test.go b/x/terp/keeper/params_test.go deleted file mode 100644 index fe2d153..0000000 --- a/x/terp/keeper/params_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package keeper_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - testkeeper "github.com/terpnetwork/terp-core/testutil/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func TestGetParams(t *testing.T) { - k, ctx := testkeeper.TerpKeeper(t) - params := types.DefaultParams() - - k.SetParams(ctx, params) - - require.EqualValues(t, params, k.GetParams(ctx)) -} diff --git a/x/terp/keeper/supplychain.go b/x/terp/keeper/supplychain.go deleted file mode 100644 index 045c7aa..0000000 --- a/x/terp/keeper/supplychain.go +++ /dev/null @@ -1,106 +0,0 @@ -package keeper - -import ( - "encoding/binary" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -// GetSupplychainCount get the total number of supplychain -func (k Keeper) GetSupplychainCount(ctx sdk.Context) uint64 { - store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte{}) - byteKey := types.KeyPrefix(types.SupplychainCountKey) - bz := store.Get(byteKey) - - // Count doesn't exist: no element - if bz == nil { - return 0 - } - - // Parse bytes - return binary.BigEndian.Uint64(bz) -} - -// SetSupplychainCount set the total number of supplychain -func (k Keeper) SetSupplychainCount(ctx sdk.Context, count uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte{}) - byteKey := types.KeyPrefix(types.SupplychainCountKey) - bz := make([]byte, 8) - binary.BigEndian.PutUint64(bz, count) - store.Set(byteKey, bz) -} - -// AppendSupplychain appends a supplychain in the store with a new id and update the count -func (k Keeper) AppendSupplychain( - ctx sdk.Context, - supplychain types.Supplychain, -) uint64 { - // Create the supplychain - count := k.GetSupplychainCount(ctx) - - // Set the ID of the appended value - supplychain.Id = count - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.SupplychainKey)) - appendedValue := k.cdc.MustMarshal(&supplychain) - store.Set(GetSupplychainIDBytes(supplychain.Id), appendedValue) - - // Update supplychain count - k.SetSupplychainCount(ctx, count+1) - - return count -} - -// SetSupplychain set a specific supplychain in the store -func (k Keeper) SetSupplychain(ctx sdk.Context, supplychain types.Supplychain) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.SupplychainKey)) - b := k.cdc.MustMarshal(&supplychain) - store.Set(GetSupplychainIDBytes(supplychain.Id), b) -} - -// GetSupplychain returns a supplychain from its id -func (k Keeper) GetSupplychain(ctx sdk.Context, id uint64) (val types.Supplychain, found bool) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.SupplychainKey)) - b := store.Get(GetSupplychainIDBytes(id)) - if b == nil { - return val, false - } - k.cdc.MustUnmarshal(b, &val) - return val, true -} - -// RemoveSupplychain removes a supplychain from the store -func (k Keeper) RemoveSupplychain(ctx sdk.Context, id uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.SupplychainKey)) - store.Delete(GetSupplychainIDBytes(id)) -} - -// GetAllSupplychain returns all supplychain -func (k Keeper) GetAllSupplychain(ctx sdk.Context) (list []types.Supplychain) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.SupplychainKey)) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var val types.Supplychain - k.cdc.MustUnmarshal(iterator.Value(), &val) - list = append(list, val) - } - - return -} - -// GetSupplychainIDBytes returns the byte representation of the ID -func GetSupplychainIDBytes(id uint64) []byte { - bz := make([]byte, 8) - binary.BigEndian.PutUint64(bz, id) - return bz -} - -// GetSupplychainIDFromBytes returns ID in uint64 format from a byte array -func GetSupplychainIDFromBytes(bz []byte) uint64 { - return binary.BigEndian.Uint64(bz) -} diff --git a/x/terp/keeper/supplychain_test.go b/x/terp/keeper/supplychain_test.go deleted file mode 100644 index 9821491..0000000 --- a/x/terp/keeper/supplychain_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - keepertest "github.com/terpnetwork/terp-core/testutil/keeper" - "github.com/terpnetwork/terp-core/testutil/nullify" - "github.com/terpnetwork/terp-core/x/terp/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func createNSupplychain(keeper *keeper.Keeper, ctx sdk.Context, n int) []types.Supplychain { - items := make([]types.Supplychain, n) - for i := range items { - items[i].Id = keeper.AppendSupplychain(ctx, items[i]) - } - return items -} - -func TestSupplychainGet(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - items := createNSupplychain(keeper, ctx, 10) - for _, item := range items { - got, found := keeper.GetSupplychain(ctx, item.Id) - require.True(t, found) - require.Equal(t, - nullify.Fill(&item), - nullify.Fill(&got), - ) - } -} - -func TestSupplychainRemove(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - items := createNSupplychain(keeper, ctx, 10) - for _, item := range items { - keeper.RemoveSupplychain(ctx, item.Id) - _, found := keeper.GetSupplychain(ctx, item.Id) - require.False(t, found) - } -} - -func TestSupplychainGetAll(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - items := createNSupplychain(keeper, ctx, 10) - require.ElementsMatch(t, - nullify.Fill(items), - nullify.Fill(keeper.GetAllSupplychain(ctx)), - ) -} - -func TestSupplychainCount(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - items := createNSupplychain(keeper, ctx, 10) - count := uint64(len(items)) - require.Equal(t, count, keeper.GetSupplychainCount(ctx)) -} diff --git a/x/terp/keeper/terpid.go b/x/terp/keeper/terpid.go deleted file mode 100644 index 4811fea..0000000 --- a/x/terp/keeper/terpid.go +++ /dev/null @@ -1,106 +0,0 @@ -package keeper - -import ( - "encoding/binary" - - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -// GetTerpidCount get the total number of terpid -func (k Keeper) GetTerpidCount(ctx sdk.Context) uint64 { - store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte{}) - byteKey := types.KeyPrefix(types.TerpidCountKey) - bz := store.Get(byteKey) - - // Count doesn't exist: no element - if bz == nil { - return 0 - } - - // Parse bytes - return binary.BigEndian.Uint64(bz) -} - -// SetTerpidCount set the total number of terpid -func (k Keeper) SetTerpidCount(ctx sdk.Context, count uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte{}) - byteKey := types.KeyPrefix(types.TerpidCountKey) - bz := make([]byte, 8) - binary.BigEndian.PutUint64(bz, count) - store.Set(byteKey, bz) -} - -// AppendTerpid appends a terpid in the store with a new id and update the count -func (k Keeper) AppendTerpid( - ctx sdk.Context, - terpid types.Terpid, -) uint64 { - // Create the terpid - count := k.GetTerpidCount(ctx) - - // Set the ID of the appended value - terpid.Id = count - - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TerpidKey)) - appendedValue := k.cdc.MustMarshal(&terpid) - store.Set(GetTerpidIDBytes(terpid.Id), appendedValue) - - // Update terpid count - k.SetTerpidCount(ctx, count+1) - - return count -} - -// SetTerpid set a specific terpid in the store -func (k Keeper) SetTerpid(ctx sdk.Context, terpid types.Terpid) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TerpidKey)) - b := k.cdc.MustMarshal(&terpid) - store.Set(GetTerpidIDBytes(terpid.Id), b) -} - -// GetTerpid returns a terpid from its id -func (k Keeper) GetTerpid(ctx sdk.Context, id uint64) (val types.Terpid, found bool) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TerpidKey)) - b := store.Get(GetTerpidIDBytes(id)) - if b == nil { - return val, false - } - k.cdc.MustUnmarshal(b, &val) - return val, true -} - -// RemoveTerpid removes a terpid from the store -func (k Keeper) RemoveTerpid(ctx sdk.Context, id uint64) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TerpidKey)) - store.Delete(GetTerpidIDBytes(id)) -} - -// GetAllTerpid returns all terpid -func (k Keeper) GetAllTerpid(ctx sdk.Context) (list []types.Terpid) { - store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TerpidKey)) - iterator := sdk.KVStorePrefixIterator(store, []byte{}) - - defer iterator.Close() - - for ; iterator.Valid(); iterator.Next() { - var val types.Terpid - k.cdc.MustUnmarshal(iterator.Value(), &val) - list = append(list, val) - } - - return -} - -// GetTerpidIDBytes returns the byte representation of the ID -func GetTerpidIDBytes(id uint64) []byte { - bz := make([]byte, 8) - binary.BigEndian.PutUint64(bz, id) - return bz -} - -// GetTerpidIDFromBytes returns ID in uint64 format from a byte array -func GetTerpidIDFromBytes(bz []byte) uint64 { - return binary.BigEndian.Uint64(bz) -} diff --git a/x/terp/keeper/terpid_test.go b/x/terp/keeper/terpid_test.go deleted file mode 100644 index 6f6119c..0000000 --- a/x/terp/keeper/terpid_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package keeper_test - -import ( - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/require" - keepertest "github.com/terpnetwork/terp-core/testutil/keeper" - "github.com/terpnetwork/terp-core/testutil/nullify" - "github.com/terpnetwork/terp-core/x/terp/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func createNTerpid(keeper *keeper.Keeper, ctx sdk.Context, n int) []types.Terpid { - items := make([]types.Terpid, n) - for i := range items { - items[i].Id = keeper.AppendTerpid(ctx, items[i]) - } - return items -} - -func TestTerpidGet(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - items := createNTerpid(keeper, ctx, 10) - for _, item := range items { - got, found := keeper.GetTerpid(ctx, item.Id) - require.True(t, found) - require.Equal(t, - nullify.Fill(&item), - nullify.Fill(&got), - ) - } -} - -func TestTerpidRemove(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - items := createNTerpid(keeper, ctx, 10) - for _, item := range items { - keeper.RemoveTerpid(ctx, item.Id) - _, found := keeper.GetTerpid(ctx, item.Id) - require.False(t, found) - } -} - -func TestTerpidGetAll(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - items := createNTerpid(keeper, ctx, 10) - require.ElementsMatch(t, - nullify.Fill(items), - nullify.Fill(keeper.GetAllTerpid(ctx)), - ) -} - -func TestTerpidCount(t *testing.T) { - keeper, ctx := keepertest.TerpKeeper(t) - items := createNTerpid(keeper, ctx, 10) - count := uint64(len(items)) - require.Equal(t, count, keeper.GetTerpidCount(ctx)) -} diff --git a/x/terp/module.go b/x/terp/module.go deleted file mode 100644 index b9b6bce..0000000 --- a/x/terp/module.go +++ /dev/null @@ -1,175 +0,0 @@ -package terp - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/gorilla/mux" - "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/spf13/cobra" - - abci "github.com/tendermint/tendermint/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/terpnetwork/terp-core/x/terp/client/cli" - "github.com/terpnetwork/terp-core/x/terp/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} -) - -// ---------------------------------------------------------------------------- -// AppModuleBasic -// ---------------------------------------------------------------------------- - -// AppModuleBasic implements the AppModuleBasic interface for the capability module. -type AppModuleBasic struct { - cdc codec.BinaryCodec -} - -func NewAppModuleBasic(cdc codec.BinaryCodec) AppModuleBasic { - return AppModuleBasic{cdc: cdc} -} - -// Name returns the capability module's name. -func (AppModuleBasic) Name() string { - return types.ModuleName -} - -func (AppModuleBasic) RegisterCodec(cdc *codec.LegacyAmino) { - types.RegisterCodec(cdc) -} - -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterCodec(cdc) -} - -// RegisterInterfaces registers the module's interface types -func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { - types.RegisterInterfaces(reg) -} - -// DefaultGenesis returns the capability module's default genesis state. -func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { - return cdc.MustMarshalJSON(types.DefaultGenesis()) -} - -// ValidateGenesis performs genesis state validation for the capability module. -func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { - var genState types.GenesisState - if err := cdc.UnmarshalJSON(bz, &genState); err != nil { - return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) - } - return genState.Validate() -} - -// RegisterRESTRoutes registers the capability module's REST service handlers. -func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { -} - -// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. -func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) //nolint:errcheck -} - -// GetTxCmd returns the capability module's root tx command. -func (a AppModuleBasic) GetTxCmd() *cobra.Command { - return cli.GetTxCmd() -} - -// GetQueryCmd returns the capability module's root query command. -func (AppModuleBasic) GetQueryCmd() *cobra.Command { - return cli.GetQueryCmd(types.StoreKey) -} - -// ---------------------------------------------------------------------------- -// AppModule -// ---------------------------------------------------------------------------- - -// AppModule implements the AppModule interface for the capability module. -type AppModule struct { - AppModuleBasic - - keeper keeper.Keeper - accountKeeper types.AccountKeeper - bankKeeper types.BankKeeper -} - -func NewAppModule( - cdc codec.Codec, - keeper keeper.Keeper, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, -) AppModule { - return AppModule{ - AppModuleBasic: NewAppModuleBasic(cdc), - keeper: keeper, - accountKeeper: accountKeeper, - bankKeeper: bankKeeper, - } -} - -// Name returns the capability module's name. -func (am AppModule) Name() string { - return am.AppModuleBasic.Name() -} - -// Route returns the capability module's message routing key. -func (am AppModule) Route() sdk.Route { - return sdk.NewRoute(types.RouterKey, NewHandler(am.keeper)) -} - -// QuerierRoute returns the capability module's query routing key. -func (AppModule) QuerierRoute() string { return types.QuerierRoute } - -// LegacyQuerierHandler returns the capability module's Querier. -func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return nil -} - -// RegisterServices registers a GRPC query service to respond to the -// module-specific GRPC queries. -func (am AppModule) RegisterServices(cfg module.Configurator) { - types.RegisterQueryServer(cfg.QueryServer(), am.keeper) -} - -// RegisterInvariants registers the capability module's invariants. -func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} - -// InitGenesis performs the capability module's genesis initialization It returns -// no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { - var genState types.GenesisState - // Initialize global index to index in genesis state - cdc.MustUnmarshalJSON(gs, &genState) - - InitGenesis(ctx, am.keeper, genState) - - return []abci.ValidatorUpdate{} -} - -// ExportGenesis returns the capability module's exported genesis state as raw JSON bytes. -func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { - genState := ExportGenesis(ctx, am.keeper) - return cdc.MustMarshalJSON(genState) -} - -// ConsensusVersion implements ConsensusVersion. -func (AppModule) ConsensusVersion() uint64 { return 1 } - -// BeginBlock executes all ABCI BeginBlock logic respective to the capability module. -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} - -// EndBlock executes all ABCI EndBlock logic respective to the capability module. It -// returns no validator updates. -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} -} diff --git a/x/terp/module_simulation.go b/x/terp/module_simulation.go deleted file mode 100644 index 403de71..0000000 --- a/x/terp/module_simulation.go +++ /dev/null @@ -1,175 +0,0 @@ -package terp - -import ( - "math/rand" - - "github.com/cosmos/cosmos-sdk/baseapp" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/module" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/terpnetwork/terp-core/testutil/sample" - terpsimulation "github.com/terpnetwork/terp-core/x/terp/simulation" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -// avoid unused import issue -var ( - _ = sample.AccAddress - _ = terpsimulation.FindAccount - _ = simappparams.StakePerAccount - _ = simulation.MsgEntryKind - _ = baseapp.Paramspace -) - -const ( - opWeightMsgCreateTerpid = "op_weight_msg_terpid" - // TODO: Determine the simulation weight value - defaultWeightMsgCreateTerpid int = 100 - - opWeightMsgUpdateTerpid = "op_weight_msg_terpid" - // TODO: Determine the simulation weight value - defaultWeightMsgUpdateTerpid int = 100 - - opWeightMsgDeleteTerpid = "op_weight_msg_terpid" - // TODO: Determine the simulation weight value - defaultWeightMsgDeleteTerpid int = 100 - - opWeightMsgCreateSupplychain = "op_weight_msg_supplychain" - // TODO: Determine the simulation weight value - defaultWeightMsgCreateSupplychain int = 100 - - opWeightMsgUpdateSupplychain = "op_weight_msg_supplychain" - // TODO: Determine the simulation weight value - defaultWeightMsgUpdateSupplychain int = 100 - - opWeightMsgDeleteSupplychain = "op_weight_msg_supplychain" - // TODO: Determine the simulation weight value - defaultWeightMsgDeleteSupplychain int = 100 - - // this line is used by starport scaffolding # simapp/module/const -) - -// GenerateGenesisState creates a randomized GenState of the module -func (AppModule) GenerateGenesisState(simState *module.SimulationState) { - accs := make([]string, len(simState.Accounts)) - for i, acc := range simState.Accounts { - accs[i] = acc.Address.String() - } - terpGenesis := types.GenesisState{ - Params: types.DefaultParams(), - TerpidList: []types.Terpid{ - { - Id: 0, - Creator: sample.AccAddress(), - }, - { - Id: 1, - Creator: sample.AccAddress(), - }, - }, - TerpidCount: 2, - SupplychainList: []types.Supplychain{ - { - Id: 0, - Creator: sample.AccAddress(), - }, - { - Id: 1, - Creator: sample.AccAddress(), - }, - }, - SupplychainCount: 2, - // this line is used by starport scaffolding # simapp/module/genesisState - } - simState.GenState[types.ModuleName] = simState.Cdc.MustMarshalJSON(&terpGenesis) -} - -// ProposalContents doesn't return any content functions for governance proposals -func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedProposalContent { - return nil -} - -// RandomizedParams creates randomized param changes for the simulator -func (am AppModule) RandomizedParams(_ *rand.Rand) []simtypes.ParamChange { - return []simtypes.ParamChange{} -} - -// RegisterStoreDecoder registers a decoder -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 { - operations := make([]simtypes.WeightedOperation, 0) - - var weightMsgCreateTerpid int - simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgCreateTerpid, &weightMsgCreateTerpid, nil, - func(_ *rand.Rand) { - weightMsgCreateTerpid = defaultWeightMsgCreateTerpid - }, - ) - operations = append(operations, simulation.NewWeightedOperation( - weightMsgCreateTerpid, - terpsimulation.SimulateMsgCreateTerpid(am.accountKeeper, am.bankKeeper, am.keeper), - )) - - var weightMsgUpdateTerpid int - simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgUpdateTerpid, &weightMsgUpdateTerpid, nil, - func(_ *rand.Rand) { - weightMsgUpdateTerpid = defaultWeightMsgUpdateTerpid - }, - ) - operations = append(operations, simulation.NewWeightedOperation( - weightMsgUpdateTerpid, - terpsimulation.SimulateMsgUpdateTerpid(am.accountKeeper, am.bankKeeper, am.keeper), - )) - - var weightMsgDeleteTerpid int - simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgDeleteTerpid, &weightMsgDeleteTerpid, nil, - func(_ *rand.Rand) { - weightMsgDeleteTerpid = defaultWeightMsgDeleteTerpid - }, - ) - operations = append(operations, simulation.NewWeightedOperation( - weightMsgDeleteTerpid, - terpsimulation.SimulateMsgDeleteTerpid(am.accountKeeper, am.bankKeeper, am.keeper), - )) - - var weightMsgCreateSupplychain int - simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgCreateSupplychain, &weightMsgCreateSupplychain, nil, - func(_ *rand.Rand) { - weightMsgCreateSupplychain = defaultWeightMsgCreateSupplychain - }, - ) - operations = append(operations, simulation.NewWeightedOperation( - weightMsgCreateSupplychain, - terpsimulation.SimulateMsgCreateSupplychain(am.accountKeeper, am.bankKeeper, am.keeper), - )) - - var weightMsgUpdateSupplychain int - simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgUpdateSupplychain, &weightMsgUpdateSupplychain, nil, - func(_ *rand.Rand) { - weightMsgUpdateSupplychain = defaultWeightMsgUpdateSupplychain - }, - ) - operations = append(operations, simulation.NewWeightedOperation( - weightMsgUpdateSupplychain, - terpsimulation.SimulateMsgUpdateSupplychain(am.accountKeeper, am.bankKeeper, am.keeper), - )) - - var weightMsgDeleteSupplychain int - simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgDeleteSupplychain, &weightMsgDeleteSupplychain, nil, - func(_ *rand.Rand) { - weightMsgDeleteSupplychain = defaultWeightMsgDeleteSupplychain - }, - ) - operations = append(operations, simulation.NewWeightedOperation( - weightMsgDeleteSupplychain, - terpsimulation.SimulateMsgDeleteSupplychain(am.accountKeeper, am.bankKeeper, am.keeper), - )) - - // this line is used by starport scaffolding # simapp/module/operation - - return operations -} diff --git a/x/terp/simulation/simap.go b/x/terp/simulation/simap.go deleted file mode 100644 index 92c437c..0000000 --- a/x/terp/simulation/simap.go +++ /dev/null @@ -1,15 +0,0 @@ -package simulation - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" -) - -// FindAccount find a specific address from an account list -func FindAccount(accs []simtypes.Account, address string) (simtypes.Account, bool) { - creator, err := sdk.AccAddressFromBech32(address) - if err != nil { - panic(err) - } - return simtypes.FindAccount(accs, creator) -} diff --git a/x/terp/simulation/supplychain.go b/x/terp/simulation/supplychain.go deleted file mode 100644 index 4964b62..0000000 --- a/x/terp/simulation/supplychain.go +++ /dev/null @@ -1,134 +0,0 @@ -package simulation - -import ( - "math/rand" - - "github.com/cosmos/cosmos-sdk/baseapp" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - 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/x/terp/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func SimulateMsgCreateSupplychain( - ak types.AccountKeeper, - bk types.BankKeeper, - k keeper.Keeper, -) simtypes.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - - msg := &types.MsgCreateSupplychain{ - Creator: simAccount.Address.String(), - } - - txCtx := simulation.OperationInput{ - R: r, - App: app, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - ModuleName: types.ModuleName, - CoinsSpentInMsg: sdk.NewCoins(), - AccountKeeper: ak, - Bankkeeper: bk, - } - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -func SimulateMsgUpdateSupplychain( - ak types.AccountKeeper, - bk types.BankKeeper, - k keeper.Keeper, -) simtypes.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - var ( - simAccount = simtypes.Account{} - supplychain = types.Supplychain{} - msg = &types.MsgUpdateSupplychain{} - allSupplychain = k.GetAllSupplychain(ctx) - found = false - ) - for _, obj := range allSupplychain { - simAccount, found = FindAccount(accs, obj.Creator) - if found { - supplychain = obj - break - } - } - if !found { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "supplychain creator not found"), nil, nil - } - msg.Creator = simAccount.Address.String() - msg.Id = supplychain.Id - - txCtx := simulation.OperationInput{ - R: r, - App: app, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - ModuleName: types.ModuleName, - CoinsSpentInMsg: sdk.NewCoins(), - AccountKeeper: ak, - Bankkeeper: bk, - } - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -func SimulateMsgDeleteSupplychain( - ak types.AccountKeeper, - bk types.BankKeeper, - k keeper.Keeper, -) simtypes.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - var ( - simAccount = simtypes.Account{} - supplychain = types.Supplychain{} - msg = &types.MsgUpdateSupplychain{} - allSupplychain = k.GetAllSupplychain(ctx) - found = false - ) - for _, obj := range allSupplychain { - simAccount, found = FindAccount(accs, obj.Creator) - if found { - supplychain = obj - break - } - } - if !found { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "supplychain creator not found"), nil, nil - } - msg.Creator = simAccount.Address.String() - msg.Id = supplychain.Id - - txCtx := simulation.OperationInput{ - R: r, - App: app, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - ModuleName: types.ModuleName, - CoinsSpentInMsg: sdk.NewCoins(), - AccountKeeper: ak, - Bankkeeper: bk, - } - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} diff --git a/x/terp/simulation/terpid.go b/x/terp/simulation/terpid.go deleted file mode 100644 index 06ce357..0000000 --- a/x/terp/simulation/terpid.go +++ /dev/null @@ -1,134 +0,0 @@ -package simulation - -import ( - "math/rand" - - "github.com/cosmos/cosmos-sdk/baseapp" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" - 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/x/terp/keeper" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func SimulateMsgCreateTerpid( - ak types.AccountKeeper, - bk types.BankKeeper, - k keeper.Keeper, -) simtypes.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - simAccount, _ := simtypes.RandomAcc(r, accs) - - msg := &types.MsgCreateTerpid{ - Creator: simAccount.Address.String(), - } - - txCtx := simulation.OperationInput{ - R: r, - App: app, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - ModuleName: types.ModuleName, - CoinsSpentInMsg: sdk.NewCoins(), - AccountKeeper: ak, - Bankkeeper: bk, - } - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -func SimulateMsgUpdateTerpid( - ak types.AccountKeeper, - bk types.BankKeeper, - k keeper.Keeper, -) simtypes.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - var ( - simAccount = simtypes.Account{} - terpid = types.Terpid{} - msg = &types.MsgUpdateTerpid{} - allTerpid = k.GetAllTerpid(ctx) - found = false - ) - for _, obj := range allTerpid { - simAccount, found = FindAccount(accs, obj.Creator) - if found { - terpid = obj - break - } - } - if !found { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "terpid creator not found"), nil, nil - } - msg.Creator = simAccount.Address.String() - msg.Id = terpid.Id - - txCtx := simulation.OperationInput{ - R: r, - App: app, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - ModuleName: types.ModuleName, - CoinsSpentInMsg: sdk.NewCoins(), - AccountKeeper: ak, - Bankkeeper: bk, - } - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} - -func SimulateMsgDeleteTerpid( - ak types.AccountKeeper, - bk types.BankKeeper, - k keeper.Keeper, -) simtypes.Operation { - return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, - ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - var ( - simAccount = simtypes.Account{} - terpid = types.Terpid{} - msg = &types.MsgUpdateTerpid{} - allTerpid = k.GetAllTerpid(ctx) - found = false - ) - for _, obj := range allTerpid { - simAccount, found = FindAccount(accs, obj.Creator) - if found { - terpid = obj - break - } - } - if !found { - return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "terpid creator not found"), nil, nil - } - msg.Creator = simAccount.Address.String() - msg.Id = terpid.Id - - txCtx := simulation.OperationInput{ - R: r, - App: app, - TxGen: simappparams.MakeTestEncodingConfig().TxConfig, - Cdc: nil, - Msg: msg, - MsgType: msg.Type(), - Context: ctx, - SimAccount: simAccount, - ModuleName: types.ModuleName, - CoinsSpentInMsg: sdk.NewCoins(), - AccountKeeper: ak, - Bankkeeper: bk, - } - return simulation.GenAndDeliverTxWithRandFees(txCtx) - } -} diff --git a/x/terp/types/codec.go b/x/terp/types/codec.go deleted file mode 100644 index 150d4f3..0000000 --- a/x/terp/types/codec.go +++ /dev/null @@ -1,39 +0,0 @@ -package types - -import ( - "github.com/cosmos/cosmos-sdk/codec" - cdctypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/msgservice" -) - -func RegisterCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgCreateTerpid{}, "terp/CreateTerpid", nil) - cdc.RegisterConcrete(&MsgUpdateTerpid{}, "terp/UpdateTerpid", nil) - cdc.RegisterConcrete(&MsgDeleteTerpid{}, "terp/DeleteTerpid", nil) - cdc.RegisterConcrete(&MsgCreateSupplychain{}, "terp/CreateSupplychain", nil) - cdc.RegisterConcrete(&MsgUpdateSupplychain{}, "terp/UpdateSupplychain", nil) - cdc.RegisterConcrete(&MsgDeleteSupplychain{}, "terp/DeleteSupplychain", nil) - // this line is used by starport scaffolding # 2 -} - -func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgCreateTerpid{}, - &MsgUpdateTerpid{}, - &MsgDeleteTerpid{}, - ) - registry.RegisterImplementations((*sdk.Msg)(nil), - &MsgCreateSupplychain{}, - &MsgUpdateSupplychain{}, - &MsgDeleteSupplychain{}, - ) - // this line is used by starport scaffolding # 3 - - msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) -} - -var ( - Amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) -) diff --git a/x/terp/types/errors.go b/x/terp/types/errors.go deleted file mode 100644 index f99e734..0000000 --- a/x/terp/types/errors.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -// DONTCOVER - -import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// x/terp module sentinel errors -var ( - ErrSample = sdkerrors.Register(ModuleName, 1100, "sample error") -) diff --git a/x/terp/types/expected_keepers.go b/x/terp/types/expected_keepers.go deleted file mode 100644 index 6aa6e97..0000000 --- a/x/terp/types/expected_keepers.go +++ /dev/null @@ -1,18 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -// AccountKeeper defines the expected account keeper used for simulations (noalias) -type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - // Methods imported from account should be defined here -} - -// BankKeeper defines the expected interface needed to retrieve account balances. -type BankKeeper interface { - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - // Methods imported from bank should be defined here -} diff --git a/x/terp/types/genesis.go b/x/terp/types/genesis.go deleted file mode 100644 index 4e3a2be..0000000 --- a/x/terp/types/genesis.go +++ /dev/null @@ -1,50 +0,0 @@ -package types - -import ( - "fmt" -) - -// DefaultIndex is the default capability global index -const DefaultIndex uint64 = 1 - -// DefaultGenesis returns the default Capability genesis state -func DefaultGenesis() *GenesisState { - return &GenesisState{ - TerpidList: []Terpid{}, - SupplychainList: []Supplychain{}, - // this line is used by starport scaffolding # genesis/types/default - Params: DefaultParams(), - } -} - -// Validate performs basic genesis state validation returning an error upon any -// failure. -func (gs GenesisState) Validate() error { - // Check for duplicated ID in terpid - terpidIdMap := make(map[uint64]bool) - terpidCount := gs.GetTerpidCount() - for _, elem := range gs.TerpidList { - if _, ok := terpidIdMap[elem.Id]; ok { - return fmt.Errorf("duplicated id for terpid") - } - if elem.Id >= terpidCount { - return fmt.Errorf("terpid id should be lower or equal than the last id") - } - terpidIdMap[elem.Id] = true - } - // Check for duplicated ID in supplychain - supplychainIdMap := make(map[uint64]bool) - supplychainCount := gs.GetSupplychainCount() - for _, elem := range gs.SupplychainList { - if _, ok := supplychainIdMap[elem.Id]; ok { - return fmt.Errorf("duplicated id for supplychain") - } - if elem.Id >= supplychainCount { - return fmt.Errorf("supplychain id should be lower or equal than the last id") - } - supplychainIdMap[elem.Id] = true - } - // this line is used by starport scaffolding # genesis/types/validate - - return gs.Params.Validate() -} diff --git a/x/terp/types/genesis.pb.go b/x/terp/types/genesis.pb.go deleted file mode 100644 index 33913c8..0000000 --- a/x/terp/types/genesis.pb.go +++ /dev/null @@ -1,534 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: terp/genesis.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/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 defines the terp module's genesis state. -type GenesisState struct { - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` - TerpidList []Terpid `protobuf:"bytes,2,rep,name=terpidList,proto3" json:"terpidList"` - TerpidCount uint64 `protobuf:"varint,3,opt,name=terpidCount,proto3" json:"terpidCount,omitempty"` - SupplychainList []Supplychain `protobuf:"bytes,4,rep,name=supplychainList,proto3" json:"supplychainList"` - SupplychainCount uint64 `protobuf:"varint,5,opt,name=supplychainCount,proto3" json:"supplychainCount,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_a0474e07bc9bd608, []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) GetTerpidList() []Terpid { - if m != nil { - return m.TerpidList - } - return nil -} - -func (m *GenesisState) GetTerpidCount() uint64 { - if m != nil { - return m.TerpidCount - } - return 0 -} - -func (m *GenesisState) GetSupplychainList() []Supplychain { - if m != nil { - return m.SupplychainList - } - return nil -} - -func (m *GenesisState) GetSupplychainCount() uint64 { - if m != nil { - return m.SupplychainCount - } - return 0 -} - -func init() { - proto.RegisterType((*GenesisState)(nil), "terpnetwork.terp.terp.GenesisState") -} - -func init() { proto.RegisterFile("terp/genesis.proto", fileDescriptor_a0474e07bc9bd608) } - -var fileDescriptor_a0474e07bc9bd608 = []byte{ - // 308 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0xb1, 0x4a, 0xc3, 0x40, - 0x1c, 0xc6, 0x73, 0x6d, 0xed, 0x70, 0x15, 0xab, 0x87, 0x4a, 0xe8, 0x70, 0x06, 0x51, 0x08, 0x0a, - 0x09, 0xd4, 0xdd, 0x21, 0x45, 0xba, 0x38, 0x48, 0x8a, 0x8b, 0xdb, 0x25, 0x86, 0xf4, 0x20, 0xbd, - 0x0b, 0xcd, 0x05, 0xec, 0x5b, 0xf8, 0x58, 0xdd, 0xec, 0xe8, 0x24, 0x92, 0xbc, 0x88, 0xe4, 0x7f, - 0xd1, 0x94, 0x48, 0x96, 0x24, 0xfc, 0xf8, 0xee, 0xf7, 0x7d, 0xe1, 0x30, 0x09, 0x42, 0xc1, 0xdc, - 0x38, 0x12, 0x51, 0xc6, 0x33, 0x27, 0x5d, 0x4b, 0x25, 0x89, 0x19, 0x70, 0x15, 0x32, 0x21, 0x58, - 0x9c, 0xc8, 0x80, 0x25, 0x4e, 0x15, 0x81, 0xc7, 0xe4, 0x34, 0x96, 0xb1, 0x84, 0x90, 0x5b, 0x7d, - 0xe9, 0xfc, 0xe4, 0x04, 0x1c, 0x29, 0x5b, 0xb3, 0x55, 0xad, 0x98, 0x9c, 0x01, 0xfa, 0xf5, 0xf0, - 0xd7, 0x1a, 0x9f, 0x03, 0xce, 0xf2, 0x34, 0x4d, 0x36, 0xe1, 0x92, 0x71, 0xa1, 0xf9, 0xe5, 0x47, - 0x0f, 0x1f, 0xce, 0xf5, 0x86, 0x85, 0x62, 0x2a, 0x22, 0xf7, 0x78, 0xa8, 0x7d, 0x26, 0xb2, 0x90, - 0x3d, 0x9a, 0x5a, 0x4e, 0xd7, 0x26, 0xe7, 0x09, 0x72, 0xde, 0x60, 0xfb, 0x75, 0x61, 0xf8, 0xf5, - 0x29, 0xe2, 0xe3, 0xa3, 0xa6, 0xfc, 0x91, 0x67, 0xca, 0xec, 0x59, 0x7d, 0x7b, 0x34, 0xbd, 0xea, - 0xf6, 0x78, 0x7f, 0xf9, 0xda, 0xd5, 0x32, 0x10, 0x1b, 0x8f, 0x1b, 0x32, 0x93, 0xb9, 0x50, 0x66, - 0xdf, 0x42, 0xf6, 0xc0, 0x6f, 0x63, 0xf2, 0x8c, 0xc7, 0x7b, 0xff, 0x08, 0xf5, 0x03, 0xa8, 0xbf, - 0xee, 0xae, 0x5f, 0x34, 0x07, 0xea, 0xfe, 0xb6, 0x83, 0xdc, 0xe0, 0xe3, 0x3d, 0xa4, 0x17, 0x1c, - 0xc0, 0x82, 0x7f, 0xdc, 0x7b, 0xd8, 0x16, 0x14, 0xed, 0x0a, 0x8a, 0xbe, 0x0b, 0x8a, 0xde, 0x4b, - 0x6a, 0xec, 0x4a, 0x6a, 0x7c, 0x96, 0xd4, 0x78, 0xb9, 0x8d, 0xb9, 0x5a, 0xe6, 0x81, 0x13, 0xca, - 0x95, 0xeb, 0x71, 0x35, 0xab, 0xd6, 0xcc, 0x61, 0x8d, 0x0b, 0xb7, 0xf3, 0xa6, 0x5f, 0x6a, 0x93, - 0x46, 0x59, 0x30, 0x84, 0xfb, 0xb9, 0xfb, 0x09, 0x00, 0x00, 0xff, 0xff, 0x5a, 0x0e, 0x3d, 0x66, - 0x27, 0x02, 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 m.SupplychainCount != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.SupplychainCount)) - i-- - dAtA[i] = 0x28 - } - if len(m.SupplychainList) > 0 { - for iNdEx := len(m.SupplychainList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.SupplychainList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x22 - } - } - if m.TerpidCount != 0 { - i = encodeVarintGenesis(dAtA, i, uint64(m.TerpidCount)) - i-- - dAtA[i] = 0x18 - } - if len(m.TerpidList) > 0 { - for iNdEx := len(m.TerpidList) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.TerpidList[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - } - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenesis(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { - offset -= sovGenesis(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *GenesisState) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovGenesis(uint64(l)) - if len(m.TerpidList) > 0 { - for _, e := range m.TerpidList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if m.TerpidCount != 0 { - n += 1 + sovGenesis(uint64(m.TerpidCount)) - } - if len(m.SupplychainList) > 0 { - for _, e := range m.SupplychainList { - l = e.Size() - n += 1 + l + sovGenesis(uint64(l)) - } - } - if m.SupplychainCount != 0 { - n += 1 + sovGenesis(uint64(m.SupplychainCount)) - } - 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 TerpidList", 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.TerpidList = append(m.TerpidList, Terpid{}) - if err := m.TerpidList[len(m.TerpidList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TerpidCount", wireType) - } - m.TerpidCount = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TerpidCount |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplychainList", 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.SupplychainList = append(m.SupplychainList, Supplychain{}) - if err := m.SupplychainList[len(m.SupplychainList)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field SupplychainCount", wireType) - } - m.SupplychainCount = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenesis - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.SupplychainCount |= 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/terp/types/genesis_test.go b/x/terp/types/genesis_test.go deleted file mode 100644 index 05b313f..0000000 --- a/x/terp/types/genesis_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package types_test - -import ( - "testing" - - "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/x/terp/types" -) - -func TestGenesisState_Validate(t *testing.T) { - for _, tc := range []struct { - desc string - genState *types.GenesisState - valid bool - }{ - { - desc: "default is valid", - genState: types.DefaultGenesis(), - valid: true, - }, - { - desc: "valid genesis state", - genState: &types.GenesisState{ - TerpidList: []types.Terpid{ - { - Id: 0, - }, - { - Id: 1, - }, - }, - TerpidCount: 2, - SupplychainList: []types.Supplychain{ - { - Id: 0, - }, - { - Id: 1, - }, - }, - SupplychainCount: 2, - // this line is used by starport scaffolding # types/genesis/validField - }, - valid: true, - }, - { - desc: "duplicated terpid", - genState: &types.GenesisState{ - TerpidList: []types.Terpid{ - { - Id: 0, - }, - { - Id: 0, - }, - }, - }, - valid: false, - }, - { - desc: "invalid terpid count", - genState: &types.GenesisState{ - TerpidList: []types.Terpid{ - { - Id: 1, - }, - }, - TerpidCount: 0, - }, - valid: false, - }, - { - desc: "duplicated supplychain", - genState: &types.GenesisState{ - SupplychainList: []types.Supplychain{ - { - Id: 0, - }, - { - Id: 0, - }, - }, - }, - valid: false, - }, - { - desc: "invalid supplychain count", - genState: &types.GenesisState{ - SupplychainList: []types.Supplychain{ - { - Id: 1, - }, - }, - SupplychainCount: 0, - }, - valid: false, - }, - // this line is used by starport scaffolding # types/genesis/testcase - } { - t.Run(tc.desc, func(t *testing.T) { - err := tc.genState.Validate() - if tc.valid { - require.NoError(t, err) - } else { - require.Error(t, err) - } - }) - } -} diff --git a/x/terp/types/keys.go b/x/terp/types/keys.go deleted file mode 100644 index 668a90d..0000000 --- a/x/terp/types/keys.go +++ /dev/null @@ -1,32 +0,0 @@ -package types - -const ( - // ModuleName defines the module name - ModuleName = "terp" - - // StoreKey defines the primary module store key - StoreKey = ModuleName - - // RouterKey is the message route for slashing - RouterKey = ModuleName - - // QuerierRoute defines the module's query routing key - QuerierRoute = ModuleName - - // MemStoreKey defines the in-memory store key - MemStoreKey = "mem_terp" -) - -func KeyPrefix(p string) []byte { - return []byte(p) -} - -const ( - TerpidKey = "Terpid-value-" - TerpidCountKey = "Terpid-count-" -) - -const ( - SupplychainKey = "Supplychain-value-" - SupplychainCountKey = "Supplychain-count-" -) diff --git a/x/terp/types/messages_supplychain.go b/x/terp/types/messages_supplychain.go deleted file mode 100644 index 7febe63..0000000 --- a/x/terp/types/messages_supplychain.go +++ /dev/null @@ -1,133 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - TypeMsgCreateSupplychain = "create_supplychain" - TypeMsgUpdateSupplychain = "update_supplychain" - TypeMsgDeleteSupplychain = "delete_supplychain" -) - -var _ sdk.Msg = &MsgCreateSupplychain{} - -func NewMsgCreateSupplychain(creator string, product string, info string, supplyinfo string, supplyextra string) *MsgCreateSupplychain { - return &MsgCreateSupplychain{ - Creator: creator, - Product: product, - Info: info, - Supplyinfo: supplyinfo, - Supplyextra: supplyextra, - } -} - -func (msg *MsgCreateSupplychain) Route() string { - return RouterKey -} - -func (msg *MsgCreateSupplychain) Type() string { - return TypeMsgCreateSupplychain -} - -func (msg *MsgCreateSupplychain) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgCreateSupplychain) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgCreateSupplychain) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) - } - return nil -} - -var _ sdk.Msg = &MsgUpdateSupplychain{} - -func NewMsgUpdateSupplychain(creator string, id uint64, product string, info string, supplyinfo string, supplyextra string) *MsgUpdateSupplychain { - return &MsgUpdateSupplychain{ - Id: id, - Creator: creator, - Product: product, - Info: info, - Supplyinfo: supplyinfo, - Supplyextra: supplyextra, - } -} - -func (msg *MsgUpdateSupplychain) Route() string { - return RouterKey -} - -func (msg *MsgUpdateSupplychain) Type() string { - return TypeMsgUpdateSupplychain -} - -func (msg *MsgUpdateSupplychain) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgUpdateSupplychain) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgUpdateSupplychain) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) - } - return nil -} - -var _ sdk.Msg = &MsgDeleteSupplychain{} - -func NewMsgDeleteSupplychain(creator string, id uint64) *MsgDeleteSupplychain { - return &MsgDeleteSupplychain{ - Id: id, - Creator: creator, - } -} - -func (msg *MsgDeleteSupplychain) Route() string { - return RouterKey -} - -func (msg *MsgDeleteSupplychain) Type() string { - return TypeMsgDeleteSupplychain -} - -func (msg *MsgDeleteSupplychain) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgDeleteSupplychain) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgDeleteSupplychain) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) - } - return nil -} diff --git a/x/terp/types/messages_supplychain_test.go b/x/terp/types/messages_supplychain_test.go deleted file mode 100644 index 4a89349..0000000 --- a/x/terp/types/messages_supplychain_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package types - -import ( - "testing" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/testutil/sample" -) - -func TestMsgCreateSupplychain_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgCreateSupplychain - err error - }{ - { - name: "invalid address", - msg: MsgCreateSupplychain{ - Creator: "invalid_address", - }, - err: sdkerrors.ErrInvalidAddress, - }, { - name: "valid address", - msg: MsgCreateSupplychain{ - Creator: sample.AccAddress(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.msg.ValidateBasic() - if tt.err != nil { - require.ErrorIs(t, err, tt.err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgUpdateSupplychain_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgUpdateSupplychain - err error - }{ - { - name: "invalid address", - msg: MsgUpdateSupplychain{ - Creator: "invalid_address", - }, - err: sdkerrors.ErrInvalidAddress, - }, { - name: "valid address", - msg: MsgUpdateSupplychain{ - Creator: sample.AccAddress(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.msg.ValidateBasic() - if tt.err != nil { - require.ErrorIs(t, err, tt.err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgDeleteSupplychain_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgDeleteSupplychain - err error - }{ - { - name: "invalid address", - msg: MsgDeleteSupplychain{ - Creator: "invalid_address", - }, - err: sdkerrors.ErrInvalidAddress, - }, { - name: "valid address", - msg: MsgDeleteSupplychain{ - Creator: sample.AccAddress(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.msg.ValidateBasic() - if tt.err != nil { - require.ErrorIs(t, err, tt.err) - return - } - require.NoError(t, err) - }) - } -} diff --git a/x/terp/types/messages_terpid.go b/x/terp/types/messages_terpid.go deleted file mode 100644 index b03caf2..0000000 --- a/x/terp/types/messages_terpid.go +++ /dev/null @@ -1,129 +0,0 @@ -package types - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -const ( - TypeMsgCreateTerpid = "create_terpid" - TypeMsgUpdateTerpid = "update_terpid" - TypeMsgDeleteTerpid = "delete_terpid" -) - -var _ sdk.Msg = &MsgCreateTerpid{} - -func NewMsgCreateTerpid(creator string, terpid string, address string) *MsgCreateTerpid { - return &MsgCreateTerpid{ - Creator: creator, - Terpid: terpid, - Address: address, - } -} - -func (msg *MsgCreateTerpid) Route() string { - return RouterKey -} - -func (msg *MsgCreateTerpid) Type() string { - return TypeMsgCreateTerpid -} - -func (msg *MsgCreateTerpid) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgCreateTerpid) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgCreateTerpid) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) - } - return nil -} - -var _ sdk.Msg = &MsgUpdateTerpid{} - -func NewMsgUpdateTerpid(creator string, id uint64, terpid string, address string) *MsgUpdateTerpid { - return &MsgUpdateTerpid{ - Id: id, - Creator: creator, - Terpid: terpid, - Address: address, - } -} - -func (msg *MsgUpdateTerpid) Route() string { - return RouterKey -} - -func (msg *MsgUpdateTerpid) Type() string { - return TypeMsgUpdateTerpid -} - -func (msg *MsgUpdateTerpid) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgUpdateTerpid) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgUpdateTerpid) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) - } - return nil -} - -var _ sdk.Msg = &MsgDeleteTerpid{} - -func NewMsgDeleteTerpid(creator string, id uint64) *MsgDeleteTerpid { - return &MsgDeleteTerpid{ - Id: id, - Creator: creator, - } -} - -func (msg *MsgDeleteTerpid) Route() string { - return RouterKey -} - -func (msg *MsgDeleteTerpid) Type() string { - return TypeMsgDeleteTerpid -} - -func (msg *MsgDeleteTerpid) GetSigners() []sdk.AccAddress { - creator, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - panic(err) - } - return []sdk.AccAddress{creator} -} - -func (msg *MsgDeleteTerpid) GetSignBytes() []byte { - bz := ModuleCdc.MustMarshalJSON(msg) - return sdk.MustSortJSON(bz) -} - -func (msg *MsgDeleteTerpid) ValidateBasic() error { - _, err := sdk.AccAddressFromBech32(msg.Creator) - if err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) - } - return nil -} diff --git a/x/terp/types/messages_terpid_test.go b/x/terp/types/messages_terpid_test.go deleted file mode 100644 index 4de774e..0000000 --- a/x/terp/types/messages_terpid_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package types - -import ( - "testing" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/stretchr/testify/require" - "github.com/terpnetwork/terp-core/testutil/sample" -) - -func TestMsgCreateTerpid_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgCreateTerpid - err error - }{ - { - name: "invalid address", - msg: MsgCreateTerpid{ - Creator: "invalid_address", - }, - err: sdkerrors.ErrInvalidAddress, - }, { - name: "valid address", - msg: MsgCreateTerpid{ - Creator: sample.AccAddress(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.msg.ValidateBasic() - if tt.err != nil { - require.ErrorIs(t, err, tt.err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgUpdateTerpid_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgUpdateTerpid - err error - }{ - { - name: "invalid address", - msg: MsgUpdateTerpid{ - Creator: "invalid_address", - }, - err: sdkerrors.ErrInvalidAddress, - }, { - name: "valid address", - msg: MsgUpdateTerpid{ - Creator: sample.AccAddress(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.msg.ValidateBasic() - if tt.err != nil { - require.ErrorIs(t, err, tt.err) - return - } - require.NoError(t, err) - }) - } -} - -func TestMsgDeleteTerpid_ValidateBasic(t *testing.T) { - tests := []struct { - name string - msg MsgDeleteTerpid - err error - }{ - { - name: "invalid address", - msg: MsgDeleteTerpid{ - Creator: "invalid_address", - }, - err: sdkerrors.ErrInvalidAddress, - }, { - name: "valid address", - msg: MsgDeleteTerpid{ - Creator: sample.AccAddress(), - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - err := tt.msg.ValidateBasic() - if tt.err != nil { - require.ErrorIs(t, err, tt.err) - return - } - require.NoError(t, err) - }) - } -} diff --git a/x/terp/types/params.go b/x/terp/types/params.go deleted file mode 100644 index 357196a..0000000 --- a/x/terp/types/params.go +++ /dev/null @@ -1,39 +0,0 @@ -package types - -import ( - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "gopkg.in/yaml.v2" -) - -var _ paramtypes.ParamSet = (*Params)(nil) - -// ParamKeyTable the param key table for launch module -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - -// NewParams creates a new Params instance -func NewParams() Params { - return Params{} -} - -// DefaultParams returns a default set of parameters -func DefaultParams() Params { - return NewParams() -} - -// ParamSetPairs get the params.ParamSet -func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{} -} - -// Validate validates the set of params -func (p Params) Validate() error { - return nil -} - -// String implements the Stringer interface. -func (p Params) String() string { - out, _ := yaml.Marshal(p) - return string(out) -} diff --git a/x/terp/types/query.pb.go b/x/terp/types/query.pb.go deleted file mode 100644 index bdcd036..0000000 --- a/x/terp/types/query.pb.go +++ /dev/null @@ -1,2272 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: terp/query.proto - -package types - -import ( - context "context" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - query "github.com/cosmos/cosmos-sdk/types/query" - _ "github.com/gogo/protobuf/gogoproto" - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/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 - -// QueryParamsRequest is request type for the Query/Params RPC method. -type QueryParamsRequest struct{} - -func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } -func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } -func (*QueryParamsRequest) ProtoMessage() {} -func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{0} -} - -func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsRequest.Merge(m, src) -} - -func (m *QueryParamsRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryParamsRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo - -// QueryParamsResponse is response type for the Query/Params RPC method. -type QueryParamsResponse struct { - // params holds all the parameters of this module. - Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` -} - -func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } -func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } -func (*QueryParamsResponse) ProtoMessage() {} -func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{1} -} - -func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} - -func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryParamsResponse.Merge(m, src) -} - -func (m *QueryParamsResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryParamsResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo - -func (m *QueryParamsResponse) GetParams() Params { - if m != nil { - return m.Params - } - return Params{} -} - -type QueryGetTerpidRequest struct { - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` -} - -func (m *QueryGetTerpidRequest) Reset() { *m = QueryGetTerpidRequest{} } -func (m *QueryGetTerpidRequest) String() string { return proto.CompactTextString(m) } -func (*QueryGetTerpidRequest) ProtoMessage() {} -func (*QueryGetTerpidRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{2} -} - -func (m *QueryGetTerpidRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryGetTerpidRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryGetTerpidRequest.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 *QueryGetTerpidRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryGetTerpidRequest.Merge(m, src) -} - -func (m *QueryGetTerpidRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryGetTerpidRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryGetTerpidRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryGetTerpidRequest proto.InternalMessageInfo - -func (m *QueryGetTerpidRequest) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -type QueryGetTerpidResponse struct { - Terpid Terpid `protobuf:"bytes,1,opt,name=Terpid,proto3" json:"Terpid"` -} - -func (m *QueryGetTerpidResponse) Reset() { *m = QueryGetTerpidResponse{} } -func (m *QueryGetTerpidResponse) String() string { return proto.CompactTextString(m) } -func (*QueryGetTerpidResponse) ProtoMessage() {} -func (*QueryGetTerpidResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{3} -} - -func (m *QueryGetTerpidResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryGetTerpidResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryGetTerpidResponse.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 *QueryGetTerpidResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryGetTerpidResponse.Merge(m, src) -} - -func (m *QueryGetTerpidResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryGetTerpidResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryGetTerpidResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryGetTerpidResponse proto.InternalMessageInfo - -func (m *QueryGetTerpidResponse) GetTerpid() Terpid { - if m != nil { - return m.Terpid - } - return Terpid{} -} - -type QueryAllTerpidRequest struct { - Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllTerpidRequest) Reset() { *m = QueryAllTerpidRequest{} } -func (m *QueryAllTerpidRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAllTerpidRequest) ProtoMessage() {} -func (*QueryAllTerpidRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{4} -} - -func (m *QueryAllTerpidRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryAllTerpidRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllTerpidRequest.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 *QueryAllTerpidRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllTerpidRequest.Merge(m, src) -} - -func (m *QueryAllTerpidRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryAllTerpidRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllTerpidRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllTerpidRequest proto.InternalMessageInfo - -func (m *QueryAllTerpidRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -type QueryAllTerpidResponse struct { - Terpid []Terpid `protobuf:"bytes,1,rep,name=Terpid,proto3" json:"Terpid"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllTerpidResponse) Reset() { *m = QueryAllTerpidResponse{} } -func (m *QueryAllTerpidResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAllTerpidResponse) ProtoMessage() {} -func (*QueryAllTerpidResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{5} -} - -func (m *QueryAllTerpidResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryAllTerpidResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllTerpidResponse.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 *QueryAllTerpidResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllTerpidResponse.Merge(m, src) -} - -func (m *QueryAllTerpidResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryAllTerpidResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllTerpidResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllTerpidResponse proto.InternalMessageInfo - -func (m *QueryAllTerpidResponse) GetTerpid() []Terpid { - if m != nil { - return m.Terpid - } - return nil -} - -func (m *QueryAllTerpidResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -type QueryGetSupplychainRequest struct { - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` -} - -func (m *QueryGetSupplychainRequest) Reset() { *m = QueryGetSupplychainRequest{} } -func (m *QueryGetSupplychainRequest) String() string { return proto.CompactTextString(m) } -func (*QueryGetSupplychainRequest) ProtoMessage() {} -func (*QueryGetSupplychainRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{6} -} - -func (m *QueryGetSupplychainRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryGetSupplychainRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryGetSupplychainRequest.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 *QueryGetSupplychainRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryGetSupplychainRequest.Merge(m, src) -} - -func (m *QueryGetSupplychainRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryGetSupplychainRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryGetSupplychainRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryGetSupplychainRequest proto.InternalMessageInfo - -func (m *QueryGetSupplychainRequest) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -type QueryGetSupplychainResponse struct { - Supplychain Supplychain `protobuf:"bytes,1,opt,name=Supplychain,proto3" json:"Supplychain"` -} - -func (m *QueryGetSupplychainResponse) Reset() { *m = QueryGetSupplychainResponse{} } -func (m *QueryGetSupplychainResponse) String() string { return proto.CompactTextString(m) } -func (*QueryGetSupplychainResponse) ProtoMessage() {} -func (*QueryGetSupplychainResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{7} -} - -func (m *QueryGetSupplychainResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryGetSupplychainResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryGetSupplychainResponse.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 *QueryGetSupplychainResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryGetSupplychainResponse.Merge(m, src) -} - -func (m *QueryGetSupplychainResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryGetSupplychainResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryGetSupplychainResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryGetSupplychainResponse proto.InternalMessageInfo - -func (m *QueryGetSupplychainResponse) GetSupplychain() Supplychain { - if m != nil { - return m.Supplychain - } - return Supplychain{} -} - -type QueryAllSupplychainRequest struct { - Pagination *query.PageRequest `protobuf:"bytes,1,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllSupplychainRequest) Reset() { *m = QueryAllSupplychainRequest{} } -func (m *QueryAllSupplychainRequest) String() string { return proto.CompactTextString(m) } -func (*QueryAllSupplychainRequest) ProtoMessage() {} -func (*QueryAllSupplychainRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{8} -} - -func (m *QueryAllSupplychainRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryAllSupplychainRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllSupplychainRequest.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 *QueryAllSupplychainRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllSupplychainRequest.Merge(m, src) -} - -func (m *QueryAllSupplychainRequest) XXX_Size() int { - return m.Size() -} - -func (m *QueryAllSupplychainRequest) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllSupplychainRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllSupplychainRequest proto.InternalMessageInfo - -func (m *QueryAllSupplychainRequest) GetPagination() *query.PageRequest { - if m != nil { - return m.Pagination - } - return nil -} - -type QueryAllSupplychainResponse struct { - Supplychain []Supplychain `protobuf:"bytes,1,rep,name=Supplychain,proto3" json:"Supplychain"` - Pagination *query.PageResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` -} - -func (m *QueryAllSupplychainResponse) Reset() { *m = QueryAllSupplychainResponse{} } -func (m *QueryAllSupplychainResponse) String() string { return proto.CompactTextString(m) } -func (*QueryAllSupplychainResponse) ProtoMessage() {} -func (*QueryAllSupplychainResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_be73ff6631d32de0, []int{9} -} - -func (m *QueryAllSupplychainResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *QueryAllSupplychainResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_QueryAllSupplychainResponse.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 *QueryAllSupplychainResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_QueryAllSupplychainResponse.Merge(m, src) -} - -func (m *QueryAllSupplychainResponse) XXX_Size() int { - return m.Size() -} - -func (m *QueryAllSupplychainResponse) XXX_DiscardUnknown() { - xxx_messageInfo_QueryAllSupplychainResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_QueryAllSupplychainResponse proto.InternalMessageInfo - -func (m *QueryAllSupplychainResponse) GetSupplychain() []Supplychain { - if m != nil { - return m.Supplychain - } - return nil -} - -func (m *QueryAllSupplychainResponse) GetPagination() *query.PageResponse { - if m != nil { - return m.Pagination - } - return nil -} - -func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "terpnetwork.terp.terp.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "terpnetwork.terp.terp.QueryParamsResponse") - proto.RegisterType((*QueryGetTerpidRequest)(nil), "terpnetwork.terp.terp.QueryGetTerpidRequest") - proto.RegisterType((*QueryGetTerpidResponse)(nil), "terpnetwork.terp.terp.QueryGetTerpidResponse") - proto.RegisterType((*QueryAllTerpidRequest)(nil), "terpnetwork.terp.terp.QueryAllTerpidRequest") - proto.RegisterType((*QueryAllTerpidResponse)(nil), "terpnetwork.terp.terp.QueryAllTerpidResponse") - proto.RegisterType((*QueryGetSupplychainRequest)(nil), "terpnetwork.terp.terp.QueryGetSupplychainRequest") - proto.RegisterType((*QueryGetSupplychainResponse)(nil), "terpnetwork.terp.terp.QueryGetSupplychainResponse") - proto.RegisterType((*QueryAllSupplychainRequest)(nil), "terpnetwork.terp.terp.QueryAllSupplychainRequest") - proto.RegisterType((*QueryAllSupplychainResponse)(nil), "terpnetwork.terp.terp.QueryAllSupplychainResponse") -} - -func init() { proto.RegisterFile("terp/query.proto", fileDescriptor_be73ff6631d32de0) } - -var fileDescriptor_be73ff6631d32de0 = []byte{ - // 625 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x95, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0xc7, 0xb3, 0x69, 0xc9, 0x61, 0x2b, 0x2a, 0x58, 0x0a, 0x2a, 0x06, 0x99, 0x68, 0xd5, 0x2f, - 0x9a, 0xd4, 0x56, 0x52, 0xb8, 0x22, 0x35, 0x08, 0x22, 0x21, 0x21, 0x95, 0x20, 0x2e, 0xdc, 0xd6, - 0x8e, 0xe5, 0xac, 0xe4, 0x78, 0xdd, 0xd8, 0x41, 0x44, 0x88, 0x0b, 0x2f, 0x00, 0x12, 0x2f, 0x81, - 0x10, 0x42, 0xe2, 0xc0, 0x3b, 0xf4, 0x58, 0xc4, 0x85, 0x13, 0x42, 0x09, 0x0f, 0x82, 0xbc, 0x3b, - 0xc5, 0x4e, 0x63, 0x2b, 0xee, 0xc7, 0x25, 0x89, 0x26, 0xf3, 0x9f, 0xf9, 0xcd, 0xcc, 0xee, 0x2c, - 0xbe, 0x62, 0xd9, 0x3e, 0x33, 0x0f, 0x86, 0xce, 0x60, 0x64, 0x04, 0x03, 0x11, 0x09, 0xb2, 0x6a, - 0xf1, 0xc8, 0x66, 0xbe, 0xcf, 0x5c, 0x4f, 0x58, 0xcc, 0x33, 0x62, 0x07, 0xf9, 0xa1, 0xad, 0xb8, - 0xc2, 0x15, 0xd2, 0xc9, 0x8c, 0x7f, 0x29, 0x7f, 0xed, 0xb6, 0x2b, 0x84, 0xeb, 0x39, 0x26, 0x0b, - 0xb8, 0xc9, 0x7c, 0x5f, 0x44, 0x2c, 0xe2, 0xc2, 0x0f, 0xe1, 0xdf, 0x6d, 0x5b, 0x84, 0x7d, 0x11, - 0x9a, 0x16, 0x0b, 0x1d, 0x95, 0xc6, 0x7c, 0xd5, 0xb0, 0x9c, 0x88, 0x35, 0xcc, 0x80, 0xb9, 0xdc, - 0x97, 0xce, 0xe0, 0x7b, 0x55, 0xb2, 0x04, 0x6c, 0xc0, 0xfa, 0xc7, 0xf2, 0xeb, 0xd2, 0x74, 0x4c, - 0xc4, 0xbb, 0x60, 0xbe, 0x21, 0xcd, 0xe1, 0x30, 0x08, 0xbc, 0x91, 0xdd, 0x63, 0x1c, 0x22, 0xd0, - 0x15, 0x4c, 0x9e, 0xc5, 0x39, 0xf6, 0x65, 0x8c, 0x8e, 0x73, 0x30, 0x74, 0xc2, 0x88, 0xbe, 0xc0, - 0xd7, 0xa6, 0xac, 0x61, 0x20, 0xfc, 0xd0, 0x21, 0x0f, 0x70, 0x45, 0xe5, 0x5a, 0x45, 0x55, 0xb4, - 0xb5, 0xd4, 0xac, 0x1a, 0x79, 0x95, 0x1b, 0x4a, 0xd9, 0x5a, 0x3c, 0xfc, 0x7d, 0xa7, 0xd4, 0x01, - 0x15, 0xad, 0xe1, 0x9b, 0x32, 0x6c, 0xdb, 0x89, 0x5a, 0xff, 0x01, 0x21, 0x27, 0x59, 0xc6, 0x65, - 0xde, 0x95, 0x81, 0x17, 0x3b, 0x65, 0xde, 0xa5, 0x3d, 0xac, 0x65, 0x39, 0x03, 0xca, 0x13, 0x8c, - 0x13, 0x2b, 0xe0, 0xac, 0xe5, 0xe3, 0x24, 0xbe, 0x80, 0x94, 0x52, 0x53, 0x1b, 0xb0, 0xf6, 0x3c, - 0x6f, 0x16, 0xeb, 0x31, 0xc6, 0x49, 0xdb, 0x21, 0xd1, 0x86, 0xa1, 0x66, 0x64, 0xc4, 0x33, 0x32, - 0xd4, 0x51, 0x80, 0x19, 0x19, 0xfb, 0xcc, 0x75, 0x40, 0xdb, 0x49, 0x29, 0xe9, 0x37, 0x04, 0xf5, - 0x9c, 0xc8, 0x92, 0x53, 0xcf, 0xc2, 0xd9, 0xeb, 0x21, 0xed, 0x29, 0xe4, 0xb2, 0x44, 0xde, 0x9c, - 0x8b, 0xac, 0x40, 0xa6, 0x98, 0xeb, 0xc9, 0x08, 0x9e, 0x27, 0x27, 0x27, 0x6f, 0x60, 0x1e, 0xbe, - 0x95, 0xe9, 0x0d, 0x15, 0x3e, 0xc5, 0x4b, 0x29, 0x33, 0x74, 0x72, 0x3d, 0xbf, 0xc4, 0x94, 0x33, - 0xd4, 0x98, 0xd6, 0xd3, 0x6e, 0xd2, 0xce, 0x0c, 0xb6, 0x8b, 0x9a, 0xda, 0x77, 0x04, 0x45, 0x9d, - 0x4c, 0x93, 0x57, 0xd4, 0xc2, 0x79, 0x8a, 0xba, 0xb0, 0xc9, 0x35, 0x7f, 0x54, 0xf0, 0x25, 0xc9, - 0x4d, 0xde, 0x23, 0x5c, 0x51, 0x97, 0x91, 0xd4, 0xf3, 0xb9, 0x66, 0x77, 0x80, 0xb6, 0x53, 0xd0, - 0x5b, 0x65, 0xa7, 0x5b, 0xef, 0x7e, 0xfe, 0xfd, 0x58, 0xa6, 0xa4, 0x6a, 0xb6, 0x78, 0xf4, 0x30, - 0x96, 0xb5, 0xa5, 0xcc, 0x54, 0xfb, 0x28, 0xd9, 0x53, 0xe4, 0x33, 0x4a, 0x9f, 0x75, 0xb2, 0x3b, - 0x27, 0x4f, 0xd6, 0xb2, 0xd0, 0xee, 0x9d, 0x4e, 0x04, 0x8c, 0x0d, 0xc9, 0x58, 0x23, 0x77, 0xf3, - 0x19, 0x93, 0xc5, 0x69, 0xbe, 0xe1, 0xdd, 0xb7, 0xe4, 0x13, 0xc2, 0x97, 0x93, 0x48, 0x7b, 0x9e, - 0x37, 0x97, 0x37, 0x6b, 0x8b, 0xcc, 0xe5, 0xcd, 0x5c, 0x0a, 0xb4, 0x2e, 0x79, 0x37, 0xc8, 0x5a, - 0x11, 0x5e, 0xf2, 0x15, 0x4d, 0x1d, 0x46, 0x52, 0xa0, 0x47, 0xb3, 0x37, 0x47, 0xbb, 0x7f, 0x4a, - 0x15, 0xa0, 0x36, 0x25, 0x6a, 0x9d, 0x6c, 0xe7, 0xa3, 0xa6, 0x1e, 0x1f, 0xd5, 0xdb, 0x2f, 0x08, - 0x2f, 0xa7, 0x62, 0xc5, 0xcd, 0x2d, 0xd0, 0xa7, 0x33, 0x30, 0x67, 0x5f, 0x5e, 0xba, 0x23, 0x99, - 0x37, 0xc9, 0x7a, 0x21, 0xe6, 0xd6, 0xa3, 0xc3, 0xb1, 0x8e, 0x8e, 0xc6, 0x3a, 0xfa, 0x33, 0xd6, - 0xd1, 0x87, 0x89, 0x5e, 0x3a, 0x9a, 0xe8, 0xa5, 0x5f, 0x13, 0xbd, 0xf4, 0xb2, 0xe6, 0xf2, 0xa8, - 0x37, 0xb4, 0x0c, 0x5b, 0xf4, 0x33, 0x43, 0xbd, 0x56, 0x5f, 0xd1, 0x28, 0x70, 0x42, 0xab, 0x22, - 0x1f, 0xde, 0xdd, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xce, 0x62, 0x98, 0x0f, 0x48, 0x08, 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 - -// QueryClient is the client API for Query service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type QueryClient interface { - // Parameters queries the parameters of the module. - Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) - // Queries a Terpid by id. - Terpid(ctx context.Context, in *QueryGetTerpidRequest, opts ...grpc.CallOption) (*QueryGetTerpidResponse, error) - // Queries a list of Terpid items. - TerpidAll(ctx context.Context, in *QueryAllTerpidRequest, opts ...grpc.CallOption) (*QueryAllTerpidResponse, error) - // Queries a Supplychain by id. - Supplychain(ctx context.Context, in *QueryGetSupplychainRequest, opts ...grpc.CallOption) (*QueryGetSupplychainResponse, error) - // Queries a list of Supplychain items. - SupplychainAll(ctx context.Context, in *QueryAllSupplychainRequest, opts ...grpc.CallOption) (*QueryAllSupplychainResponse, error) -} - -type queryClient struct { - cc grpc1.ClientConn -} - -func NewQueryClient(cc grpc1.ClientConn) QueryClient { - return &queryClient{cc} -} - -func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { - out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Query/Params", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Terpid(ctx context.Context, in *QueryGetTerpidRequest, opts ...grpc.CallOption) (*QueryGetTerpidResponse, error) { - out := new(QueryGetTerpidResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Query/Terpid", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) TerpidAll(ctx context.Context, in *QueryAllTerpidRequest, opts ...grpc.CallOption) (*QueryAllTerpidResponse, error) { - out := new(QueryAllTerpidResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Query/TerpidAll", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) Supplychain(ctx context.Context, in *QueryGetSupplychainRequest, opts ...grpc.CallOption) (*QueryGetSupplychainResponse, error) { - out := new(QueryGetSupplychainResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Query/Supplychain", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *queryClient) SupplychainAll(ctx context.Context, in *QueryAllSupplychainRequest, opts ...grpc.CallOption) (*QueryAllSupplychainResponse, error) { - out := new(QueryAllSupplychainResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Query/SupplychainAll", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// QueryServer is the server API for Query service. -type QueryServer interface { - // Parameters queries the parameters of the module. - Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) - // Queries a Terpid by id. - Terpid(context.Context, *QueryGetTerpidRequest) (*QueryGetTerpidResponse, error) - // Queries a list of Terpid items. - TerpidAll(context.Context, *QueryAllTerpidRequest) (*QueryAllTerpidResponse, error) - // Queries a Supplychain by id. - Supplychain(context.Context, *QueryGetSupplychainRequest) (*QueryGetSupplychainResponse, error) - // Queries a list of Supplychain items. - SupplychainAll(context.Context, *QueryAllSupplychainRequest) (*QueryAllSupplychainResponse, error) -} - -// UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct{} - -func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") -} - -func (*UnimplementedQueryServer) Terpid(ctx context.Context, req *QueryGetTerpidRequest) (*QueryGetTerpidResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Terpid not implemented") -} - -func (*UnimplementedQueryServer) TerpidAll(ctx context.Context, req *QueryAllTerpidRequest) (*QueryAllTerpidResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method TerpidAll not implemented") -} - -func (*UnimplementedQueryServer) Supplychain(ctx context.Context, req *QueryGetSupplychainRequest) (*QueryGetSupplychainResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Supplychain not implemented") -} - -func (*UnimplementedQueryServer) SupplychainAll(ctx context.Context, req *QueryAllSupplychainRequest) (*QueryAllSupplychainResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method SupplychainAll not implemented") -} - -func RegisterQueryServer(s grpc1.Server, srv QueryServer) { - s.RegisterService(&_Query_serviceDesc, srv) -} - -func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryParamsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Params(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.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_Terpid_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryGetTerpidRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Terpid(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Query/Terpid", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Terpid(ctx, req.(*QueryGetTerpidRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_TerpidAll_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAllTerpidRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).TerpidAll(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Query/TerpidAll", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).TerpidAll(ctx, req.(*QueryAllTerpidRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_Supplychain_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryGetSupplychainRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).Supplychain(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Query/Supplychain", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).Supplychain(ctx, req.(*QueryGetSupplychainRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _Query_SupplychainAll_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryAllSupplychainRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(QueryServer).SupplychainAll(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Query/SupplychainAll", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(QueryServer).SupplychainAll(ctx, req.(*QueryAllSupplychainRequest)) - } - return interceptor(ctx, in, info, handler) -} - -var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "terpnetwork.terp.terp.Query", - HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Params", - Handler: _Query_Params_Handler, - }, - { - MethodName: "Terpid", - Handler: _Query_Terpid_Handler, - }, - { - MethodName: "TerpidAll", - Handler: _Query_TerpidAll_Handler, - }, - { - MethodName: "Supplychain", - Handler: _Query_Supplychain_Handler, - }, - { - MethodName: "SupplychainAll", - Handler: _Query_SupplychainAll_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "terp/query.proto", -} - -func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *QueryGetTerpidRequest) 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 *QueryGetTerpidRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryGetTerpidRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Id != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryGetTerpidResponse) 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 *QueryGetTerpidResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryGetTerpidResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Terpid.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 *QueryAllTerpidRequest) 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 *QueryAllTerpidRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllTerpidRequest) 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 *QueryAllTerpidResponse) 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 *QueryAllTerpidResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllTerpidResponse) 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.Terpid) > 0 { - for iNdEx := len(m.Terpid) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Terpid[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 *QueryGetSupplychainRequest) 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 *QueryGetSupplychainRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryGetSupplychainRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Id != 0 { - i = encodeVarintQuery(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *QueryGetSupplychainResponse) 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 *QueryGetSupplychainResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryGetSupplychainResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - { - size, err := m.Supplychain.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 *QueryAllSupplychainRequest) 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 *QueryAllSupplychainRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllSupplychainRequest) 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 *QueryAllSupplychainResponse) 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 *QueryAllSupplychainResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *QueryAllSupplychainResponse) 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.Supplychain) > 0 { - for iNdEx := len(m.Supplychain) - 1; iNdEx >= 0; iNdEx-- { - { - size, err := m.Supplychain[iNdEx].MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintQuery(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - } - return len(dAtA) - i, nil -} - -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryGetTerpidRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Id != 0 { - n += 1 + sovQuery(uint64(m.Id)) - } - return n -} - -func (m *QueryGetTerpidResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Terpid.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryAllTerpidRequest) 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 *QueryAllTerpidResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Terpid) > 0 { - for _, e := range m.Terpid { - 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 *QueryGetSupplychainRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Id != 0 { - n += 1 + sovQuery(uint64(m.Id)) - } - return n -} - -func (m *QueryGetSupplychainResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = m.Supplychain.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} - -func (m *QueryAllSupplychainRequest) 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 *QueryAllSupplychainResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Supplychain) > 0 { - for _, e := range m.Supplychain { - l = e.Size() - n += 1 + l + sovQuery(uint64(l)) - } - } - if m.Pagination != nil { - l = m.Pagination.Size() - n += 1 + l + sovQuery(uint64(l)) - } - return n -} - -func sovQuery(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozQuery(x uint64) (n int) { - return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *QueryGetTerpidRequest) 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: QueryGetTerpidRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryGetTerpidRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= 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 *QueryGetTerpidResponse) 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: QueryGetTerpidResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryGetTerpidResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Terpid", 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.Terpid.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 *QueryAllTerpidRequest) 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: QueryAllTerpidRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllTerpidRequest: 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 *QueryAllTerpidResponse) 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: QueryAllTerpidResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllTerpidResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Terpid", 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.Terpid = append(m.Terpid, Terpid{}) - if err := m.Terpid[len(m.Terpid)-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 *QueryGetSupplychainRequest) 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: QueryGetSupplychainRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryGetSupplychainRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= 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 *QueryGetSupplychainResponse) 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: QueryGetSupplychainResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryGetSupplychainResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplychain", 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.Supplychain.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 *QueryAllSupplychainRequest) 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: QueryAllSupplychainRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllSupplychainRequest: 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 *QueryAllSupplychainResponse) 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: QueryAllSupplychainResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: QueryAllSupplychainResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplychain", 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.Supplychain = append(m.Supplychain, Supplychain{}) - if err := m.Supplychain[len(m.Supplychain)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagination", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowQuery - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthQuery - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthQuery - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pagination == nil { - m.Pagination = &query.PageResponse{} - } - if err := m.Pagination.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipQuery(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthQuery - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipQuery(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowQuery - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthQuery - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupQuery - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthQuery - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/terp/types/query.pb.gw.go b/x/terp/types/query.pb.gw.go deleted file mode 100644 index 96dbe75..0000000 --- a/x/terp/types/query.pb.gw.go +++ /dev/null @@ -1,497 +0,0 @@ -// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: terp/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_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryParamsRequest - var metadata runtime.ServerMetadata - - msg, err := server.Params(ctx, &protoReq) - return msg, metadata, err -} - -func request_Query_Terpid_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryGetTerpidRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - msg, err := client.Terpid(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_Terpid_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryGetTerpidRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - msg, err := server.Terpid(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_TerpidAll_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} - -func request_Query_TerpidAll_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllTerpidRequest - 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_TerpidAll_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.TerpidAll(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_TerpidAll_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllTerpidRequest - 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_TerpidAll_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.TerpidAll(ctx, &protoReq) - return msg, metadata, err -} - -func request_Query_Supplychain_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryGetSupplychainRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - msg, err := client.Supplychain(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_Supplychain_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryGetSupplychainRequest - var metadata runtime.ServerMetadata - - var ( - val string - ok bool - err error - _ = err - ) - - val, ok = pathParams["id"] - if !ok { - return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "id") - } - - protoReq.Id, err = runtime.Uint64(val) - - if err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "id", err) - } - - msg, err := server.Supplychain(ctx, &protoReq) - return msg, metadata, err -} - -var filter_Query_SupplychainAll_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} - -func request_Query_SupplychainAll_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllSupplychainRequest - 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_SupplychainAll_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := client.SupplychainAll(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) - return msg, metadata, err -} - -func local_request_Query_SupplychainAll_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { - var protoReq QueryAllSupplychainRequest - 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_SupplychainAll_0); err != nil { - return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) - } - - msg, err := server.SupplychainAll(ctx, &protoReq) - return msg, metadata, err -} - -// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". -// UnaryRPC :call QueryServer directly. -// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. -// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. -func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - var stream runtime.ServerTransportStream - ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) - md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Terpid_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_Terpid_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_Terpid_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_TerpidAll_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_TerpidAll_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_TerpidAll_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Supplychain_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_Supplychain_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_Supplychain_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_SupplychainAll_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_SupplychainAll_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_SupplychainAll_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - return nil -} - -// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but -// automatically dials to "endpoint" and closes the connection when "ctx" gets done. -func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { - conn, err := grpc.Dial(endpoint, opts...) - if err != nil { - return err - } - defer func() { - if err != nil { - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - return - } - go func() { - <-ctx.Done() - if cerr := conn.Close(); cerr != nil { - grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) - } - }() - }() - - return RegisterQueryHandler(ctx, mux, conn) -} - -// RegisterQueryHandler registers the http handlers for service Query to "mux". -// The handlers forward requests to the grpc endpoint over "conn". -func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { - return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) -} - -// RegisterQueryHandlerClient registers the http handlers for service Query -// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". -// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" -// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in -// "QueryClient" to call the correct interceptors. -func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { - mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { - ctx, cancel := context.WithCancel(req.Context()) - defer cancel() - inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) - rctx, err := runtime.AnnotateContext(ctx, mux, req) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) - ctx = runtime.NewServerMetadataContext(ctx, md) - if err != nil { - runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) - return - } - - forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Terpid_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_Terpid_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_Terpid_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_TerpidAll_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_TerpidAll_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_TerpidAll_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_Supplychain_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_Supplychain_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_Supplychain_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - mux.Handle("GET", pattern_Query_SupplychainAll_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_SupplychainAll_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_SupplychainAll_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) - - return nil -} - -var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 1, 2, 2}, []string{"BitCannaGlobal", "terp", "params"}, "", runtime.AssumeColonVerbOpt(true))) - - pattern_Query_Terpid_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"BitCannaGlobal", "terp", "terpid", "id"}, "", runtime.AssumeColonVerbOpt(true))) - - pattern_Query_TerpidAll_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 1, 2, 2}, []string{"BitCannaGlobal", "terp", "terpid"}, "", runtime.AssumeColonVerbOpt(true))) - - pattern_Query_Supplychain_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"BitCannaGlobal", "terp", "supplychain", "id"}, "", runtime.AssumeColonVerbOpt(true))) - - pattern_Query_SupplychainAll_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 1, 2, 2}, []string{"BitCannaGlobal", "terp", "supplychain"}, "", runtime.AssumeColonVerbOpt(true))) -) - -var ( - forward_Query_Params_0 = runtime.ForwardResponseMessage - - forward_Query_Terpid_0 = runtime.ForwardResponseMessage - - forward_Query_TerpidAll_0 = runtime.ForwardResponseMessage - - forward_Query_Supplychain_0 = runtime.ForwardResponseMessage - - forward_Query_SupplychainAll_0 = runtime.ForwardResponseMessage -) diff --git a/x/terp/types/supplychain.pb.go b/x/terp/types/supplychain.pb.go deleted file mode 100644 index 7e6c3ff..0000000 --- a/x/terp/types/supplychain.pb.go +++ /dev/null @@ -1,570 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: terp/supplychain.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - proto "github.com/gogo/protobuf/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 - -type Supplychain struct { - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Product string `protobuf:"bytes,2,opt,name=product,proto3" json:"product,omitempty"` - Info string `protobuf:"bytes,3,opt,name=info,proto3" json:"info,omitempty"` - Supplyinfo string `protobuf:"bytes,4,opt,name=supplyinfo,proto3" json:"supplyinfo,omitempty"` - Supplyextra string `protobuf:"bytes,5,opt,name=supplyextra,proto3" json:"supplyextra,omitempty"` - Creator string `protobuf:"bytes,6,opt,name=creator,proto3" json:"creator,omitempty"` -} - -func (m *Supplychain) Reset() { *m = Supplychain{} } -func (m *Supplychain) String() string { return proto.CompactTextString(m) } -func (*Supplychain) ProtoMessage() {} -func (*Supplychain) Descriptor() ([]byte, []int) { - return fileDescriptor_b6988f475c438d71, []int{0} -} - -func (m *Supplychain) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Supplychain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Supplychain.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 *Supplychain) XXX_Merge(src proto.Message) { - xxx_messageInfo_Supplychain.Merge(m, src) -} - -func (m *Supplychain) XXX_Size() int { - return m.Size() -} - -func (m *Supplychain) XXX_DiscardUnknown() { - xxx_messageInfo_Supplychain.DiscardUnknown(m) -} - -var xxx_messageInfo_Supplychain proto.InternalMessageInfo - -func (m *Supplychain) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -func (m *Supplychain) GetProduct() string { - if m != nil { - return m.Product - } - return "" -} - -func (m *Supplychain) GetInfo() string { - if m != nil { - return m.Info - } - return "" -} - -func (m *Supplychain) GetSupplyinfo() string { - if m != nil { - return m.Supplyinfo - } - return "" -} - -func (m *Supplychain) GetSupplyextra() string { - if m != nil { - return m.Supplyextra - } - return "" -} - -func (m *Supplychain) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func init() { - proto.RegisterType((*Supplychain)(nil), "terpnetwork.terp.terp.Supplychain") -} - -func init() { proto.RegisterFile("terp/supplychain.proto", fileDescriptor_b6988f475c438d71) } - -var fileDescriptor_b6988f475c438d71 = []byte{ - // 237 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4b, 0x4a, 0xce, 0x4b, - 0xd4, 0x2f, 0x2e, 0x2d, 0x28, 0xc8, 0xa9, 0x4c, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2b, 0x28, 0xca, - 0x2f, 0xc9, 0x17, 0x92, 0x48, 0xca, 0x2c, 0x49, 0x4e, 0xcc, 0xcb, 0x4b, 0x4c, 0xcf, 0xc9, 0x4f, - 0x4a, 0xcc, 0xd1, 0x03, 0x29, 0x03, 0x13, 0x4a, 0xcb, 0x19, 0xb9, 0xb8, 0x83, 0x11, 0xea, 0x85, - 0xf8, 0xb8, 0x98, 0x32, 0x53, 0x24, 0x18, 0x15, 0x18, 0x35, 0x58, 0x82, 0x98, 0x32, 0x53, 0x84, - 0x24, 0xb8, 0xd8, 0x0b, 0x8a, 0xf2, 0x53, 0x4a, 0x93, 0x4b, 0x24, 0x98, 0x14, 0x18, 0x35, 0x38, - 0x83, 0x60, 0x5c, 0x21, 0x21, 0x2e, 0x96, 0xcc, 0xbc, 0xb4, 0x7c, 0x09, 0x66, 0xb0, 0x30, 0x98, - 0x2d, 0x24, 0xc7, 0xc5, 0x05, 0xb1, 0x1c, 0x2c, 0xc3, 0x02, 0x96, 0x41, 0x12, 0x11, 0x52, 0xe0, - 0xe2, 0x86, 0xf0, 0x52, 0x2b, 0x4a, 0x8a, 0x12, 0x25, 0x58, 0xc1, 0x0a, 0x90, 0x85, 0x40, 0xf6, - 0x25, 0x17, 0xa5, 0x26, 0x96, 0xe4, 0x17, 0x49, 0xb0, 0x41, 0xec, 0x83, 0x72, 0x9d, 0x5c, 0x4f, - 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, - 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x3b, 0x3d, 0xb3, 0x24, 0xa3, 0x34, - 0x49, 0x2f, 0x39, 0x3f, 0x57, 0xdf, 0x29, 0xb3, 0xc4, 0x19, 0xe4, 0x51, 0x77, 0xb0, 0x47, 0xf5, - 0xc1, 0xe1, 0x51, 0x01, 0xa1, 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0x21, 0x62, 0x0c, - 0x08, 0x00, 0x00, 0xff, 0xff, 0x7b, 0x6d, 0x15, 0xc9, 0x2b, 0x01, 0x00, 0x00, -} - -func (m *Supplychain) 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 *Supplychain) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Supplychain) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintSupplychain(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0x32 - } - if len(m.Supplyextra) > 0 { - i -= len(m.Supplyextra) - copy(dAtA[i:], m.Supplyextra) - i = encodeVarintSupplychain(dAtA, i, uint64(len(m.Supplyextra))) - i-- - dAtA[i] = 0x2a - } - if len(m.Supplyinfo) > 0 { - i -= len(m.Supplyinfo) - copy(dAtA[i:], m.Supplyinfo) - i = encodeVarintSupplychain(dAtA, i, uint64(len(m.Supplyinfo))) - i-- - dAtA[i] = 0x22 - } - if len(m.Info) > 0 { - i -= len(m.Info) - copy(dAtA[i:], m.Info) - i = encodeVarintSupplychain(dAtA, i, uint64(len(m.Info))) - i-- - dAtA[i] = 0x1a - } - if len(m.Product) > 0 { - i -= len(m.Product) - copy(dAtA[i:], m.Product) - i = encodeVarintSupplychain(dAtA, i, uint64(len(m.Product))) - i-- - dAtA[i] = 0x12 - } - if m.Id != 0 { - i = encodeVarintSupplychain(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintSupplychain(dAtA []byte, offset int, v uint64) int { - offset -= sovSupplychain(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *Supplychain) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Id != 0 { - n += 1 + sovSupplychain(uint64(m.Id)) - } - l = len(m.Product) - if l > 0 { - n += 1 + l + sovSupplychain(uint64(l)) - } - l = len(m.Info) - if l > 0 { - n += 1 + l + sovSupplychain(uint64(l)) - } - l = len(m.Supplyinfo) - if l > 0 { - n += 1 + l + sovSupplychain(uint64(l)) - } - l = len(m.Supplyextra) - if l > 0 { - n += 1 + l + sovSupplychain(uint64(l)) - } - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovSupplychain(uint64(l)) - } - return n -} - -func sovSupplychain(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozSupplychain(x uint64) (n int) { - return sovSupplychain(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *Supplychain) 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 ErrIntOverflowSupplychain - } - 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: Supplychain: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Supplychain: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSupplychain - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Product", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSupplychain - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSupplychain - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSupplychain - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Product = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Info", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSupplychain - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSupplychain - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSupplychain - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Info = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplyinfo", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSupplychain - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSupplychain - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSupplychain - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Supplyinfo = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplyextra", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowSupplychain - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSupplychain - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSupplychain - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Supplyextra = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - 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 ErrIntOverflowSupplychain - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthSupplychain - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthSupplychain - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipSupplychain(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthSupplychain - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipSupplychain(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, ErrIntOverflowSupplychain - } - 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, ErrIntOverflowSupplychain - } - 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, ErrIntOverflowSupplychain - } - 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, ErrInvalidLengthSupplychain - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupSupplychain - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthSupplychain - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthSupplychain = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowSupplychain = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupSupplychain = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/terp/types/terpid.pb.go b/x/terp/types/terpid.pb.go deleted file mode 100644 index d1f78fe..0000000 --- a/x/terp/types/terpid.pb.go +++ /dev/null @@ -1,466 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: terp/terpid.proto - -package types - -import ( - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - proto "github.com/gogo/protobuf/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 - -type Terpid struct { - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - Terpid string `protobuf:"bytes,2,opt,name=terpid,proto3" json:"terpid,omitempty"` - Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` - Creator string `protobuf:"bytes,4,opt,name=creator,proto3" json:"creator,omitempty"` -} - -func (m *Terpid) Reset() { *m = Terpid{} } -func (m *Terpid) String() string { return proto.CompactTextString(m) } -func (*Terpid) ProtoMessage() {} -func (*Terpid) Descriptor() ([]byte, []int) { - return fileDescriptor_4b4053733ed2336d, []int{0} -} - -func (m *Terpid) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *Terpid) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Terpid.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 *Terpid) XXX_Merge(src proto.Message) { - xxx_messageInfo_Terpid.Merge(m, src) -} - -func (m *Terpid) XXX_Size() int { - return m.Size() -} - -func (m *Terpid) XXX_DiscardUnknown() { - xxx_messageInfo_Terpid.DiscardUnknown(m) -} - -var xxx_messageInfo_Terpid proto.InternalMessageInfo - -func (m *Terpid) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -func (m *Terpid) GetTerpid() string { - if m != nil { - return m.Terpid - } - return "" -} - -func (m *Terpid) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -func (m *Terpid) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func init() { - proto.RegisterType((*Terpid)(nil), "terpnetwork.terp.terp.Terpid") -} - -func init() { proto.RegisterFile("terp/terpid.proto", fileDescriptor_4b4053733ed2336d) } - -var fileDescriptor_4b4053733ed2336d = []byte{ - // 199 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4d, 0x4a, 0xce, 0x4b, - 0xd4, 0x4f, 0xca, 0x2c, 0x49, 0x4e, 0xcc, 0xcb, 0x4b, 0xcc, 0x4c, 0xd1, 0x2b, 0x28, 0xca, 0x2f, - 0xc9, 0x17, 0x92, 0x80, 0x89, 0xa4, 0xe7, 0xe4, 0x27, 0x25, 0xe6, 0xe8, 0x81, 0x54, 0x81, 0x09, - 0xa5, 0x0c, 0x2e, 0x2e, 0x27, 0xb8, 0x6a, 0x21, 0x3e, 0x2e, 0xa6, 0xcc, 0x14, 0x09, 0x46, 0x05, - 0x46, 0x0d, 0x96, 0x20, 0xa6, 0xcc, 0x14, 0x21, 0x31, 0x2e, 0x36, 0x90, 0xaa, 0xcc, 0x14, 0x09, - 0x26, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x28, 0x4f, 0x48, 0x82, 0x8b, 0x3d, 0x31, 0x25, 0xa5, 0x28, - 0xb5, 0xb8, 0x58, 0x82, 0x19, 0x2c, 0x01, 0xe3, 0x82, 0x64, 0x92, 0x8b, 0x52, 0x13, 0x4b, 0xf2, - 0x8b, 0x24, 0x58, 0x20, 0x32, 0x50, 0xae, 0x93, 0xeb, 0x89, 0x47, 0x72, 0x8c, 0x17, 0x1e, 0xc9, - 0x31, 0x3e, 0x78, 0x24, 0xc7, 0x38, 0xe1, 0xb1, 0x1c, 0xc3, 0x85, 0xc7, 0x72, 0x0c, 0x37, 0x1e, - 0xcb, 0x31, 0x44, 0x69, 0xa7, 0x67, 0x96, 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x3b, - 0x65, 0x96, 0x38, 0x83, 0x1c, 0xe3, 0x0e, 0x76, 0xa8, 0x3e, 0xd8, 0x3b, 0x15, 0x10, 0xaa, 0xa4, - 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0xec, 0x23, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x27, - 0x38, 0xc9, 0x73, 0xea, 0x00, 0x00, 0x00, -} - -func (m *Terpid) 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 *Terpid) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *Terpid) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTerpid(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0x22 - } - if len(m.Address) > 0 { - i -= len(m.Address) - copy(dAtA[i:], m.Address) - i = encodeVarintTerpid(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0x1a - } - if len(m.Terpid) > 0 { - i -= len(m.Terpid) - copy(dAtA[i:], m.Terpid) - i = encodeVarintTerpid(dAtA, i, uint64(len(m.Terpid))) - i-- - dAtA[i] = 0x12 - } - if m.Id != 0 { - i = encodeVarintTerpid(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func encodeVarintTerpid(dAtA []byte, offset int, v uint64) int { - offset -= sovTerpid(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} - -func (m *Terpid) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Id != 0 { - n += 1 + sovTerpid(uint64(m.Id)) - } - l = len(m.Terpid) - if l > 0 { - n += 1 + l + sovTerpid(uint64(l)) - } - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTerpid(uint64(l)) - } - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTerpid(uint64(l)) - } - return n -} - -func sovTerpid(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} - -func sozTerpid(x uint64) (n int) { - return sovTerpid(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -func (m *Terpid) 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 ErrIntOverflowTerpid - } - 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: Terpid: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Terpid: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTerpid - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Terpid", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTerpid - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTerpid - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTerpid - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Terpid = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - 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 ErrIntOverflowTerpid - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTerpid - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTerpid - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Address = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - 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 ErrIntOverflowTerpid - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTerpid - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTerpid - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipTerpid(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTerpid - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func skipTerpid(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, ErrIntOverflowTerpid - } - 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, ErrIntOverflowTerpid - } - 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, ErrIntOverflowTerpid - } - 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, ErrInvalidLengthTerpid - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupTerpid - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthTerpid - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthTerpid = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowTerpid = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupTerpid = fmt.Errorf("proto: unexpected end of group") -) diff --git a/x/terp/types/tx.pb.go b/x/terp/types/tx.pb.go deleted file mode 100644 index 15c31dc..0000000 --- a/x/terp/types/tx.pb.go +++ /dev/null @@ -1,3067 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: terp/tx.proto - -package types - -import ( - context "context" - fmt "fmt" - io "io" - math "math" - math_bits "math/bits" - - grpc1 "github.com/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/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 - -type MsgCreateTerpid struct { - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - Terpid string `protobuf:"bytes,2,opt,name=terpid,proto3" json:"terpid,omitempty"` - Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` -} - -func (m *MsgCreateTerpid) Reset() { *m = MsgCreateTerpid{} } -func (m *MsgCreateTerpid) String() string { return proto.CompactTextString(m) } -func (*MsgCreateTerpid) ProtoMessage() {} -func (*MsgCreateTerpid) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{0} -} - -func (m *MsgCreateTerpid) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgCreateTerpid) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateTerpid.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 *MsgCreateTerpid) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateTerpid.Merge(m, src) -} - -func (m *MsgCreateTerpid) XXX_Size() int { - return m.Size() -} - -func (m *MsgCreateTerpid) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateTerpid.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateTerpid proto.InternalMessageInfo - -func (m *MsgCreateTerpid) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func (m *MsgCreateTerpid) GetTerpid() string { - if m != nil { - return m.Terpid - } - return "" -} - -func (m *MsgCreateTerpid) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -type MsgCreateTerpidResponse struct { - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` -} - -func (m *MsgCreateTerpidResponse) Reset() { *m = MsgCreateTerpidResponse{} } -func (m *MsgCreateTerpidResponse) String() string { return proto.CompactTextString(m) } -func (*MsgCreateTerpidResponse) ProtoMessage() {} -func (*MsgCreateTerpidResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{1} -} - -func (m *MsgCreateTerpidResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgCreateTerpidResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateTerpidResponse.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 *MsgCreateTerpidResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateTerpidResponse.Merge(m, src) -} - -func (m *MsgCreateTerpidResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgCreateTerpidResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateTerpidResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateTerpidResponse proto.InternalMessageInfo - -func (m *MsgCreateTerpidResponse) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -type MsgUpdateTerpid struct { - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - Id uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` - Terpid string `protobuf:"bytes,3,opt,name=terpid,proto3" json:"terpid,omitempty"` - Address string `protobuf:"bytes,4,opt,name=address,proto3" json:"address,omitempty"` -} - -func (m *MsgUpdateTerpid) Reset() { *m = MsgUpdateTerpid{} } -func (m *MsgUpdateTerpid) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateTerpid) ProtoMessage() {} -func (*MsgUpdateTerpid) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{2} -} - -func (m *MsgUpdateTerpid) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateTerpid) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateTerpid.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 *MsgUpdateTerpid) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateTerpid.Merge(m, src) -} - -func (m *MsgUpdateTerpid) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateTerpid) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateTerpid.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateTerpid proto.InternalMessageInfo - -func (m *MsgUpdateTerpid) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func (m *MsgUpdateTerpid) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -func (m *MsgUpdateTerpid) GetTerpid() string { - if m != nil { - return m.Terpid - } - return "" -} - -func (m *MsgUpdateTerpid) GetAddress() string { - if m != nil { - return m.Address - } - return "" -} - -type MsgUpdateTerpidResponse struct{} - -func (m *MsgUpdateTerpidResponse) Reset() { *m = MsgUpdateTerpidResponse{} } -func (m *MsgUpdateTerpidResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateTerpidResponse) ProtoMessage() {} -func (*MsgUpdateTerpidResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{3} -} - -func (m *MsgUpdateTerpidResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateTerpidResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateTerpidResponse.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 *MsgUpdateTerpidResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateTerpidResponse.Merge(m, src) -} - -func (m *MsgUpdateTerpidResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateTerpidResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateTerpidResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateTerpidResponse proto.InternalMessageInfo - -type MsgDeleteTerpid struct { - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - Id uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` -} - -func (m *MsgDeleteTerpid) Reset() { *m = MsgDeleteTerpid{} } -func (m *MsgDeleteTerpid) String() string { return proto.CompactTextString(m) } -func (*MsgDeleteTerpid) ProtoMessage() {} -func (*MsgDeleteTerpid) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{4} -} - -func (m *MsgDeleteTerpid) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgDeleteTerpid) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeleteTerpid.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 *MsgDeleteTerpid) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeleteTerpid.Merge(m, src) -} - -func (m *MsgDeleteTerpid) XXX_Size() int { - return m.Size() -} - -func (m *MsgDeleteTerpid) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeleteTerpid.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeleteTerpid proto.InternalMessageInfo - -func (m *MsgDeleteTerpid) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func (m *MsgDeleteTerpid) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -type MsgDeleteTerpidResponse struct{} - -func (m *MsgDeleteTerpidResponse) Reset() { *m = MsgDeleteTerpidResponse{} } -func (m *MsgDeleteTerpidResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDeleteTerpidResponse) ProtoMessage() {} -func (*MsgDeleteTerpidResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{5} -} - -func (m *MsgDeleteTerpidResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgDeleteTerpidResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeleteTerpidResponse.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 *MsgDeleteTerpidResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeleteTerpidResponse.Merge(m, src) -} - -func (m *MsgDeleteTerpidResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgDeleteTerpidResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeleteTerpidResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeleteTerpidResponse proto.InternalMessageInfo - -type MsgCreateSupplychain struct { - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - Product string `protobuf:"bytes,2,opt,name=product,proto3" json:"product,omitempty"` - Info string `protobuf:"bytes,3,opt,name=info,proto3" json:"info,omitempty"` - Supplyinfo string `protobuf:"bytes,4,opt,name=supplyinfo,proto3" json:"supplyinfo,omitempty"` - Supplyextra string `protobuf:"bytes,5,opt,name=supplyextra,proto3" json:"supplyextra,omitempty"` -} - -func (m *MsgCreateSupplychain) Reset() { *m = MsgCreateSupplychain{} } -func (m *MsgCreateSupplychain) String() string { return proto.CompactTextString(m) } -func (*MsgCreateSupplychain) ProtoMessage() {} -func (*MsgCreateSupplychain) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{6} -} - -func (m *MsgCreateSupplychain) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgCreateSupplychain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateSupplychain.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 *MsgCreateSupplychain) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateSupplychain.Merge(m, src) -} - -func (m *MsgCreateSupplychain) XXX_Size() int { - return m.Size() -} - -func (m *MsgCreateSupplychain) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateSupplychain.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateSupplychain proto.InternalMessageInfo - -func (m *MsgCreateSupplychain) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func (m *MsgCreateSupplychain) GetProduct() string { - if m != nil { - return m.Product - } - return "" -} - -func (m *MsgCreateSupplychain) GetInfo() string { - if m != nil { - return m.Info - } - return "" -} - -func (m *MsgCreateSupplychain) GetSupplyinfo() string { - if m != nil { - return m.Supplyinfo - } - return "" -} - -func (m *MsgCreateSupplychain) GetSupplyextra() string { - if m != nil { - return m.Supplyextra - } - return "" -} - -type MsgCreateSupplychainResponse struct { - Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` -} - -func (m *MsgCreateSupplychainResponse) Reset() { *m = MsgCreateSupplychainResponse{} } -func (m *MsgCreateSupplychainResponse) String() string { return proto.CompactTextString(m) } -func (*MsgCreateSupplychainResponse) ProtoMessage() {} -func (*MsgCreateSupplychainResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{7} -} - -func (m *MsgCreateSupplychainResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgCreateSupplychainResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgCreateSupplychainResponse.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 *MsgCreateSupplychainResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgCreateSupplychainResponse.Merge(m, src) -} - -func (m *MsgCreateSupplychainResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgCreateSupplychainResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgCreateSupplychainResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgCreateSupplychainResponse proto.InternalMessageInfo - -func (m *MsgCreateSupplychainResponse) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -type MsgUpdateSupplychain struct { - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - Id uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` - Product string `protobuf:"bytes,3,opt,name=product,proto3" json:"product,omitempty"` - Info string `protobuf:"bytes,4,opt,name=info,proto3" json:"info,omitempty"` - Supplyinfo string `protobuf:"bytes,5,opt,name=supplyinfo,proto3" json:"supplyinfo,omitempty"` - Supplyextra string `protobuf:"bytes,6,opt,name=supplyextra,proto3" json:"supplyextra,omitempty"` -} - -func (m *MsgUpdateSupplychain) Reset() { *m = MsgUpdateSupplychain{} } -func (m *MsgUpdateSupplychain) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateSupplychain) ProtoMessage() {} -func (*MsgUpdateSupplychain) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{8} -} - -func (m *MsgUpdateSupplychain) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateSupplychain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateSupplychain.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 *MsgUpdateSupplychain) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateSupplychain.Merge(m, src) -} - -func (m *MsgUpdateSupplychain) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateSupplychain) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateSupplychain.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateSupplychain proto.InternalMessageInfo - -func (m *MsgUpdateSupplychain) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func (m *MsgUpdateSupplychain) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -func (m *MsgUpdateSupplychain) GetProduct() string { - if m != nil { - return m.Product - } - return "" -} - -func (m *MsgUpdateSupplychain) GetInfo() string { - if m != nil { - return m.Info - } - return "" -} - -func (m *MsgUpdateSupplychain) GetSupplyinfo() string { - if m != nil { - return m.Supplyinfo - } - return "" -} - -func (m *MsgUpdateSupplychain) GetSupplyextra() string { - if m != nil { - return m.Supplyextra - } - return "" -} - -type MsgUpdateSupplychainResponse struct{} - -func (m *MsgUpdateSupplychainResponse) Reset() { *m = MsgUpdateSupplychainResponse{} } -func (m *MsgUpdateSupplychainResponse) String() string { return proto.CompactTextString(m) } -func (*MsgUpdateSupplychainResponse) ProtoMessage() {} -func (*MsgUpdateSupplychainResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{9} -} - -func (m *MsgUpdateSupplychainResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgUpdateSupplychainResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgUpdateSupplychainResponse.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 *MsgUpdateSupplychainResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgUpdateSupplychainResponse.Merge(m, src) -} - -func (m *MsgUpdateSupplychainResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgUpdateSupplychainResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgUpdateSupplychainResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgUpdateSupplychainResponse proto.InternalMessageInfo - -type MsgDeleteSupplychain struct { - Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` - Id uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` -} - -func (m *MsgDeleteSupplychain) Reset() { *m = MsgDeleteSupplychain{} } -func (m *MsgDeleteSupplychain) String() string { return proto.CompactTextString(m) } -func (*MsgDeleteSupplychain) ProtoMessage() {} -func (*MsgDeleteSupplychain) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{10} -} - -func (m *MsgDeleteSupplychain) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgDeleteSupplychain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeleteSupplychain.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 *MsgDeleteSupplychain) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeleteSupplychain.Merge(m, src) -} - -func (m *MsgDeleteSupplychain) XXX_Size() int { - return m.Size() -} - -func (m *MsgDeleteSupplychain) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeleteSupplychain.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeleteSupplychain proto.InternalMessageInfo - -func (m *MsgDeleteSupplychain) GetCreator() string { - if m != nil { - return m.Creator - } - return "" -} - -func (m *MsgDeleteSupplychain) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -type MsgDeleteSupplychainResponse struct{} - -func (m *MsgDeleteSupplychainResponse) Reset() { *m = MsgDeleteSupplychainResponse{} } -func (m *MsgDeleteSupplychainResponse) String() string { return proto.CompactTextString(m) } -func (*MsgDeleteSupplychainResponse) ProtoMessage() {} -func (*MsgDeleteSupplychainResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_12d2bc8ae8552a21, []int{11} -} - -func (m *MsgDeleteSupplychainResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} - -func (m *MsgDeleteSupplychainResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MsgDeleteSupplychainResponse.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 *MsgDeleteSupplychainResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_MsgDeleteSupplychainResponse.Merge(m, src) -} - -func (m *MsgDeleteSupplychainResponse) XXX_Size() int { - return m.Size() -} - -func (m *MsgDeleteSupplychainResponse) XXX_DiscardUnknown() { - xxx_messageInfo_MsgDeleteSupplychainResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_MsgDeleteSupplychainResponse proto.InternalMessageInfo - -func init() { - proto.RegisterType((*MsgCreateTerpid)(nil), "terpnetwork.terp.terp.MsgCreateTerpid") - proto.RegisterType((*MsgCreateTerpidResponse)(nil), "terpnetwork.terp.terp.MsgCreateTerpidResponse") - proto.RegisterType((*MsgUpdateTerpid)(nil), "terpnetwork.terp.terp.MsgUpdateTerpid") - proto.RegisterType((*MsgUpdateTerpidResponse)(nil), "terpnetwork.terp.terp.MsgUpdateTerpidResponse") - proto.RegisterType((*MsgDeleteTerpid)(nil), "terpnetwork.terp.terp.MsgDeleteTerpid") - proto.RegisterType((*MsgDeleteTerpidResponse)(nil), "terpnetwork.terp.terp.MsgDeleteTerpidResponse") - proto.RegisterType((*MsgCreateSupplychain)(nil), "terpnetwork.terp.terp.MsgCreateSupplychain") - proto.RegisterType((*MsgCreateSupplychainResponse)(nil), "terpnetwork.terp.terp.MsgCreateSupplychainResponse") - proto.RegisterType((*MsgUpdateSupplychain)(nil), "terpnetwork.terp.terp.MsgUpdateSupplychain") - proto.RegisterType((*MsgUpdateSupplychainResponse)(nil), "terpnetwork.terp.terp.MsgUpdateSupplychainResponse") - proto.RegisterType((*MsgDeleteSupplychain)(nil), "terpnetwork.terp.terp.MsgDeleteSupplychain") - proto.RegisterType((*MsgDeleteSupplychainResponse)(nil), "terpnetwork.terp.terp.MsgDeleteSupplychainResponse") -} - -func init() { proto.RegisterFile("terp/tx.proto", fileDescriptor_12d2bc8ae8552a21) } - -var fileDescriptor_12d2bc8ae8552a21 = []byte{ - // 511 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x55, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0x8e, 0xf3, 0x57, 0x31, 0x08, 0x54, 0x16, 0xa8, 0xac, 0x00, 0x56, 0xe5, 0x13, 0x12, 0xea, - 0x46, 0x02, 0xc1, 0x15, 0x94, 0x82, 0x38, 0xf5, 0x12, 0xc4, 0x85, 0xdb, 0xda, 0x5e, 0xd2, 0x95, - 0x82, 0x6d, 0xbc, 0x1b, 0xc9, 0x15, 0x2f, 0xc1, 0x23, 0xf0, 0x08, 0x3c, 0x06, 0xc7, 0x1e, 0x39, - 0xa2, 0xe4, 0xc6, 0x53, 0x20, 0xcf, 0xda, 0xc6, 0xf5, 0x66, 0x13, 0xb7, 0x97, 0x36, 0x33, 0x3b, - 0x3b, 0xdf, 0xf7, 0xcd, 0xec, 0x27, 0xc3, 0x9d, 0x20, 0x8c, 0xd9, 0x54, 0xe5, 0x34, 0xcd, 0x12, - 0x95, 0x10, 0x37, 0x10, 0x2a, 0x64, 0x71, 0xcc, 0x16, 0xcb, 0x24, 0x60, 0x4b, 0x5a, 0x9c, 0xe2, - 0x9f, 0xc9, 0x43, 0x2c, 0xac, 0x8e, 0x45, 0xa4, 0x2f, 0x4c, 0x8e, 0x30, 0x2d, 0x57, 0x69, 0xba, - 0xbc, 0x08, 0xcf, 0x99, 0x88, 0x75, 0xde, 0x67, 0x70, 0xff, 0x4c, 0x2e, 0x4e, 0x33, 0xce, 0x14, - 0x9f, 0xd5, 0x97, 0x88, 0x0b, 0x07, 0x61, 0x91, 0x4b, 0x32, 0xd7, 0x39, 0x76, 0x9e, 0xde, 0x9a, - 0x57, 0x21, 0x39, 0x82, 0x71, 0xd1, 0x4a, 0x44, 0x6e, 0x1f, 0x0f, 0xca, 0xa8, 0xb8, 0xc1, 0xa2, - 0x28, 0xe3, 0x52, 0xba, 0x03, 0x7d, 0xa3, 0x0c, 0xfd, 0x13, 0x78, 0xb4, 0x05, 0x62, 0xce, 0x65, - 0x9a, 0xc4, 0x92, 0x93, 0xbb, 0xd0, 0x17, 0x11, 0xa2, 0x0c, 0xe7, 0x7d, 0x11, 0xf9, 0x5f, 0x91, - 0xd1, 0xc7, 0x34, 0xea, 0xca, 0x48, 0x37, 0xe8, 0x57, 0x0d, 0x1a, 0x0c, 0x07, 0x36, 0x86, 0xc3, - 0xab, 0x0c, 0x9f, 0x20, 0xc3, 0x36, 0x64, 0xc5, 0xd0, 0x7f, 0x8d, 0x8c, 0xde, 0xf2, 0x25, 0xbf, - 0x19, 0xa3, 0xb2, 0x7f, 0xbb, 0x41, 0xdd, 0xff, 0x87, 0x03, 0x0f, 0xea, 0x09, 0x7d, 0xf8, 0xbf, - 0xa2, 0x1d, 0x08, 0x2e, 0x1c, 0xa4, 0x59, 0x12, 0xad, 0x42, 0x55, 0xae, 0xa1, 0x0a, 0x09, 0x81, - 0xa1, 0x88, 0x3f, 0x27, 0xa5, 0x76, 0xfc, 0x4d, 0x3c, 0x00, 0xbd, 0x79, 0x3c, 0xd1, 0xe2, 0x1b, - 0x19, 0x72, 0x0c, 0xb7, 0x75, 0xc4, 0x73, 0x95, 0x31, 0x77, 0x84, 0x05, 0xcd, 0x94, 0x4f, 0xe1, - 0xf1, 0x36, 0x86, 0xd6, 0x25, 0xfe, 0xd4, 0x92, 0xf4, 0x48, 0xbb, 0x49, 0x6a, 0xaf, 0xb1, 0x21, - 0x71, 0xb0, 0x5d, 0xe2, 0xd0, 0x2a, 0x71, 0xb4, 0x4f, 0xe2, 0xd8, 0x94, 0xe8, 0xa1, 0x44, 0x83, - 0x71, 0xbd, 0xa5, 0x37, 0xa8, 0x48, 0x2f, 0xf1, 0x46, 0x8a, 0x4a, 0x04, 0xa3, 0x43, 0x85, 0xf0, - 0xfc, 0xef, 0x08, 0x06, 0x67, 0x72, 0x41, 0x72, 0x38, 0x34, 0x0c, 0x79, 0x42, 0x6d, 0x8e, 0xa7, - 0x5b, 0xcc, 0x35, 0x79, 0x79, 0xad, 0xf2, 0x7a, 0x8d, 0x39, 0x1c, 0x1a, 0xc6, 0xdb, 0x8d, 0xdc, - 0x2e, 0xdf, 0x83, 0x6c, 0xf3, 0x58, 0x81, 0x6c, 0x18, 0x6c, 0x37, 0x72, 0xbb, 0x7c, 0x0f, 0xb2, - 0xcd, 0x7d, 0xe4, 0x1b, 0xdc, 0x33, 0x9d, 0x47, 0x3b, 0xcc, 0xaf, 0x51, 0x3f, 0x79, 0x75, 0xbd, - 0xfa, 0x26, 0xb8, 0xe9, 0x11, 0xda, 0x61, 0x84, 0xdd, 0xc1, 0xad, 0x2f, 0xba, 0x00, 0x37, 0x9f, - 0x33, 0xed, 0x30, 0xc5, 0xee, 0xe0, 0xd6, 0xc7, 0x3e, 0x7b, 0xf7, 0x6b, 0xed, 0x39, 0x97, 0x6b, - 0xcf, 0xf9, 0xb3, 0xf6, 0x9c, 0xef, 0x1b, 0xaf, 0x77, 0xb9, 0xf1, 0x7a, 0xbf, 0x37, 0x5e, 0xef, - 0xd3, 0xb3, 0x85, 0x50, 0xe7, 0xab, 0x80, 0x86, 0xc9, 0x97, 0xe9, 0x4c, 0xa8, 0xd3, 0xa2, 0xf7, - 0x7b, 0xec, 0x3d, 0xc5, 0x8f, 0x58, 0xae, 0xff, 0xa9, 0x8b, 0x94, 0xcb, 0x60, 0x8c, 0x9f, 0xb1, - 0x17, 0xff, 0x02, 0x00, 0x00, 0xff, 0xff, 0x7d, 0x44, 0x0d, 0x1c, 0x20, 0x07, 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 { - CreateTerpid(ctx context.Context, in *MsgCreateTerpid, opts ...grpc.CallOption) (*MsgCreateTerpidResponse, error) - UpdateTerpid(ctx context.Context, in *MsgUpdateTerpid, opts ...grpc.CallOption) (*MsgUpdateTerpidResponse, error) - DeleteTerpid(ctx context.Context, in *MsgDeleteTerpid, opts ...grpc.CallOption) (*MsgDeleteTerpidResponse, error) - CreateSupplychain(ctx context.Context, in *MsgCreateSupplychain, opts ...grpc.CallOption) (*MsgCreateSupplychainResponse, error) - UpdateSupplychain(ctx context.Context, in *MsgUpdateSupplychain, opts ...grpc.CallOption) (*MsgUpdateSupplychainResponse, error) - DeleteSupplychain(ctx context.Context, in *MsgDeleteSupplychain, opts ...grpc.CallOption) (*MsgDeleteSupplychainResponse, error) -} - -type msgClient struct { - cc grpc1.ClientConn -} - -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} -} - -func (c *msgClient) CreateTerpid(ctx context.Context, in *MsgCreateTerpid, opts ...grpc.CallOption) (*MsgCreateTerpidResponse, error) { - out := new(MsgCreateTerpidResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Msg/CreateTerpid", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateTerpid(ctx context.Context, in *MsgUpdateTerpid, opts ...grpc.CallOption) (*MsgUpdateTerpidResponse, error) { - out := new(MsgUpdateTerpidResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Msg/UpdateTerpid", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) DeleteTerpid(ctx context.Context, in *MsgDeleteTerpid, opts ...grpc.CallOption) (*MsgDeleteTerpidResponse, error) { - out := new(MsgDeleteTerpidResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Msg/DeleteTerpid", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) CreateSupplychain(ctx context.Context, in *MsgCreateSupplychain, opts ...grpc.CallOption) (*MsgCreateSupplychainResponse, error) { - out := new(MsgCreateSupplychainResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Msg/CreateSupplychain", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) UpdateSupplychain(ctx context.Context, in *MsgUpdateSupplychain, opts ...grpc.CallOption) (*MsgUpdateSupplychainResponse, error) { - out := new(MsgUpdateSupplychainResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Msg/UpdateSupplychain", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *msgClient) DeleteSupplychain(ctx context.Context, in *MsgDeleteSupplychain, opts ...grpc.CallOption) (*MsgDeleteSupplychainResponse, error) { - out := new(MsgDeleteSupplychainResponse) - err := c.cc.Invoke(ctx, "/terpnetwork.terp.terp.Msg/DeleteSupplychain", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// MsgServer is the server API for Msg service. -type MsgServer interface { - CreateTerpid(context.Context, *MsgCreateTerpid) (*MsgCreateTerpidResponse, error) - UpdateTerpid(context.Context, *MsgUpdateTerpid) (*MsgUpdateTerpidResponse, error) - DeleteTerpid(context.Context, *MsgDeleteTerpid) (*MsgDeleteTerpidResponse, error) - CreateSupplychain(context.Context, *MsgCreateSupplychain) (*MsgCreateSupplychainResponse, error) - UpdateSupplychain(context.Context, *MsgUpdateSupplychain) (*MsgUpdateSupplychainResponse, error) - DeleteSupplychain(context.Context, *MsgDeleteSupplychain) (*MsgDeleteSupplychainResponse, error) -} - -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct{} - -func (*UnimplementedMsgServer) CreateTerpid(ctx context.Context, req *MsgCreateTerpid) (*MsgCreateTerpidResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateTerpid not implemented") -} - -func (*UnimplementedMsgServer) UpdateTerpid(ctx context.Context, req *MsgUpdateTerpid) (*MsgUpdateTerpidResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateTerpid not implemented") -} - -func (*UnimplementedMsgServer) DeleteTerpid(ctx context.Context, req *MsgDeleteTerpid) (*MsgDeleteTerpidResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DeleteTerpid not implemented") -} - -func (*UnimplementedMsgServer) CreateSupplychain(ctx context.Context, req *MsgCreateSupplychain) (*MsgCreateSupplychainResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateSupplychain not implemented") -} - -func (*UnimplementedMsgServer) UpdateSupplychain(ctx context.Context, req *MsgUpdateSupplychain) (*MsgUpdateSupplychainResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateSupplychain not implemented") -} - -func (*UnimplementedMsgServer) DeleteSupplychain(ctx context.Context, req *MsgDeleteSupplychain) (*MsgDeleteSupplychainResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DeleteSupplychain not implemented") -} - -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) -} - -func _Msg_CreateTerpid_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgCreateTerpid) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).CreateTerpid(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Msg/CreateTerpid", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).CreateTerpid(ctx, req.(*MsgCreateTerpid)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateTerpid_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateTerpid) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateTerpid(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Msg/UpdateTerpid", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateTerpid(ctx, req.(*MsgUpdateTerpid)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_DeleteTerpid_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeleteTerpid) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).DeleteTerpid(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Msg/DeleteTerpid", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).DeleteTerpid(ctx, req.(*MsgDeleteTerpid)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_CreateSupplychain_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgCreateSupplychain) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).CreateSupplychain(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Msg/CreateSupplychain", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).CreateSupplychain(ctx, req.(*MsgCreateSupplychain)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_UpdateSupplychain_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgUpdateSupplychain) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).UpdateSupplychain(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Msg/UpdateSupplychain", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).UpdateSupplychain(ctx, req.(*MsgUpdateSupplychain)) - } - return interceptor(ctx, in, info, handler) -} - -func _Msg_DeleteSupplychain_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(MsgDeleteSupplychain) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(MsgServer).DeleteSupplychain(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/terpnetwork.terp.terp.Msg/DeleteSupplychain", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(MsgServer).DeleteSupplychain(ctx, req.(*MsgDeleteSupplychain)) - } - return interceptor(ctx, in, info, handler) -} - -var _Msg_serviceDesc = grpc.ServiceDesc{ - ServiceName: "terpnetwork.terp.terp.Msg", - HandlerType: (*MsgServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "CreateTerpid", - Handler: _Msg_CreateTerpid_Handler, - }, - { - MethodName: "UpdateTerpid", - Handler: _Msg_UpdateTerpid_Handler, - }, - { - MethodName: "DeleteTerpid", - Handler: _Msg_DeleteTerpid_Handler, - }, - { - MethodName: "CreateSupplychain", - Handler: _Msg_CreateSupplychain_Handler, - }, - { - MethodName: "UpdateSupplychain", - Handler: _Msg_UpdateSupplychain_Handler, - }, - { - MethodName: "DeleteSupplychain", - Handler: _Msg_DeleteSupplychain_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "terp/tx.proto", -} - -func (m *MsgCreateTerpid) 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 *MsgCreateTerpid) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateTerpid) 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 = encodeVarintTx(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0x1a - } - if len(m.Terpid) > 0 { - i -= len(m.Terpid) - copy(dAtA[i:], m.Terpid) - i = encodeVarintTx(dAtA, i, uint64(len(m.Terpid))) - i-- - dAtA[i] = 0x12 - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgCreateTerpidResponse) 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 *MsgCreateTerpidResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateTerpidResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Id != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateTerpid) 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 *MsgUpdateTerpid) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateTerpid) 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 = encodeVarintTx(dAtA, i, uint64(len(m.Address))) - i-- - dAtA[i] = 0x22 - } - if len(m.Terpid) > 0 { - i -= len(m.Terpid) - copy(dAtA[i:], m.Terpid) - i = encodeVarintTx(dAtA, i, uint64(len(m.Terpid))) - i-- - dAtA[i] = 0x1a - } - if m.Id != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x10 - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateTerpidResponse) 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 *MsgUpdateTerpidResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateTerpidResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgDeleteTerpid) 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 *MsgDeleteTerpid) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeleteTerpid) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Id != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x10 - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDeleteTerpidResponse) 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 *MsgDeleteTerpidResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeleteTerpidResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgCreateSupplychain) 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 *MsgCreateSupplychain) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateSupplychain) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Supplyextra) > 0 { - i -= len(m.Supplyextra) - copy(dAtA[i:], m.Supplyextra) - i = encodeVarintTx(dAtA, i, uint64(len(m.Supplyextra))) - i-- - dAtA[i] = 0x2a - } - if len(m.Supplyinfo) > 0 { - i -= len(m.Supplyinfo) - copy(dAtA[i:], m.Supplyinfo) - i = encodeVarintTx(dAtA, i, uint64(len(m.Supplyinfo))) - i-- - dAtA[i] = 0x22 - } - if len(m.Info) > 0 { - i -= len(m.Info) - copy(dAtA[i:], m.Info) - i = encodeVarintTx(dAtA, i, uint64(len(m.Info))) - i-- - dAtA[i] = 0x1a - } - if len(m.Product) > 0 { - i -= len(m.Product) - copy(dAtA[i:], m.Product) - i = encodeVarintTx(dAtA, i, uint64(len(m.Product))) - i-- - dAtA[i] = 0x12 - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgCreateSupplychainResponse) 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 *MsgCreateSupplychainResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgCreateSupplychainResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Id != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x8 - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateSupplychain) 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 *MsgUpdateSupplychain) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateSupplychain) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Supplyextra) > 0 { - i -= len(m.Supplyextra) - copy(dAtA[i:], m.Supplyextra) - i = encodeVarintTx(dAtA, i, uint64(len(m.Supplyextra))) - i-- - dAtA[i] = 0x32 - } - if len(m.Supplyinfo) > 0 { - i -= len(m.Supplyinfo) - copy(dAtA[i:], m.Supplyinfo) - i = encodeVarintTx(dAtA, i, uint64(len(m.Supplyinfo))) - i-- - dAtA[i] = 0x2a - } - if len(m.Info) > 0 { - i -= len(m.Info) - copy(dAtA[i:], m.Info) - i = encodeVarintTx(dAtA, i, uint64(len(m.Info))) - i-- - dAtA[i] = 0x22 - } - if len(m.Product) > 0 { - i -= len(m.Product) - copy(dAtA[i:], m.Product) - i = encodeVarintTx(dAtA, i, uint64(len(m.Product))) - i-- - dAtA[i] = 0x1a - } - if m.Id != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x10 - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgUpdateSupplychainResponse) 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 *MsgUpdateSupplychainResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgUpdateSupplychainResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil -} - -func (m *MsgDeleteSupplychain) 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 *MsgDeleteSupplychain) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeleteSupplychain) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Id != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.Id)) - i-- - dAtA[i] = 0x10 - } - if len(m.Creator) > 0 { - i -= len(m.Creator) - copy(dAtA[i:], m.Creator) - i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func (m *MsgDeleteSupplychainResponse) 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 *MsgDeleteSupplychainResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *MsgDeleteSupplychainResponse) 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 *MsgCreateTerpid) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Terpid) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgCreateTerpidResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Id != 0 { - n += 1 + sovTx(uint64(m.Id)) - } - return n -} - -func (m *MsgUpdateTerpid) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.Id != 0 { - n += 1 + sovTx(uint64(m.Id)) - } - l = len(m.Terpid) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgUpdateTerpidResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgDeleteTerpid) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.Id != 0 { - n += 1 + sovTx(uint64(m.Id)) - } - return n -} - -func (m *MsgDeleteTerpidResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgCreateSupplychain) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Product) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Info) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Supplyinfo) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Supplyextra) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgCreateSupplychainResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Id != 0 { - n += 1 + sovTx(uint64(m.Id)) - } - return n -} - -func (m *MsgUpdateSupplychain) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.Id != 0 { - n += 1 + sovTx(uint64(m.Id)) - } - l = len(m.Product) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Info) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Supplyinfo) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - l = len(m.Supplyextra) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - return n -} - -func (m *MsgUpdateSupplychainResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n -} - -func (m *MsgDeleteSupplychain) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Creator) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) - } - if m.Id != 0 { - n += 1 + sovTx(uint64(m.Id)) - } - return n -} - -func (m *MsgDeleteSupplychainResponse) 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 *MsgCreateTerpid) 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: MsgCreateTerpid: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateTerpid: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Terpid", 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.Terpid = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - 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 - 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 *MsgCreateTerpidResponse) 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: MsgCreateTerpidResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateTerpidResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateTerpid) 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: MsgUpdateTerpid: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateTerpid: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Terpid", 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.Terpid = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - 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 - 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 *MsgUpdateTerpidResponse) 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: MsgUpdateTerpidResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateTerpidResponse: 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 *MsgDeleteTerpid) 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: MsgDeleteTerpid: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeleteTerpid: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgDeleteTerpidResponse) 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: MsgDeleteTerpidResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeleteTerpidResponse: 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 *MsgCreateSupplychain) 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: MsgCreateSupplychain: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateSupplychain: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Product", 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.Product = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Info", 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.Info = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplyinfo", 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.Supplyinfo = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplyextra", 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.Supplyextra = 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 *MsgCreateSupplychainResponse) 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: MsgCreateSupplychainResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgCreateSupplychainResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgUpdateSupplychain) 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: MsgUpdateSupplychain: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateSupplychain: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Product", 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.Product = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Info", 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.Info = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplyinfo", 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.Supplyinfo = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Supplyextra", 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.Supplyextra = 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 *MsgUpdateSupplychainResponse) 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: MsgUpdateSupplychainResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgUpdateSupplychainResponse: 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 *MsgDeleteSupplychain) 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: MsgDeleteSupplychain: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeleteSupplychain: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTx - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTx - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Creator = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) - } - m.Id = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Id |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipTx(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} - -func (m *MsgDeleteSupplychainResponse) 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: MsgDeleteSupplychainResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgDeleteSupplychainResponse: 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/terp/types/types.go b/x/terp/types/types.go deleted file mode 100644 index ab1254f..0000000 --- a/x/terp/types/types.go +++ /dev/null @@ -1 +0,0 @@ -package types diff --git a/x/tokenfactory/README.md b/x/tokenfactory/README.md new file mode 100644 index 0000000..7d6644e --- /dev/null +++ b/x/tokenfactory/README.md @@ -0,0 +1,155 @@ +# Token Factory + +The tokenfactory module allows any account to create a new token with +the name `factory/{creator address}/{subdenom}`. Because tokens are +namespaced by creator address, this allows token minting to be +permissionless, due to not needing to resolve name collisions. A single +account can create multiple denoms, by providing a unique subdenom for each +created denom. Once a denom is created, the original creator is given +"admin" privileges over the asset. This allows them to: + +- Mint their denom to any account +- Burn their denom from any account +- Create a transfer of their denom between any two accounts +- Change the admin. In the future, more admin capabilities may be added. Admins + can choose to share admin privileges with other accounts using the authz + module. The `ChangeAdmin` functionality, allows changing the master admin + account, or even setting it to `""`, meaning no account has admin privileges + of the asset. + +## Messages + +### CreateDenom + +Creates a denom of `factory/{creator address}/{subdenom}` given the denom creator +address and the subdenom. Subdenoms can contain `[a-zA-Z0-9./]`. + +```go +message MsgCreateDenom { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + string subdenom = 2 [ (gogoproto.moretags) = "yaml:\"subdenom\"" ]; +} +``` + +**State Modifications:** + +- Fund community pool with the denom creation fee from the creator address, set + in `Params`. +- Set `DenomMetaData` via bank keeper. +- Set `AuthorityMetadata` for the given denom to store the admin for the created + denom `factory/{creator address}/{subdenom}`. Admin is automatically set as the + Msg sender. +- Add denom to the `CreatorPrefixStore`, where a state of denoms created per + creator is kept. + +### Mint + +Minting of a specific denom is only allowed for the current admin. +Note, the current admin is defaulted to the creator of the denom. + +```go +message MsgMint { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + cosmos.base.v1beta1.Coin amount = 2 [ + (gogoproto.moretags) = "yaml:\"amount\"", + (gogoproto.nullable) = false + ]; +} +``` + +**State Modifications:** + +- Safety check the following + - Check that the denom minting is created via `tokenfactory` module + - Check that the sender of the message is the admin of the denom +- Mint designated amount of tokens for the denom via `bank` module + +### Burn + +Burning of a specific denom is only allowed for the current admin. +Note, the current admin is defaulted to the creator of the denom. + +```go +message MsgBurn { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + cosmos.base.v1beta1.Coin amount = 2 [ + (gogoproto.moretags) = "yaml:\"amount\"", + (gogoproto.nullable) = false + ]; +} +``` + +**State Modifications:** + +- Saftey check the following + - Check that the denom minting is created via `tokenfactory` module + - Check that the sender of the message is the admin of the denom +- Burn designated amount of tokens for the denom via `bank` module + +### ChangeAdmin + +Change the admin of a denom. Note, this is only allowed to be called by the current admin of the denom. + +```go +message MsgChangeAdmin { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + string denom = 2 [ (gogoproto.moretags) = "yaml:\"denom\"" ]; + string newAdmin = 3 [ (gogoproto.moretags) = "yaml:\"new_admin\"" ]; +} +``` + +### SetDenomMetadata + +Setting of metadata for a specific denom is only allowed for the admin of the denom. +It allows the overwriting of the denom metadata in the bank module. + +```go +message MsgChangeAdmin { + string sender = 1 [ (gogoproto.moretags) = "yaml:\"sender\"" ]; + cosmos.bank.v1beta1.Metadata metadata = 2 [ (gogoproto.moretags) = "yaml:\"metadata\"", (gogoproto.nullable) = false ]; +} +``` + +**State Modifications:** + +- Check that sender of the message is the admin of denom +- Modify `AuthorityMetadata` state entry to change the admin of the denom + +## Expectations from the chain + +The chain's bech32 prefix for addresses can be at most 16 characters long. + +This comes from denoms having a 128 byte maximum length, enforced from the SDK, +and us setting longest_subdenom to be 44 bytes. + +A token factory token's denom is: `factory/{creator address}/{subdenom}` + +Splitting up into sub-components, this has: + +- `len(factory) = 7` +- `2 * len("/") = 2` +- `len(longest_subdenom)` +- `len(creator_address) = len(bech32(longest_addr_length, chain_addr_prefix))`. + +Longest addr length at the moment is `32 bytes`. Due to SDK error correction +settings, this means `len(bech32(32, chain_addr_prefix)) = len(chain_addr_prefix) + 1 + 58`. +Adding this all, we have a total length constraint of `128 = 7 + 2 + len(longest_subdenom) + len(longest_chain_addr_prefix) + 1 + 58`. +Therefore `len(longest_subdenom) + len(longest_chain_addr_prefix) = 128 - (7 + 2 + 1 + 58) = 60`. + +The choice between how we standardized the split these 60 bytes between maxes +from longest_subdenom and longest_chain_addr_prefix is somewhat arbitrary. +Considerations going into this: + +- Per [BIP-0173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki#bech32) + the technically longest HRP for a 32 byte address ('data field') is 31 bytes. + (Comes from encode(data) = 59 bytes, and max length = 90 bytes) +- subdenom should be at least 32 bytes so hashes can go into it +- longer subdenoms are very helpful for creating human readable denoms +- chain addresses should prefer being smaller. The longest HRP in cosmos to date is 11 bytes. (`persistence`) + +For explicitness, its currently set to `len(longest_subdenom) = 44` and `len(longest_chain_addr_prefix) = 16`. + +Please note, if the SDK increases the maximum length of a denom from 128 bytes, +these caps should increase. + +So please don't make code rely on these max lengths for parsing. diff --git a/x/tokenfactory/bindings/custom_msg_test.go b/x/tokenfactory/bindings/custom_msg_test.go new file mode 100644 index 0000000..1675783 --- /dev/null +++ b/x/tokenfactory/bindings/custom_msg_test.go @@ -0,0 +1,277 @@ +package bindings_test + +import ( + "encoding/json" + "fmt" + "testing" + + "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" +) + +func TestCreateDenomMsg(t *testing.T) { + creator := RandomAccountAddress() + terp, ctx := SetupCustomApp(t, creator) + + lucky := RandomAccountAddress() + reflect := instantiateReflectContract(t, ctx, terp, 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) + + msg := bindings.TokenMsg{CreateDenom: &bindings.CreateDenom{ + Subdenom: "SUN", + }} + err := executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) + + // query the denom and see if it matches + query := bindings.TokenQuery{ + FullDenom: &bindings.FullDenom{ + CreatorAddr: reflect.String(), + Subdenom: "SUN", + }, + } + resp := bindings.FullDenomResponse{} + queryCustom(t, ctx, terp, 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) + + lucky := RandomAccountAddress() + reflect := instantiateReflectContract(t, ctx, terp, 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) + + // lucky was broke + balances := terp.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{}) + require.NoError(t, err) + sunDenom := fmt.Sprintf("factory/%s/%s", reflect.String(), msg.CreateDenom.Subdenom) + + amount, ok := sdk.NewIntFromString("808010808") + require.True(t, ok) + msg = bindings.TokenMsg{MintTokens: &bindings.MintTokens{ + Denom: sunDenom, + Amount: amount, + MintToAddress: lucky.String(), + }} + err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) + + balances = terp.BankKeeper.GetAllBalances(ctx, lucky) + require.Len(t, balances, 1) + coin := balances[0] + require.Equal(t, amount, coin.Amount) + require.Contains(t, coin.Denom, "factory/") + + // query the denom and see if it matches + query := bindings.TokenQuery{ + FullDenom: &bindings.FullDenom{ + CreatorAddr: reflect.String(), + Subdenom: "SUN", + }, + } + resp := bindings.FullDenomResponse{} + queryCustom(t, ctx, terp, 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{}) + require.NoError(t, err) + + balances = terp.BankKeeper.GetAllBalances(ctx, lucky) + require.Len(t, balances, 1) + coin = balances[0] + require.Equal(t, amount.MulRaw(2), coin.Amount) + require.Contains(t, coin.Denom, "factory/") + + // query the denom and see if it matches + query = bindings.TokenQuery{ + FullDenom: &bindings.FullDenom{ + CreatorAddr: reflect.String(), + Subdenom: "SUN", + }, + } + resp = bindings.FullDenomResponse{} + queryCustom(t, ctx, terp, reflect, query, &resp) + + require.Equal(t, resp.Denom, coin.Denom) + + // now mint another amount / denom + // create it first + msg = bindings.TokenMsg{CreateDenom: &bindings.CreateDenom{ + Subdenom: "MOON", + }} + err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) + moonDenom := fmt.Sprintf("factory/%s/%s", reflect.String(), msg.CreateDenom.Subdenom) + + amount = amount.SubRaw(1) + msg = bindings.TokenMsg{MintTokens: &bindings.MintTokens{ + Denom: moonDenom, + Amount: amount, + MintToAddress: lucky.String(), + }} + err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) + + balances = terp.BankKeeper.GetAllBalances(ctx, lucky) + require.Len(t, balances, 2) + coin = balances[0] + require.Equal(t, amount, coin.Amount) + require.Contains(t, coin.Denom, "factory/") + + // query the denom and see if it matches + query = bindings.TokenQuery{ + FullDenom: &bindings.FullDenom{ + CreatorAddr: reflect.String(), + Subdenom: "MOON", + }, + } + resp = bindings.FullDenomResponse{} + queryCustom(t, ctx, terp, reflect, query, &resp) + + require.Equal(t, resp.Denom, coin.Denom) + + // and check the first denom is unchanged + coin = balances[1] + require.Equal(t, amount.AddRaw(1).MulRaw(2), coin.Amount) + require.Contains(t, coin.Denom, "factory/") + + // query the denom and see if it matches + query = bindings.TokenQuery{ + FullDenom: &bindings.FullDenom{ + CreatorAddr: reflect.String(), + Subdenom: "SUN", + }, + } + resp = bindings.FullDenomResponse{} + queryCustom(t, ctx, terp, reflect, query, &resp) + + require.Equal(t, resp.Denom, coin.Denom) +} + +func TestBurnMsg(t *testing.T) { + creator := RandomAccountAddress() + terp, ctx := SetupCustomApp(t, creator) + + lucky := RandomAccountAddress() + reflect := instantiateReflectContract(t, ctx, terp, 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) + + // lucky was broke + balances := terp.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{}) + require.NoError(t, err) + sunDenom := fmt.Sprintf("factory/%s/%s", reflect.String(), msg.CreateDenom.Subdenom) + + amount, ok := sdk.NewIntFromString("808010808") + require.True(t, ok) + + msg = bindings.TokenMsg{MintTokens: &bindings.MintTokens{ + Denom: sunDenom, + Amount: amount, + MintToAddress: lucky.String(), + }} + err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) + + // can't burn from different address + msg = bindings.TokenMsg{BurnTokens: &bindings.BurnTokens{ + Denom: sunDenom, + Amount: amount, + BurnFromAddress: lucky.String(), + }} + err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + require.Error(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) + require.NoError(t, err) + + msg = bindings.TokenMsg{BurnTokens: &bindings.BurnTokens{ + Denom: sunDenom, + Amount: amount, + BurnFromAddress: reflect.String(), + }} + err = executeCustom(t, ctx, terp, reflect, lucky, msg, sdk.Coin{}) + require.NoError(t, err) +} + +type ReflectExec struct { + ReflectMsg *ReflectMsgs `json:"reflect_msg,omitempty"` + ReflectSubMsg *ReflectSubMsgs `json:"reflect_sub_msg,omitempty"` +} + +type ReflectMsgs struct { + Msgs []wasmvmtypes.CosmosMsg `json:"msgs"` +} + +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 { + t.Helper() + wrapped := bindings.TokenFactoryMsg{ + Token: &msg, + } + customBz, err := json.Marshal(wrapped) + require.NoError(t, err) + + reflectMsg := ReflectExec{ + ReflectMsg: &ReflectMsgs{ + Msgs: []wasmvmtypes.CosmosMsg{{ + Custom: customBz, + }}, + }, + } + reflectBz, err := json.Marshal(reflectMsg) + require.NoError(t, err) + + // no funds sent if amount is 0 + var coins sdk.Coins + if !funds.Amount.IsNil() { + coins = sdk.Coins{funds} + } + + contractKeeper := keeper.NewDefaultPermissionKeeper(terp.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 new file mode 100644 index 0000000..67e3491 --- /dev/null +++ b/x/tokenfactory/bindings/custom_query_test.go @@ -0,0 +1,75 @@ +package bindings_test + +import ( + "encoding/json" + "fmt" + "testing" + + "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" +) + +func TestQueryFullDenom(t *testing.T) { + actor := RandomAccountAddress() + tokenz, ctx := SetupCustomApp(t, actor) + + reflect := instantiateReflectContract(t, ctx, tokenz, actor) + require.NotEmpty(t, reflect) + + // query full denom + query := bindings.TokenQuery{ + FullDenom: &bindings.FullDenom{ + CreatorAddr: reflect.String(), + Subdenom: "ustart", + }, + } + resp := bindings.FullDenomResponse{} + queryCustom(t, ctx, tokenz, reflect, query, &resp) + + expected := fmt.Sprintf("factory/%s/ustart", reflect.String()) + require.EqualValues(t, expected, resp.Denom) +} + +type ReflectQuery struct { + Chain *ChainRequest `json:"chain,omitempty"` +} + +type ChainRequest struct { + Request wasmvmtypes.QueryRequest `json:"request"` +} + +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() + wrapped := bindings.TokenFactoryQuery{ + Token: &request, + } + msgBz, err := json.Marshal(wrapped) + require.NoError(t, err) + fmt.Println(string(msgBz)) + + query := ReflectQuery{ + Chain: &ChainRequest{ + Request: wasmvmtypes.QueryRequest{Custom: msgBz}, + }, + } + queryBz, err := json.Marshal(query) + require.NoError(t, err) + fmt.Println(string(queryBz)) + + resBz, err := tokenz.WasmKeeper.QuerySmart(ctx, contract, queryBz) + require.NoError(t, err) + var resp ChainResponse + err = json.Unmarshal(resBz, &resp) + require.NoError(t, err) + err = json.Unmarshal(resp.Data, response) + require.NoError(t, err) +} diff --git a/x/tokenfactory/bindings/helpers_test.go b/x/tokenfactory/bindings/helpers_test.go new file mode 100644 index 0000000..6857249 --- /dev/null +++ b/x/tokenfactory/bindings/helpers_test.go @@ -0,0 +1,108 @@ +package bindings_test + +import ( + "os" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/cometbft/cometbft/crypto" + "github.com/cometbft/cometbft/crypto/ed25519" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + + sdk "github.com/cosmos/cosmos-sdk/types" + + 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" +) + +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 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) +} + +// we need to make this deterministic (same every test run), as content might affect gas costs +func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { + key := ed25519.GenPrivKey() + pub := key.PubKey() + addr := sdk.AccAddress(pub.Address()) + return key, pub, addr +} + +func RandomAccountAddress() sdk.AccAddress { + _, _, addr := keyPubAddr() + return addr +} + +func RandomBech32AccountAddress() string { + return RandomAccountAddress().String() +} + +func storeReflectCode(t *testing.T, ctx sdk.Context, tokenz *app.TerpApp, addr sdk.AccAddress) uint64 { + t.Helper() + wasmCode, err := os.ReadFile("./testdata/token_reflect.wasm") + require.NoError(t, err) + + contractKeeper := keeper.NewDefaultPermissionKeeper(tokenz.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() + initMsgBz := []byte("{}") + contractKeeper := keeper.NewDefaultPermissionKeeper(tokenz.WasmKeeper) + codeID := uint64(1) + addr, _, err := contractKeeper.Instantiate(ctx, codeID, funder, funder, initMsgBz, "demo contract", nil) + require.NoError(t, err) + + 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) + require.NoError(t, err) +} + +func SetupCustomApp(t *testing.T, addr sdk.AccAddress) (*app.TerpApp, sdk.Context) { + t.Helper() + tokenz, ctx := CreateTestInput() + wasmKeeper := tokenz.WasmKeeper + + storeReflectCode(t, ctx, tokenz, addr) + + cInfo := wasmKeeper.GetCodeInfo(ctx, 1) + require.NotNil(t, cInfo) + + return tokenz, ctx +} diff --git a/x/tokenfactory/bindings/message_plugin.go b/x/tokenfactory/bindings/message_plugin.go new file mode 100644 index 0000000..0e67ca2 --- /dev/null +++ b/x/tokenfactory/bindings/message_plugin.go @@ -0,0 +1,321 @@ +package bindings + +import ( + "encoding/json" + + errorsmod "cosmossdk.io/errors" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" + 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" +) + +// CustomMessageDecorator returns decorator for custom CosmWasm bindings messages +func CustomMessageDecorator(bank *bankkeeper.BaseKeeper, tokenFactory *tokenfactorykeeper.Keeper) func(wasmkeeper.Messenger) wasmkeeper.Messenger { + return func(old wasmkeeper.Messenger) wasmkeeper.Messenger { + return &CustomMessenger{ + wrapped: old, + bank: bank, + tokenFactory: tokenFactory, + } + } +} + +type CustomMessenger struct { + wrapped wasmkeeper.Messenger + bank *bankkeeper.BaseKeeper + tokenFactory *tokenfactorykeeper.Keeper +} + +var _ wasmkeeper.Messenger = (*CustomMessenger)(nil) + +// DispatchMsg executes on the contractMsg. +func (m *CustomMessenger) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Event, [][]byte, error) { + if msg.Custom != nil { + // only handle the happy path where this is really creating / minting / swapping ... + // leave everything else for the wrapped version + var contractMsg bindingstypes.TokenFactoryMsg + if err := json.Unmarshal(msg.Custom, &contractMsg); err != nil { + return nil, nil, errorsmod.Wrap(err, "token factory msg") + } + if contractMsg.Token == nil { + return nil, nil, errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "nil token field") + } + tokenMsg := contractMsg.Token + + if tokenMsg.CreateDenom != nil { + return m.createDenom(ctx, contractAddr, tokenMsg.CreateDenom) + } + if tokenMsg.MintTokens != nil { + return m.mintTokens(ctx, contractAddr, tokenMsg.MintTokens) + } + if tokenMsg.ChangeAdmin != nil { + return m.changeAdmin(ctx, contractAddr, tokenMsg.ChangeAdmin) + } + if tokenMsg.BurnTokens != nil { + return m.burnTokens(ctx, contractAddr, tokenMsg.BurnTokens) + } + if tokenMsg.SetMetadata != nil { + return m.setMetadata(ctx, contractAddr, tokenMsg.SetMetadata) + } + } + return m.wrapped.DispatchMsg(ctx, contractAddr, contractIBCPortID, msg) +} + +// createDenom creates a new token denom +func (m *CustomMessenger) createDenom(ctx sdk.Context, contractAddr sdk.AccAddress, createDenom *bindingstypes.CreateDenom) ([]sdk.Event, [][]byte, error) { + bz, err := PerformCreateDenom(m.tokenFactory, m.bank, ctx, contractAddr, createDenom) + if err != nil { + return nil, nil, errorsmod.Wrap(err, "perform create denom") + } + // TODO: double check how this is all encoded to the contract + return nil, [][]byte{bz}, nil +} + +// PerformCreateDenom is used with createDenom to create a token denom; validates the msgCreateDenom. +func PerformCreateDenom(f *tokenfactorykeeper.Keeper, b *bankkeeper.BaseKeeper, ctx sdk.Context, contractAddr sdk.AccAddress, createDenom *bindingstypes.CreateDenom) ([]byte, error) { + if createDenom == nil { + return nil, wasmvmtypes.InvalidRequest{Err: "create denom null create denom"} + } + + msgServer := tokenfactorykeeper.NewMsgServerImpl(*f) + + msgCreateDenom := tokenfactorytypes.NewMsgCreateDenom(contractAddr.String(), createDenom.Subdenom) + + if err := msgCreateDenom.ValidateBasic(); err != nil { + return nil, errorsmod.Wrap(err, "failed validating MsgCreateDenom") + } + + // Create denom + resp, err := msgServer.CreateDenom( + sdk.WrapSDKContext(ctx), + msgCreateDenom, + ) + if err != nil { + return nil, errorsmod.Wrap(err, "creating denom") + } + + if createDenom.Metadata != nil { + newDenom := resp.NewTokenDenom + err := PerformSetMetadata(f, b, ctx, contractAddr, newDenom, *createDenom.Metadata) + if err != nil { + return nil, errorsmod.Wrap(err, "setting metadata") + } + } + + return resp.Marshal() +} + +// mintTokens mints tokens of a specified denom to an address. +func (m *CustomMessenger) mintTokens(ctx sdk.Context, contractAddr sdk.AccAddress, mint *bindingstypes.MintTokens) ([]sdk.Event, [][]byte, error) { + err := PerformMint(m.tokenFactory, m.bank, ctx, contractAddr, mint) + if err != nil { + return nil, nil, errorsmod.Wrap(err, "perform mint") + } + return nil, nil, nil +} + +// PerformMint used with mintTokens to validate the mint message and mint through token factory. +func PerformMint(f *tokenfactorykeeper.Keeper, b *bankkeeper.BaseKeeper, ctx sdk.Context, contractAddr sdk.AccAddress, mint *bindingstypes.MintTokens) error { + if mint == nil { + return wasmvmtypes.InvalidRequest{Err: "mint token null mint"} + } + rcpt, err := parseAddress(mint.MintToAddress) + if err != nil { + return err + } + + coin := sdk.Coin{Denom: mint.Denom, Amount: mint.Amount} + sdkMsg := tokenfactorytypes.NewMsgMint(contractAddr.String(), coin) + if err = sdkMsg.ValidateBasic(); err != nil { + return err + } + + // Mint through token factory / message server + msgServer := tokenfactorykeeper.NewMsgServerImpl(*f) + _, err = msgServer.Mint(sdk.WrapSDKContext(ctx), sdkMsg) + if err != nil { + return errorsmod.Wrap(err, "minting coins from message") + } + err = b.SendCoins(ctx, contractAddr, rcpt, sdk.NewCoins(coin)) + if err != nil { + return errorsmod.Wrap(err, "sending newly minted coins from message") + } + return nil +} + +// changeAdmin changes the admin. +func (m *CustomMessenger) changeAdmin(ctx sdk.Context, contractAddr sdk.AccAddress, changeAdmin *bindingstypes.ChangeAdmin) ([]sdk.Event, [][]byte, error) { + err := ChangeAdmin(m.tokenFactory, ctx, contractAddr, changeAdmin) + if err != nil { + return nil, nil, errorsmod.Wrap(err, "failed to change admin") + } + return nil, nil, nil +} + +// ChangeAdmin is used with changeAdmin to validate changeAdmin messages and to dispatch. +func ChangeAdmin(f *tokenfactorykeeper.Keeper, ctx sdk.Context, contractAddr sdk.AccAddress, changeAdmin *bindingstypes.ChangeAdmin) error { + if changeAdmin == nil { + return wasmvmtypes.InvalidRequest{Err: "changeAdmin is nil"} + } + newAdminAddr, err := parseAddress(changeAdmin.NewAdminAddress) + if err != nil { + return err + } + + changeAdminMsg := tokenfactorytypes.NewMsgChangeAdmin(contractAddr.String(), changeAdmin.Denom, newAdminAddr.String()) + if err := changeAdminMsg.ValidateBasic(); err != nil { + return err + } + + msgServer := tokenfactorykeeper.NewMsgServerImpl(*f) + _, err = msgServer.ChangeAdmin(sdk.WrapSDKContext(ctx), changeAdminMsg) + if err != nil { + return errorsmod.Wrap(err, "failed changing admin from message") + } + return nil +} + +// burnTokens burns tokens. +func (m *CustomMessenger) burnTokens(ctx sdk.Context, contractAddr sdk.AccAddress, burn *bindingstypes.BurnTokens) ([]sdk.Event, [][]byte, error) { + err := PerformBurn(m.tokenFactory, ctx, contractAddr, burn) + if err != nil { + return nil, nil, errorsmod.Wrap(err, "perform burn") + } + return nil, nil, nil +} + +// PerformBurn performs token burning after validating tokenBurn message. +func PerformBurn(f *tokenfactorykeeper.Keeper, ctx sdk.Context, contractAddr sdk.AccAddress, burn *bindingstypes.BurnTokens) error { + 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 err := sdkMsg.ValidateBasic(); err != nil { + return err + } + + // Burn through token factory / message server + msgServer := tokenfactorykeeper.NewMsgServerImpl(*f) + _, err := msgServer.Burn(sdk.WrapSDKContext(ctx), sdkMsg) + if err != nil { + return errorsmod.Wrap(err, "burning coins 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) + if err != nil { + return nil, nil, errorsmod.Wrap(err, "perform create denom") + } + return nil, nil, nil +} + +// PerformSetMetadata is used with setMetadata to add new metadata +// It also is called inside CreateDenom if optional metadata field is set +func PerformSetMetadata(f *tokenfactorykeeper.Keeper, b *bankkeeper.BaseKeeper, ctx sdk.Context, contractAddr sdk.AccAddress, denom string, metadata bindingstypes.Metadata) error { + // ensure contract address is admin of denom + auth, err := f.GetAuthorityMetadata(ctx, denom) + if err != nil { + return err + } + if auth.Admin != contractAddr.String() { + return wasmvmtypes.InvalidRequest{Err: "only admin can set metadata"} + } + + // ensure we are setting proper denom metadata (bank uses Base field, fill it if missing) + if metadata.Base == "" { + metadata.Base = denom + } else if metadata.Base != denom { + // this is the key that we set + return wasmvmtypes.InvalidRequest{Err: "Base must be the same as denom"} + } + + // Create and validate the metadata + bankMetadata := WasmMetadataToSdk(metadata) + if err := bankMetadata.Validate(); err != nil { + return err + } + + b.SetDenomMetaData(ctx, bankMetadata) + return nil +} + +// GetFullDenom is a function, not method, so the message_plugin can use it +func GetFullDenom(contract string, subDenom string) (string, error) { + // Address validation + if _, err := parseAddress(contract); err != nil { + return "", err + } + fullDenom, err := tokenfactorytypes.GetTokenDenom(contract, subDenom) + if err != nil { + return "", errorsmod.Wrap(err, "validate sub-denom") + } + + return fullDenom, nil +} + +// parseAddress parses address from bech32 string and verifies its format. +func parseAddress(addr string) (sdk.AccAddress, error) { + parsed, err := sdk.AccAddressFromBech32(addr) + if err != nil { + return nil, errorsmod.Wrap(err, "address from bech32") + } + err = sdk.VerifyAddressFormat(parsed) + if err != nil { + return nil, errorsmod.Wrap(err, "verify address format") + } + return parsed, nil +} + +func WasmMetadataToSdk(metadata bindingstypes.Metadata) banktypes.Metadata { + denoms := []*banktypes.DenomUnit{} + for _, unit := range metadata.DenomUnits { + denoms = append(denoms, &banktypes.DenomUnit{ + Denom: unit.Denom, + Exponent: unit.Exponent, + Aliases: unit.Aliases, + }) + } + return banktypes.Metadata{ + Description: metadata.Description, + Display: metadata.Display, + Base: metadata.Base, + Name: metadata.Name, + Symbol: metadata.Symbol, + DenomUnits: denoms, + } +} + +func SdkMetadataToWasm(metadata banktypes.Metadata) *bindingstypes.Metadata { + denoms := []bindingstypes.DenomUnit{} + for _, unit := range metadata.DenomUnits { + denoms = append(denoms, bindingstypes.DenomUnit{ + Denom: unit.Denom, + Exponent: unit.Exponent, + Aliases: unit.Aliases, + }) + } + return &bindingstypes.Metadata{ + Description: metadata.Description, + Display: metadata.Display, + Base: metadata.Base, + Name: metadata.Name, + Symbol: metadata.Symbol, + DenomUnits: denoms, + } +} diff --git a/x/tokenfactory/bindings/queries.go b/x/tokenfactory/bindings/queries.go new file mode 100644 index 0000000..15dd308 --- /dev/null +++ b/x/tokenfactory/bindings/queries.go @@ -0,0 +1,57 @@ +package bindings + +import ( + "fmt" + + 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" +) + +type QueryPlugin struct { + bankKeeper *bankkeeper.BaseKeeper + tokenFactoryKeeper *tokenfactorykeeper.Keeper +} + +// NewQueryPlugin returns a reference to a new QueryPlugin. +func NewQueryPlugin(b *bankkeeper.BaseKeeper, tfk *tokenfactorykeeper.Keeper) *QueryPlugin { + return &QueryPlugin{ + bankKeeper: b, + tokenFactoryKeeper: tfk, + } +} + +// GetDenomAdmin is a query to get denom admin. +func (qp QueryPlugin) GetDenomAdmin(ctx sdk.Context, denom string) (*bindingstypes.AdminResponse, error) { + metadata, err := qp.tokenFactoryKeeper.GetAuthorityMetadata(ctx, denom) + if err != nil { + return nil, fmt.Errorf("failed to get admin for denom: %s", denom) + } + return &bindingstypes.AdminResponse{Admin: metadata.Admin}, nil +} + +func (qp QueryPlugin) GetDenomsByCreator(ctx sdk.Context, creator string) (*bindingstypes.DenomsByCreatorResponse, error) { + // TODO: validate creator address + denoms := qp.tokenFactoryKeeper.GetDenomsFromCreator(ctx, creator) + return &bindingstypes.DenomsByCreatorResponse{Denoms: denoms}, nil +} + +func (qp QueryPlugin) GetMetadata(ctx sdk.Context, denom string) (*bindingstypes.MetadataResponse, error) { + metadata, found := qp.bankKeeper.GetDenomMetaData(ctx, denom) + var parsed *bindingstypes.Metadata + if found { + parsed = SdkMetadataToWasm(metadata) + } + return &bindingstypes.MetadataResponse{Metadata: parsed}, nil +} + +func (qp QueryPlugin) GetParams(ctx sdk.Context) (*bindingstypes.ParamsResponse, error) { + params := qp.tokenFactoryKeeper.GetParams(ctx) + return &bindingstypes.ParamsResponse{ + Params: bindingstypes.Params{ + DenomCreationFee: ConvertSdkCoinsToWasmCoins(params.DenomCreationFee), + }, + }, nil +} diff --git a/x/tokenfactory/bindings/query_plugin.go b/x/tokenfactory/bindings/query_plugin.go new file mode 100644 index 0000000..0dfbfeb --- /dev/null +++ b/x/tokenfactory/bindings/query_plugin.go @@ -0,0 +1,123 @@ +package bindings + +import ( + "encoding/json" + "fmt" + + errorsmod "cosmossdk.io/errors" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" + 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" +) + +// CustomQuerier dispatches custom CosmWasm bindings queries. +func CustomQuerier(qp *QueryPlugin) func(ctx sdk.Context, request json.RawMessage) ([]byte, error) { + 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") + } + if contractQuery.Token == nil { + return nil, errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "nil token field") + } + tokenQuery := contractQuery.Token + + switch { + case tokenQuery.FullDenom != nil: + creator := tokenQuery.FullDenom.CreatorAddr + subdenom := tokenQuery.FullDenom.Subdenom + + fullDenom, err := GetFullDenom(creator, subdenom) + if err != nil { + return nil, errorsmod.Wrap(err, "terp full denom query") + } + + res := bindingstypes.FullDenomResponse{ + Denom: fullDenom, + } + + bz, err := json.Marshal(res) + if err != nil { + return nil, errorsmod.Wrap(err, "failed to marshal FullDenomResponse") + } + + return bz, nil + + case tokenQuery.Admin != nil: + res, err := qp.GetDenomAdmin(ctx, tokenQuery.Admin.Denom) + if err != nil { + return nil, err + } + + bz, err := json.Marshal(res) + if err != nil { + return nil, fmt.Errorf("failed to JSON marshal AdminResponse: %w", err) + } + + return bz, nil + + case tokenQuery.Metadata != nil: + res, err := qp.GetMetadata(ctx, tokenQuery.Metadata.Denom) + if err != nil { + return nil, err + } + + bz, err := json.Marshal(res) + if err != nil { + return nil, fmt.Errorf("failed to JSON marshal MetadataResponse: %w", err) + } + + return bz, nil + + case tokenQuery.DenomsByCreator != nil: + res, err := qp.GetDenomsByCreator(ctx, tokenQuery.DenomsByCreator.Creator) + if err != nil { + return nil, err + } + + bz, err := json.Marshal(res) + if err != nil { + return nil, fmt.Errorf("failed to JSON marshal DenomsByCreatorResponse: %w", err) + } + + return bz, nil + + case tokenQuery.Params != nil: + res, err := qp.GetParams(ctx) + if err != nil { + return nil, err + } + + bz, err := json.Marshal(res) + if err != nil { + return nil, fmt.Errorf("failed to JSON marshal ParamsResponse: %w", err) + } + + return bz, nil + + default: + return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown token query variant"} + } + } +} + +// ConvertSdkCoinsToWasmCoins converts sdk type coins to wasm vm type coins +func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins { + var toSend wasmvmtypes.Coins + for _, coin := range coins { + c := ConvertSdkCoinToWasmCoin(coin) + toSend = append(toSend, c) + } + return toSend +} + +// ConvertSdkCoinToWasmCoin converts a sdk type coin to a wasm vm type coin +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 + Amount: coin.Amount.String(), + } +} diff --git a/x/tokenfactory/bindings/testdata/download_releases.sh b/x/tokenfactory/bindings/testdata/download_releases.sh new file mode 100755 index 0000000..161a33f --- /dev/null +++ b/x/tokenfactory/bindings/testdata/download_releases.sh @@ -0,0 +1,16 @@ +#!/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" +url="https://github.com/CosmWasm/token-bindings/releases/download/$tag/token_reflect.wasm" +echo "Downloading $url ..." +wget -O "token_reflect.wasm" "$url" + +rm -f version.txt +echo "$tag" >version.txt \ No newline at end of file diff --git a/x/tokenfactory/bindings/testdata/token_reflect.wasm b/x/tokenfactory/bindings/testdata/token_reflect.wasm new file mode 100644 index 0000000..0d742e1 Binary files /dev/null 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 new file mode 100644 index 0000000..b19b521 --- /dev/null +++ b/x/tokenfactory/bindings/testdata/version.txt @@ -0,0 +1 @@ +v0.8.0 diff --git a/x/tokenfactory/bindings/types/msg.go b/x/tokenfactory/bindings/types/msg.go new file mode 100644 index 0000000..3c6cfa2 --- /dev/null +++ b/x/tokenfactory/bindings/types/msg.go @@ -0,0 +1,60 @@ +package types + +import "cosmossdk.io/math" + +type TokenFactoryMsg struct { + Token *TokenMsg `json:"token,omitempty"` +} + +type TokenMsg struct { + /// Contracts can create denoms, namespaced under the contract's address. + /// A contract may create any number of independent sub-denoms. + CreateDenom *CreateDenom `json:"create_denom,omitempty"` + /// Contracts can change the admin of a denom that they are the admin of. + ChangeAdmin *ChangeAdmin `json:"change_admin,omitempty"` + /// Contracts can mint native tokens for an existing factory denom + /// that they are the admin of. + MintTokens *MintTokens `json:"mint_tokens,omitempty"` + /// Contracts can burn native tokens for an existing factory denom + /// that they are the admin of. + /// Currently, the burn from address must be the admin contract. + BurnTokens *BurnTokens `json:"burn_tokens,omitempty"` + /// Sets the metadata on a denom which the contract controls + SetMetadata *SetMetadata `json:"set_metadata,omitempty"` +} + +// CreateDenom creates a new factory denom, of denomination: +// factory/{creating contract address}/{Subdenom} +// Subdenom can be of length at most 44 characters, in [0-9a-zA-Z./] +// The (creating contract address, subdenom) pair must be unique. +// The created denom's admin is the creating contract address, +// but this admin can be changed using the ChangeAdmin binding. +type CreateDenom struct { + Subdenom string `json:"subdenom"` + Metadata *Metadata `json:"metadata,omitempty"` +} + +// ChangeAdmin changes the admin for a factory denom. +// If the NewAdminAddress is empty, the denom has no admin. +type ChangeAdmin struct { + Denom string `json:"denom"` + NewAdminAddress string `json:"new_admin_address"` +} + +type MintTokens struct { + Denom string `json:"denom"` + Amount math.Int `json:"amount"` + MintToAddress string `json:"mint_to_address"` +} + +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"` +} + +type SetMetadata struct { + Denom string `json:"denom"` + Metadata Metadata `json:"metadata"` +} diff --git a/x/tokenfactory/bindings/types/query.go b/x/tokenfactory/bindings/types/query.go new file mode 100644 index 0000000..f2dab49 --- /dev/null +++ b/x/tokenfactory/bindings/types/query.go @@ -0,0 +1,59 @@ +package types + +type TokenFactoryQuery struct { + Token *TokenQuery `json:"token,omitempty"` +} + +// See https://github.com/CosmWasm/token-bindings/blob/main/packages/bindings/src/query.rs +type TokenQuery struct { + /// Given a subdenom minted by a contract via `OsmosisMsg::MintTokens`, + /// returns the full denom as used by `BankMsg::Send`. + FullDenom *FullDenom `json:"full_denom,omitempty"` + Admin *DenomAdmin `json:"admin,omitempty"` + Metadata *GetMetadata `json:"metadata,omitempty"` + DenomsByCreator *DenomsByCreator `json:"denoms_by_creator,omitempty"` + Params *GetParams `json:"params,omitempty"` +} + +// query types + +type FullDenom struct { + CreatorAddr string `json:"creator_addr"` + Subdenom string `json:"subdenom"` +} + +type GetMetadata struct { + Denom string `json:"denom"` +} + +type DenomAdmin struct { + Denom string `json:"denom"` +} + +type DenomsByCreator struct { + Creator string `json:"creator"` +} + +type GetParams struct{} + +// responses + +type FullDenomResponse struct { + Denom string `json:"denom"` +} + +type AdminResponse struct { + Admin string `json:"admin"` +} + +type MetadataResponse struct { + Metadata *Metadata `json:"metadata,omitempty"` +} + +type DenomsByCreatorResponse struct { + Denoms []string `json:"denoms"` +} + +type ParamsResponse struct { + Params Params `json:"params"` +} diff --git a/x/tokenfactory/bindings/types/types.go b/x/tokenfactory/bindings/types/types.go new file mode 100644 index 0000000..2c75fee --- /dev/null +++ b/x/tokenfactory/bindings/types/types.go @@ -0,0 +1,37 @@ +package types + +import ( + wasmvmtypes "github.com/CosmWasm/wasmvm/types" +) + +type Metadata struct { + Description string `json:"description"` + // DenomUnits represents the list of DenomUnit's for a given coin + DenomUnits []DenomUnit `json:"denom_units"` + // Base represents the base denom (should be the DenomUnit with exponent = 0). + Base string `json:"base"` + // Display indicates the suggested denom that should be displayed in clients. + Display string `json:"display"` + // Name defines the name of the token (eg: Cosmos Atom) + Name string `json:"name"` + // Symbol is the token symbol usually shown on exchanges (eg: ATOM). + // This can be the same as the display. + Symbol string `json:"symbol"` +} + +type DenomUnit struct { + // Denom represents the string name of the given denom unit (e.g uatom). + Denom string `json:"denom"` + // Exponent represents power of 10 exponent that one must + // raise the base_denom to in order to equal the given DenomUnit's denom + // 1 denom = 1^exponent base_denom + // (e.g. with a base_denom of uatom, one can create a DenomUnit of 'atom' with + // exponent = 6, thus: 1 atom = 10^6 uatom). + Exponent uint32 `json:"exponent"` + // Aliases is a list of string aliases for the given denom + Aliases []string `json:"aliases"` +} + +type Params struct { + DenomCreationFee []wasmvmtypes.Coin `json:"denom_creation_fee"` +} diff --git a/x/tokenfactory/bindings/validate_msg_test.go b/x/tokenfactory/bindings/validate_msg_test.go new file mode 100644 index 0000000..e0a88ce --- /dev/null +++ b/x/tokenfactory/bindings/validate_msg_test.go @@ -0,0 +1,429 @@ +package bindings_test + +import ( + "fmt" + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + + 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" + + "github.com/stretchr/testify/require" +) + +func TestCreateDenom(t *testing.T) { + actor := RandomAccountAddress() + tokenz, 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) + + specs := map[string]struct { + createDenom *bindings.CreateDenom + expErr bool + expPanic bool + }{ + "valid sub-denom": { + createDenom: &bindings.CreateDenom{ + Subdenom: "MOON", + }, + }, + "empty sub-denom": { + createDenom: &bindings.CreateDenom{ + Subdenom: "", + }, + expPanic: true, + }, + "invalid sub-denom": { + createDenom: &bindings.CreateDenom{ + Subdenom: "sub-denom@2", + }, + expErr: true, + }, + "null create denom": { + createDenom: nil, + expErr: true, + }, + } + 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) + // then + if spec.expErr { + require.Error(t, gotErr) + return + } + require.NoError(t, gotErr) + }) + } +} + +func TestChangeAdmin(t *testing.T) { + const validDenom = "validdenom" + + tokenCreator := RandomAccountAddress() + + specs := map[string]struct { + actor sdk.AccAddress + changeAdmin *bindings.ChangeAdmin + + expErrMsg string + }{ + "valid": { + changeAdmin: &bindings.ChangeAdmin{ + Denom: fmt.Sprintf("factory/%s/%s", tokenCreator.String(), validDenom), + NewAdminAddress: RandomBech32AccountAddress(), + }, + actor: tokenCreator, + }, + "typo in factory in denom name": { + changeAdmin: &bindings.ChangeAdmin{ + Denom: fmt.Sprintf("facory/%s/%s", tokenCreator.String(), validDenom), + NewAdminAddress: RandomBech32AccountAddress(), + }, + actor: tokenCreator, + expErrMsg: "denom prefix is incorrect. Is: facory. Should be: factory: invalid denom", + }, + "invalid address in denom": { + changeAdmin: &bindings.ChangeAdmin{ + Denom: fmt.Sprintf("factory/%s/%s", RandomBech32AccountAddress(), validDenom), + NewAdminAddress: RandomBech32AccountAddress(), + }, + actor: tokenCreator, + expErrMsg: "failed changing admin from message: unauthorized account", + }, + "other denom name in 3 part name": { + changeAdmin: &bindings.ChangeAdmin{ + Denom: fmt.Sprintf("factory/%s/%s", tokenCreator.String(), "invalid denom"), + NewAdminAddress: RandomBech32AccountAddress(), + }, + actor: tokenCreator, + expErrMsg: fmt.Sprintf("invalid denom: factory/%s/invalid denom", tokenCreator.String()), + }, + "empty denom": { + changeAdmin: &bindings.ChangeAdmin{ + Denom: "", + NewAdminAddress: RandomBech32AccountAddress(), + }, + actor: tokenCreator, + expErrMsg: "invalid denom: ", + }, + "empty address": { + changeAdmin: &bindings.ChangeAdmin{ + Denom: fmt.Sprintf("factory/%s/%s", tokenCreator.String(), validDenom), + NewAdminAddress: "", + }, + actor: tokenCreator, + expErrMsg: "address from bech32: empty address string is not allowed", + }, + "creator is a different address": { + changeAdmin: &bindings.ChangeAdmin{ + Denom: fmt.Sprintf("factory/%s/%s", tokenCreator.String(), validDenom), + NewAdminAddress: RandomBech32AccountAddress(), + }, + actor: RandomAccountAddress(), + expErrMsg: "failed changing admin from message: unauthorized account", + }, + "change to the same address": { + changeAdmin: &bindings.ChangeAdmin{ + Denom: fmt.Sprintf("factory/%s/%s", tokenCreator.String(), validDenom), + NewAdminAddress: tokenCreator.String(), + }, + actor: tokenCreator, + }, + "nil binding": { + actor: tokenCreator, + expErrMsg: "invalid request: changeAdmin is nil - original request: ", + }, + } + for name, spec := range specs { + t.Run(name, func(t *testing.T) { + // Setup + tokenz, 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) + + _, err := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, tokenCreator, &bindings.CreateDenom{ + Subdenom: validDenom, + }) + require.NoError(t, err) + + err = wasmbinding.ChangeAdmin(&tokenz.TokenFactoryKeeper, ctx, spec.actor, spec.changeAdmin) + if len(spec.expErrMsg) > 0 { + require.Error(t, err) + actualErrMsg := err.Error() + require.Equal(t, spec.expErrMsg, actualErrMsg) + return + } + require.NoError(t, err) + }) + } +} + +func TestMint(t *testing.T) { + creator := RandomAccountAddress() + tokenz, 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) + + // Create denoms for valid mint tests + validDenom := bindings.CreateDenom{ + Subdenom: "MOON", + } + _, err := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.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) + + validDenomStr := fmt.Sprintf("factory/%s/%s", creator.String(), validDenom.Subdenom) + emptyDenomStr := fmt.Sprintf("factory/%s/%s", creator.String(), emptyDenom.Subdenom) + + lucky := RandomAccountAddress() + + // lucky was broke + balances := tokenz.BankKeeper.GetAllBalances(ctx, lucky) + require.Empty(t, balances) + + amount, ok := sdk.NewIntFromString("8080") + require.True(t, ok) + + specs := map[string]struct { + mint *bindings.MintTokens + expErr bool + }{ + "valid mint": { + mint: &bindings.MintTokens{ + Denom: validDenomStr, + Amount: amount, + MintToAddress: lucky.String(), + }, + }, + "empty sub-denom": { + mint: &bindings.MintTokens{ + Denom: emptyDenomStr, + Amount: amount, + MintToAddress: lucky.String(), + }, + expErr: true, + }, + "nonexistent sub-denom": { + mint: &bindings.MintTokens{ + Denom: fmt.Sprintf("factory/%s/%s", creator.String(), "SUN"), + Amount: amount, + MintToAddress: lucky.String(), + }, + expErr: true, + }, + "invalid sub-denom": { + mint: &bindings.MintTokens{ + Denom: "sub-denom_2", + Amount: amount, + MintToAddress: lucky.String(), + }, + expErr: true, + }, + "zero amount": { + mint: &bindings.MintTokens{ + Denom: validDenomStr, + Amount: sdk.ZeroInt(), + MintToAddress: lucky.String(), + }, + expErr: true, + }, + "negative amount": { + mint: &bindings.MintTokens{ + Denom: validDenomStr, + Amount: amount.Neg(), + MintToAddress: lucky.String(), + }, + expErr: true, + }, + "empty recipient": { + mint: &bindings.MintTokens{ + Denom: validDenomStr, + Amount: amount, + MintToAddress: "", + }, + expErr: true, + }, + "invalid recipient": { + mint: &bindings.MintTokens{ + Denom: validDenomStr, + Amount: amount, + MintToAddress: "invalid", + }, + expErr: true, + }, + "null mint": { + mint: nil, + expErr: true, + }, + } + for name, spec := range specs { + t.Run(name, func(t *testing.T) { + // when + gotErr := wasmbinding.PerformMint(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, spec.mint) + // then + if spec.expErr { + require.Error(t, gotErr) + return + } + require.NoError(t, gotErr) + }) + } +} + +func TestBurn(t *testing.T) { + creator := RandomAccountAddress() + tokenz, 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) + + // Create denoms for valid burn tests + validDenom := bindings.CreateDenom{ + Subdenom: "MOON", + } + _, err := wasmbinding.PerformCreateDenom(&tokenz.TokenFactoryKeeper, &tokenz.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) + }) + + lucky := RandomAccountAddress() + + // lucky was broke + balances := tokenz.BankKeeper.GetAllBalances(ctx, lucky) + require.Empty(t, balances) + + validDenomStr := fmt.Sprintf("factory/%s/%s", creator.String(), validDenom.Subdenom) + emptyDenomStr := fmt.Sprintf("factory/%s/%s", creator.String(), emptyDenom.Subdenom) + mintAmount, ok := sdk.NewIntFromString("8080") + require.True(t, ok) + + specs := map[string]struct { + burn *bindings.BurnTokens + expErr bool + }{ + "valid burn": { + burn: &bindings.BurnTokens{ + Denom: validDenomStr, + Amount: mintAmount, + BurnFromAddress: creator.String(), + }, + expErr: false, + }, + "non admin address": { + burn: &bindings.BurnTokens{ + Denom: validDenomStr, + Amount: mintAmount, + BurnFromAddress: lucky.String(), + }, + expErr: true, + }, + "empty sub-denom": { + burn: &bindings.BurnTokens{ + Denom: emptyDenomStr, + Amount: mintAmount, + BurnFromAddress: creator.String(), + }, + expErr: true, + }, + "invalid sub-denom": { + burn: &bindings.BurnTokens{ + Denom: "sub-denom_2", + Amount: mintAmount, + BurnFromAddress: creator.String(), + }, + expErr: true, + }, + "non-minted denom": { + burn: &bindings.BurnTokens{ + Denom: fmt.Sprintf("factory/%s/%s", creator.String(), "SUN"), + Amount: mintAmount, + BurnFromAddress: creator.String(), + }, + expErr: true, + }, + "zero amount": { + burn: &bindings.BurnTokens{ + Denom: validDenomStr, + Amount: sdk.ZeroInt(), + BurnFromAddress: creator.String(), + }, + expErr: true, + }, + "negative amount": { + burn: nil, + expErr: true, + }, + "null burn": { + burn: &bindings.BurnTokens{ + Denom: validDenomStr, + Amount: mintAmount.Neg(), + BurnFromAddress: creator.String(), + }, + expErr: true, + }, + } + + for name, spec := range specs { + t.Run(name, func(t *testing.T) { + // Mint valid denom str and empty denom string for burn test + mintBinding := &bindings.MintTokens{ + Denom: validDenomStr, + Amount: mintAmount, + MintToAddress: creator.String(), + } + err := wasmbinding.PerformMint(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, mintBinding) + require.NoError(t, err) + + emptyDenomMintBinding := &bindings.MintTokens{ + Denom: emptyDenomStr, + Amount: mintAmount, + MintToAddress: creator.String(), + } + err = wasmbinding.PerformMint(&tokenz.TokenFactoryKeeper, &tokenz.BankKeeper, ctx, creator, emptyDenomMintBinding) + require.Error(t, err) + + // when + gotErr := wasmbinding.PerformBurn(&tokenz.TokenFactoryKeeper, ctx, creator, spec.burn) + // then + if spec.expErr { + require.Error(t, gotErr) + return + } + require.NoError(t, gotErr) + }) + } +} diff --git a/x/tokenfactory/bindings/validate_queries_test.go b/x/tokenfactory/bindings/validate_queries_test.go new file mode 100644 index 0000000..c800103 --- /dev/null +++ b/x/tokenfactory/bindings/validate_queries_test.go @@ -0,0 +1,115 @@ +package bindings_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" + + wasmbinding "github.com/terpnetwork/terp-core/x/tokenfactory/bindings" +) + +func TestFullDenom(t *testing.T) { + actor := RandomAccountAddress() + + specs := map[string]struct { + addr string + subdenom string + expFullDenom string + expErr bool + }{ + "valid address": { + addr: actor.String(), + subdenom: "subDenom1", + expFullDenom: fmt.Sprintf("factory/%s/subDenom1", actor.String()), + }, + "empty address": { + addr: "", + subdenom: "subDenom1", + expErr: true, + }, + "invalid address": { + addr: "invalid", + subdenom: "subDenom1", + expErr: true, + }, + "empty sub-denom": { + addr: actor.String(), + subdenom: "", + expFullDenom: fmt.Sprintf("factory/%s/", actor.String()), + }, + "invalid sub-denom (contains @)": { + addr: actor.String(), + subdenom: "sub@denom", + expErr: true, + }, + } + for name, spec := range specs { + t.Run(name, func(t *testing.T) { + // when + gotFullDenom, gotErr := wasmbinding.GetFullDenom(spec.addr, spec.subdenom) + // then + if spec.expErr { + require.Error(t, gotErr) + return + } + require.NoError(t, gotErr) + assert.Equal(t, spec.expFullDenom, gotFullDenom, "exp %s but got %s", spec.expFullDenom, gotFullDenom) + }) + } +} + +func TestDenomAdmin(t *testing.T) { + addr := RandomAccountAddress() + app, ctx := SetupCustomApp(t, addr) + + // set token creation fee to zero to make testing easier + tfParams := app.TokenFactoryKeeper.GetParams(ctx) + tfParams.DenomCreationFee = sdk.NewCoins() + app.TokenFactoryKeeper.SetParams(ctx, tfParams) + + // create a subdenom via the token factory + admin := sdk.AccAddress([]byte("addr1_______________")) + tfDenom, err := app.TokenFactoryKeeper.CreateDenom(ctx, admin.String(), "subdenom") + require.NoError(t, err) + require.NotEmpty(t, tfDenom) + + queryPlugin := wasmbinding.NewQueryPlugin(&app.BankKeeper, &app.TokenFactoryKeeper) + + testCases := []struct { + name string + denom string + expectErr bool + expectAdmin string + }{ + { + name: "valid token factory denom", + denom: tfDenom, + expectAdmin: admin.String(), + }, + { + name: "invalid token factory denom", + denom: "uosmo", + expectErr: false, + expectAdmin: "", + }, + } + + for _, tc := range testCases { + tc := tc + + t.Run(tc.name, func(t *testing.T) { + resp, err := queryPlugin.GetDenomAdmin(ctx, tc.denom) + if tc.expectErr { + require.Error(t, err) + } else { + require.NoError(t, err) + require.NotNil(t, resp) + require.Equal(t, tc.expectAdmin, resp.Admin) + } + }) + } +} diff --git a/x/tokenfactory/bindings/wasm.go b/x/tokenfactory/bindings/wasm.go new file mode 100644 index 0000000..33ea401 --- /dev/null +++ b/x/tokenfactory/bindings/wasm.go @@ -0,0 +1,30 @@ +package bindings + +import ( + "github.com/terpnetwork/terp-core/x/wasm" + + wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" + + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + + tokenfactorykeeper "github.com/terpnetwork/terp-core/x/tokenfactory/keeper" +) + +func RegisterCustomPlugins( + bank *bankkeeper.BaseKeeper, + tokenFactory *tokenfactorykeeper.Keeper, +) []wasmkeeper.Option { + wasmQueryPlugin := NewQueryPlugin(bank, tokenFactory) + + queryPluginOpt := wasmkeeper.WithQueryPlugins(&wasmkeeper.QueryPlugins{ + Custom: CustomQuerier(wasmQueryPlugin), + }) + messengerDecoratorOpt := wasmkeeper.WithMessageHandlerDecorator( + CustomMessageDecorator(bank, tokenFactory), + ) + + return []wasm.Option{ + queryPluginOpt, + messengerDecoratorOpt, + } +} diff --git a/x/tokenfactory/client/cli/query.go b/x/tokenfactory/client/cli/query.go new file mode 100644 index 0000000..b23a7e2 --- /dev/null +++ b/x/tokenfactory/client/cli/query.go @@ -0,0 +1,122 @@ +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" +) + +// GetQueryCmd returns the cli query commands for this module +func GetQueryCmd() *cobra.Command { + // Group tokenfactory queries under a subcommand + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("Querying commands for the %s module", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + GetParams(), + GetCmdDenomAuthorityMetadata(), + GetCmdDenomsFromCreator(), + ) + + return cmd +} + +// GetParams returns the params for the module +func GetParams() *cobra.Command { + cmd := &cobra.Command{ + Use: "params [flags]", + Short: "Get the params for the x/tokenfactory module", + Args: cobra.ExactArgs(0), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.Params(cmd.Context(), &types.QueryParamsRequest{}) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetCmdDenomAuthorityMetadata returns the authority metadata for a queried denom +func GetCmdDenomAuthorityMetadata() *cobra.Command { + cmd := &cobra.Command{ + Use: "denom-authority-metadata [denom] [flags]", + Short: "Get the authority metadata for a specific denom", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.DenomAuthorityMetadata(cmd.Context(), &types.QueryDenomAuthorityMetadataRequest{ + Denom: args[0], + }) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} + +// GetCmdDenomsFromCreator a command to get a list of all tokens created by a specific creator address +func GetCmdDenomsFromCreator() *cobra.Command { + cmd := &cobra.Command{ + Use: "denoms-from-creator [creator address] [flags]", + Short: "Returns a list of all tokens created by a specific creator address", + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx, err := client.GetClientQueryContext(cmd) + if err != nil { + return err + } + queryClient := types.NewQueryClient(clientCtx) + + res, err := queryClient.DenomsFromCreator(cmd.Context(), &types.QueryDenomsFromCreatorRequest{ + Creator: args[0], + }) + if err != nil { + return err + } + + return clientCtx.PrintProto(res) + }, + } + + flags.AddQueryFlagsToCmd(cmd) + + return cmd +} diff --git a/x/tokenfactory/client/cli/tx.go b/x/tokenfactory/client/cli/tx.go new file mode 100644 index 0000000..9b0aeff --- /dev/null +++ b/x/tokenfactory/client/cli/tx.go @@ -0,0 +1,200 @@ +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/x/tokenfactory/types" +) + +// GetTxCmd returns the transaction commands for this module +func GetTxCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: types.ModuleName, + Short: fmt.Sprintf("%s transactions subcommands", types.ModuleName), + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, + } + + cmd.AddCommand( + NewCreateDenomCmd(), + NewMintCmd(), + NewBurnCmd(), + // NewForceTransferCmd(), + NewChangeAdminCmd(), + ) + + return cmd +} + +// NewCreateDenomCmd broadcast MsgCreateDenom +func NewCreateDenomCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "create-denom [subdenom] [flags]", + Short: "create a new denom from an account", + Args: cobra.ExactArgs(1), + 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 + } + + msg := types.NewMsgCreateDenom( + clientCtx.GetFromAddress().String(), + args[0], + ) + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} + +// NewMintCmd broadcast MsgMint +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.", + Args: cobra.ExactArgs(1), + 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 + } + + amount, err := sdk.ParseCoinNormalized(args[0]) + if err != nil { + return err + } + + msg := types.NewMsgMint( + clientCtx.GetFromAddress().String(), + amount, + ) + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} + +// NewBurnCmd broadcast MsgBurn +func NewBurnCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "burn [amount] [flags]", + Short: "Burn tokens from an 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) + if err != nil { + return err + } + + txf, err := tx.NewFactoryCLI(clientCtx, cmd.Flags()) + if err != nil { + return err + } + + amount, err := sdk.ParseCoinNormalized(args[0]) + if err != nil { + return err + } + + msg := types.NewMsgBurn( + clientCtx.GetFromAddress().String(), + amount, + ) + + 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 := 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 +// } + +// NewChangeAdminCmd broadcast MsgChangeAdmin +func NewChangeAdminCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "change-admin [denom] [new-admin-address] [flags]", + Short: "Changes the admin address for a factory-created denom. 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 + } + + msg := types.NewMsgChangeAdmin( + clientCtx.GetFromAddress().String(), + args[0], + args[1], + ) + + return tx.GenerateOrBroadcastTxWithFactory(clientCtx, txf, msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + return cmd +} diff --git a/x/tokenfactory/keeper/admins.go b/x/tokenfactory/keeper/admins.go new file mode 100644 index 0000000..665895b --- /dev/null +++ b/x/tokenfactory/keeper/admins.go @@ -0,0 +1,49 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/gogoproto/proto" + + "github.com/terpnetwork/terp-core/x/tokenfactory/types" +) + +// GetAuthorityMetadata returns the authority metadata for a specific denom +func (k Keeper) GetAuthorityMetadata(ctx sdk.Context, denom string) (types.DenomAuthorityMetadata, error) { + bz := k.GetDenomPrefixStore(ctx, denom).Get([]byte(types.DenomAuthorityMetadataKey)) + + metadata := types.DenomAuthorityMetadata{} + err := proto.Unmarshal(bz, &metadata) + if err != nil { + return types.DenomAuthorityMetadata{}, err + } + return metadata, nil +} + +// setAuthorityMetadata stores authority metadata for a specific denom +func (k Keeper) setAuthorityMetadata(ctx sdk.Context, denom string, metadata types.DenomAuthorityMetadata) error { + err := metadata.Validate() + if err != nil { + return err + } + + store := k.GetDenomPrefixStore(ctx, denom) + + bz, err := proto.Marshal(&metadata) + if err != nil { + return err + } + + store.Set([]byte(types.DenomAuthorityMetadataKey), bz) + return nil +} + +func (k Keeper) setAdmin(ctx sdk.Context, denom string, admin string) error { + metadata, err := k.GetAuthorityMetadata(ctx, denom) + if err != nil { + return err + } + + metadata.Admin = admin + + return k.setAuthorityMetadata(ctx, denom, metadata) +} diff --git a/x/tokenfactory/keeper/admins_test.go b/x/tokenfactory/keeper/admins_test.go new file mode 100644 index 0000000..335320f --- /dev/null +++ b/x/tokenfactory/keeper/admins_test.go @@ -0,0 +1,404 @@ +package keeper_test + +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" +) + +func (suite *KeeperTestSuite) TestAdminMsgs() { + addr0bal := int64(0) + addr1bal := int64(0) + + bankKeeper := suite.App.BankKeeper + + suite.CreateDefaultDenom() + // Make sure that the admin is set correctly + queryRes, err := suite.queryClient.DenomAuthorityMetadata(suite.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{ + Denom: suite.defaultDenom, + }) + suite.Require().NoError(err) + suite.Require().Equal(suite.TestAccs[0].String(), queryRes.AuthorityMetadata.Admin) + + // Test minting to admins own account + _, err = suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMint(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 10))) + addr0bal += 10 + 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 burning from own account + _, err = suite.msgServer.Burn(sdk.WrapSDKContext(suite.Ctx), types.NewMsgBurn(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 5))) + suite.Require().NoError(err) + suite.Require().True(bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom).Amount.Int64() == addr1bal) + + // Test Change Admin + _, err = suite.msgServer.ChangeAdmin(sdk.WrapSDKContext(suite.Ctx), types.NewMsgChangeAdmin(suite.TestAccs[0].String(), suite.defaultDenom, suite.TestAccs[1].String())) + suite.Require().NoError(err) + queryRes, err = suite.queryClient.DenomAuthorityMetadata(suite.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{ + Denom: suite.defaultDenom, + }) + suite.Require().NoError(err) + suite.Require().Equal(suite.TestAccs[1].String(), queryRes.AuthorityMetadata.Admin) + + // Make sure old admin can no longer do actions + _, err = suite.msgServer.Burn(sdk.WrapSDKContext(suite.Ctx), types.NewMsgBurn(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 5))) + suite.Require().Error(err) + + // Make sure the new admin works + _, err = suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMint(suite.TestAccs[1].String(), sdk.NewInt64Coin(suite.defaultDenom, 5))) + addr1bal += 5 + suite.Require().NoError(err) + suite.Require().True(bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[1], suite.defaultDenom).Amount.Int64() == addr1bal) + + // Try setting admin to empty + _, err = suite.msgServer.ChangeAdmin(sdk.WrapSDKContext(suite.Ctx), types.NewMsgChangeAdmin(suite.TestAccs[1].String(), suite.defaultDenom, "")) + suite.Require().NoError(err) + queryRes, err = suite.queryClient.DenomAuthorityMetadata(suite.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{ + Denom: suite.defaultDenom, + }) + suite.Require().NoError(err) + suite.Require().Equal("", queryRes.AuthorityMetadata.Admin) +} + +// TestMintDenom ensures the following properties of the MintMessage: +// * Noone can mint tokens for a denom that doesn't exist +// * 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 + + // Create a denom + suite.CreateDefaultDenom() + + for _, tc := range []struct { + desc string + amount int64 + mintDenom string + admin string + valid bool + }{ + { + desc: "denom does not exist", + amount: 10, + mintDenom: "factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", + admin: suite.TestAccs[0].String(), + valid: false, + }, + { + desc: "mint is not by the admin", + amount: 10, + mintDenom: suite.defaultDenom, + admin: suite.TestAccs[1].String(), + valid: false, + }, + { + desc: "success case", + amount: 10, + mintDenom: suite.defaultDenom, + admin: suite.TestAccs[0].String(), + valid: 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 + 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)) + } else { + suite.Require().Error(err) + } + }) + } +} + +func (suite *KeeperTestSuite) TestBurnDenom() { + var addr0bal int64 + + // 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 + + for _, tc := range []struct { + desc string + amount int64 + burnDenom string + admin string + valid bool + }{ + { + desc: "denom does not exist", + amount: 10, + burnDenom: "factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", + admin: suite.TestAccs[0].String(), + valid: false, + }, + { + desc: "burn is not by the admin", + amount: 10, + burnDenom: suite.defaultDenom, + admin: suite.TestAccs[1].String(), + valid: false, + }, + { + desc: "burn amount is bigger than minted amount", + amount: 1000, + burnDenom: suite.defaultDenom, + admin: suite.TestAccs[1].String(), + valid: false, + }, + { + desc: "success case", + amount: 10, + burnDenom: suite.defaultDenom, + admin: suite.TestAccs[0].String(), + valid: true, + }, + } { + 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 + 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)) + } 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)) + } + }) + } +} + +func (suite *KeeperTestSuite) TestChangeAdminDenom() { + for _, tc := range []struct { + desc string + msgChangeAdmin func(denom string) *types.MsgChangeAdmin + expectedChangeAdminPass bool + expectedAdminIndex int + msgMint func(denom string) *types.MsgMint + expectedMintPass bool + }{ + { + desc: "creator admin can't mint after setting to '' ", + msgChangeAdmin: func(denom string) *types.MsgChangeAdmin { + return types.NewMsgChangeAdmin(suite.TestAccs[0].String(), denom, "") + }, + expectedChangeAdminPass: true, + expectedAdminIndex: -1, + msgMint: func(denom string) *types.MsgMint { + return types.NewMsgMint(suite.TestAccs[0].String(), sdk.NewInt64Coin(denom, 5)) + }, + expectedMintPass: false, + }, + { + desc: "non-admins can't change the existing admin", + msgChangeAdmin: func(denom string) *types.MsgChangeAdmin { + return types.NewMsgChangeAdmin(suite.TestAccs[1].String(), denom, suite.TestAccs[2].String()) + }, + expectedChangeAdminPass: false, + expectedAdminIndex: 0, + }, + { + desc: "success change admin", + msgChangeAdmin: func(denom string) *types.MsgChangeAdmin { + return types.NewMsgChangeAdmin(suite.TestAccs[0].String(), denom, suite.TestAccs[1].String()) + }, + expectedAdminIndex: 1, + expectedChangeAdminPass: true, + msgMint: func(denom string) *types.MsgMint { + return types.NewMsgMint(suite.TestAccs[1].String(), sdk.NewInt64Coin(denom, 5)) + }, + expectedMintPass: true, + }, + } { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + // setup test + suite.SetupTest() + + // Create a denom and mint + res, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin")) + suite.Require().NoError(err) + + testDenom := res.GetNewTokenDenom() + + _, err = suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMint(suite.TestAccs[0].String(), sdk.NewInt64Coin(testDenom, 10))) + suite.Require().NoError(err) + + _, err = suite.msgServer.ChangeAdmin(sdk.WrapSDKContext(suite.Ctx), tc.msgChangeAdmin(testDenom)) + if tc.expectedChangeAdminPass { + suite.Require().NoError(err) + } else { + suite.Require().Error(err) + } + + queryRes, err := suite.queryClient.DenomAuthorityMetadata(suite.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{ + Denom: testDenom, + }) + suite.Require().NoError(err) + + // expectedAdminIndex with negative value is assumed as admin with value of "" + const emptyStringAdminIndexFlag = -1 + if tc.expectedAdminIndex == emptyStringAdminIndexFlag { + suite.Require().Equal("", queryRes.AuthorityMetadata.Admin) + } else { + suite.Require().Equal(suite.TestAccs[tc.expectedAdminIndex].String(), queryRes.AuthorityMetadata.Admin) + } + + // we test mint to test if admin authority is performed properly after admin change. + if tc.msgMint != nil { + _, err := suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), tc.msgMint(testDenom)) + if tc.expectedMintPass { + suite.Require().NoError(err) + } else { + suite.Require().Error(err) + } + } + }) + } +} + +func (suite *KeeperTestSuite) TestSetDenomMetaData() { + // setup test + suite.SetupTest() + suite.CreateDefaultDenom() + + for _, tc := range []struct { + desc string + msgSetDenomMetadata types.MsgSetDenomMetadata + expectedPass bool + }{ + { + desc: "successful set denom metadata", + msgSetDenomMetadata: *types.NewMsgSetDenomMetadata(suite.TestAccs[0].String(), banktypes.Metadata{ + Description: "yeehaw", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: suite.defaultDenom, + Exponent: 0, + }, + { + Denom: "uosmo", + Exponent: 6, + }, + }, + Base: suite.defaultDenom, + Display: "uosmo", + Name: "OSMO", + Symbol: "OSMO", + }), + expectedPass: true, + }, + { + desc: "non existent factory denom name", + msgSetDenomMetadata: *types.NewMsgSetDenomMetadata(suite.TestAccs[0].String(), banktypes.Metadata{ + Description: "yeehaw", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: fmt.Sprintf("factory/%s/litecoin", suite.TestAccs[0].String()), + Exponent: 0, + }, + { + Denom: "uosmo", + Exponent: 6, + }, + }, + Base: fmt.Sprintf("factory/%s/litecoin", suite.TestAccs[0].String()), + Display: "uosmo", + Name: "OSMO", + Symbol: "OSMO", + }), + expectedPass: false, + }, + { + desc: "non-factory denom", + msgSetDenomMetadata: *types.NewMsgSetDenomMetadata(suite.TestAccs[0].String(), banktypes.Metadata{ + Description: "yeehaw", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: "uosmo", + Exponent: 0, + }, + { + Denom: "uosmoo", + Exponent: 6, + }, + }, + Base: "uosmo", + Display: "uosmoo", + Name: "OSMO", + Symbol: "OSMO", + }), + expectedPass: false, + }, + { + desc: "wrong admin", + msgSetDenomMetadata: *types.NewMsgSetDenomMetadata(suite.TestAccs[1].String(), banktypes.Metadata{ + Description: "yeehaw", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: suite.defaultDenom, + Exponent: 0, + }, + { + Denom: "uosmo", + Exponent: 6, + }, + }, + Base: suite.defaultDenom, + Display: "uosmo", + Name: "OSMO", + Symbol: "OSMO", + }), + expectedPass: false, + }, + { + desc: "invalid metadata (missing display denom unit)", + msgSetDenomMetadata: *types.NewMsgSetDenomMetadata(suite.TestAccs[0].String(), banktypes.Metadata{ + Description: "yeehaw", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: suite.defaultDenom, + Exponent: 0, + }, + }, + Base: suite.defaultDenom, + Display: "uosmo", + Name: "OSMO", + Symbol: "OSMO", + }), + expectedPass: false, + }, + } { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + bankKeeper := suite.App.BankKeeper + res, err := suite.msgServer.SetDenomMetadata(sdk.WrapSDKContext(suite.Ctx), &tc.msgSetDenomMetadata) + if tc.expectedPass { + suite.Require().NoError(err) + suite.Require().NotNil(res) + + md, found := bankKeeper.GetDenomMetaData(suite.Ctx, suite.defaultDenom) + suite.Require().True(found) + suite.Require().Equal(tc.msgSetDenomMetadata.Metadata.Name, md.Name) + } else { + suite.Require().Error(err) + } + }) + } +} diff --git a/x/tokenfactory/keeper/bankactions.go b/x/tokenfactory/keeper/bankactions.go new file mode 100644 index 0000000..803c4c3 --- /dev/null +++ b/x/tokenfactory/keeper/bankactions.go @@ -0,0 +1,73 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/x/tokenfactory/types" +) + +func (k Keeper) mintTo(ctx sdk.Context, amount sdk.Coin, mintTo string) error { + // verify that denom is an x/tokenfactory denom + _, _, err := types.DeconstructDenom(amount.Denom) + if err != nil { + return err + } + + err = k.bankKeeper.MintCoins(ctx, types.ModuleName, sdk.NewCoins(amount)) + if err != nil { + return err + } + + addr, err := sdk.AccAddressFromBech32(mintTo) + if err != nil { + return err + } + + return k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, + addr, + sdk.NewCoins(amount)) +} + +func (k Keeper) burnFrom(ctx sdk.Context, amount sdk.Coin, burnFrom string) error { + // verify that denom is an x/tokenfactory denom + _, _, err := types.DeconstructDenom(amount.Denom) + if err != nil { + return err + } + + addr, err := sdk.AccAddressFromBech32(burnFrom) + if err != nil { + return err + } + + err = k.bankKeeper.SendCoinsFromAccountToModule(ctx, + addr, + types.ModuleName, + sdk.NewCoins(amount)) + if err != nil { + return err + } + + 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 + // verify that denom is an x/tokenfactory denom + _, _, err := types.DeconstructDenom(amount.Denom) + if err != nil { + return err + } + + fromSdkAddr, err := sdk.AccAddressFromBech32(fromAddr) + if err != nil { + return err + } + + toSdkAddr, err := sdk.AccAddressFromBech32(toAddr) + if err != nil { + return err + } + + return k.bankKeeper.SendCoins(ctx, fromSdkAddr, toSdkAddr, sdk.NewCoins(amount)) +} diff --git a/x/tokenfactory/keeper/createdenom.go b/x/tokenfactory/keeper/createdenom.go new file mode 100644 index 0000000..4c5fe3e --- /dev/null +++ b/x/tokenfactory/keeper/createdenom.go @@ -0,0 +1,86 @@ +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" +) + +// ConvertToBaseToken converts a fee amount in a whitelisted fee token to the base fee token amount +func (k Keeper) CreateDenom(ctx sdk.Context, creatorAddr string, subdenom string) (newTokenDenom string, err error) { + denom, err := k.validateCreateDenom(ctx, creatorAddr, subdenom) + if err != nil { + return "", err + } + + err = k.chargeForCreateDenom(ctx, creatorAddr, subdenom) + if err != nil { + return "", err + } + + err = k.createDenomAfterValidation(ctx, creatorAddr, denom) + return denom, err +} + +// Runs CreateDenom logic after the charge and all denom validation has been handled. +// Made into a second function for genesis initialization. +func (k Keeper) createDenomAfterValidation(ctx sdk.Context, creatorAddr string, denom string) (err error) { + denomMetaData := banktypes.Metadata{ + DenomUnits: []*banktypes.DenomUnit{{ + Denom: denom, + Exponent: 0, + }}, + Base: denom, + } + + k.bankKeeper.SetDenomMetaData(ctx, denomMetaData) + + authorityMetadata := types.DenomAuthorityMetadata{ + Admin: creatorAddr, + } + err = k.setAuthorityMetadata(ctx, denom, authorityMetadata) + if err != nil { + return err + } + + k.addDenomFromCreator(ctx, creatorAddr, denom) + return nil +} + +func (k Keeper) validateCreateDenom(ctx sdk.Context, creatorAddr string, subdenom string) (newTokenDenom string, err error) { + // 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") + } + + denom, err := types.GetTokenDenom(creatorAddr, subdenom) + if err != nil { + return "", err + } + + _, found := k.bankKeeper.GetDenomMetaData(ctx, denom) + if found { + return "", types.ErrDenomExists + } + + 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 { + return err + } + } + return nil +} diff --git a/x/tokenfactory/keeper/createdenom_test.go b/x/tokenfactory/keeper/createdenom_test.go new file mode 100644 index 0000000..1900bbf --- /dev/null +++ b/x/tokenfactory/keeper/createdenom_test.go @@ -0,0 +1,163 @@ +package keeper_test + +import ( + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/x/tokenfactory/testhelpers" + "github.com/terpnetwork/terp-core/x/tokenfactory/types" +) + +func (suite *KeeperTestSuite) TestMsgCreateDenom() { + var ( + tokenFactoryKeeper = suite.App.TokenFactoryKeeper + bankKeeper = suite.App.BankKeeper + denomCreationFee = tokenFactoryKeeper.GetParams(suite.Ctx).DenomCreationFee + ) + + // Get balance of acc 0 before creating a denom + preCreateBalance := bankKeeper.GetBalance(suite.Ctx, suite.TestAccs[0], denomCreationFee[0].Denom) + + // Creating a denom should work + res, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin")) + suite.Require().NoError(err) + suite.Require().NotEmpty(res.GetNewTokenDenom()) + + // Make sure that the admin is set correctly + queryRes, err := suite.queryClient.DenomAuthorityMetadata(suite.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{ + Denom: res.GetNewTokenDenom(), + }) + suite.Require().NoError(err) + suite.Require().Equal(suite.TestAccs[0].String(), queryRes.AuthorityMetadata.Admin) + + // 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])) + + // Make sure that a second version of the same denom can't be recreated + _, err = suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin")) + suite.Require().Error(err) + + // Creating a second denom should work + res, err = suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "litecoin")) + suite.Require().NoError(err) + suite.Require().NotEmpty(res.GetNewTokenDenom()) + + // Try querying all the denoms created by suite.TestAccs[0] + queryRes2, err := suite.queryClient.DenomsFromCreator(suite.Ctx.Context(), &types.QueryDenomsFromCreatorRequest{ + Creator: suite.TestAccs[0].String(), + }) + suite.Require().NoError(err) + suite.Require().Len(queryRes2.Denoms, 2) + + // Make sure that a second account can create a denom with the same subdenom + res, err = suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[1].String(), "bitcoin")) + suite.Require().NoError(err) + suite.Require().NotEmpty(res.GetNewTokenDenom()) + + // Make sure that an address with a "/" in it can't create denoms + _, err = suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom("osmosis.eth/creator", "bitcoin")) + suite.Require().Error(err) +} + +func (suite *KeeperTestSuite) TestCreateDenom() { + var ( + primaryDenom = types.DefaultParams().DenomCreationFee[0].Denom + secondaryDenom = testhelpers.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} + largeCreationFee = types.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, sdk.NewInt(5000000000)))} + ) + + for _, tc := range []struct { + desc string + denomCreationFee types.Params + setup func() + subdenom string + valid bool + }{ + { + desc: "subdenom too long", + denomCreationFee: defaultDenomCreationFee, + subdenom: "assadsadsadasdasdsadsadsadsadsadsadsklkadaskkkdasdasedskhanhassyeunganassfnlksdflksafjlkasd", + valid: false, + }, + { + desc: "subdenom and creator pair already exists", + denomCreationFee: defaultDenomCreationFee, + setup: func() { + _, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin")) + suite.Require().NoError(err) + }, + subdenom: "bitcoin", + valid: false, + }, + { + desc: "success case: defaultDenomCreationFee", + denomCreationFee: defaultDenomCreationFee, + subdenom: "evmos", + valid: true, + }, + { + desc: "success case: twoDenomCreationFee", + denomCreationFee: twoDenomCreationFee, + subdenom: "catcoin", + valid: true, + }, + { + desc: "success case: nilCreationFee", + denomCreationFee: nilCreationFee, + subdenom: "czcoin", + valid: true, + }, + { + desc: "account doesn't have enough to pay for denom creation fee", + denomCreationFee: largeCreationFee, + subdenom: "tooexpensive", + valid: false, + }, + { + desc: "subdenom having invalid characters", + denomCreationFee: defaultDenomCreationFee, + subdenom: "bit/***///&&&/coin", + valid: false, + }, + } { + suite.SetupTest() + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + if tc.setup != nil { + tc.setup() + } + tokenFactoryKeeper := suite.App.TokenFactoryKeeper + bankKeeper := suite.App.BankKeeper + // Set denom creation fee in params + tokenFactoryKeeper.SetParams(suite.Ctx, tc.denomCreationFee) + 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]) + 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]) + if tc.valid { + suite.Require().NoError(err) + suite.Require().True(preCreateBalance.Sub(postCreateBalance...).IsEqual(denomCreationFee)) + + // Make sure that the admin is set correctly + queryRes, err := suite.queryClient.DenomAuthorityMetadata(suite.Ctx.Context(), &types.QueryDenomAuthorityMetadataRequest{ + Denom: res.GetNewTokenDenom(), + }) + + suite.Require().NoError(err) + suite.Require().Equal(suite.TestAccs[0].String(), queryRes.AuthorityMetadata.Admin) + + } else { + suite.Require().Error(err) + // Ensure we don't charge if we expect an error + suite.Require().True(preCreateBalance.IsEqual(postCreateBalance)) + } + }) + } +} diff --git a/x/tokenfactory/keeper/creators.go b/x/tokenfactory/keeper/creators.go new file mode 100644 index 0000000..570d54b --- /dev/null +++ b/x/tokenfactory/keeper/creators.go @@ -0,0 +1,27 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (k Keeper) addDenomFromCreator(ctx sdk.Context, creator, denom string) { + store := k.GetCreatorPrefixStore(ctx, creator) + store.Set([]byte(denom), []byte(denom)) +} + +func (k Keeper) GetDenomsFromCreator(ctx sdk.Context, creator string) []string { + store := k.GetCreatorPrefixStore(ctx, creator) + + iterator := store.Iterator(nil, nil) + defer iterator.Close() + + denoms := []string{} + for ; iterator.Valid(); iterator.Next() { + denoms = append(denoms, string(iterator.Key())) + } + return denoms +} + +func (k Keeper) GetAllDenomsIterator(ctx sdk.Context) sdk.Iterator { + return k.GetCreatorsPrefixStore(ctx).Iterator(nil, nil) +} diff --git a/x/tokenfactory/keeper/genesis.go b/x/tokenfactory/keeper/genesis.go new file mode 100644 index 0000000..52577e8 --- /dev/null +++ b/x/tokenfactory/keeper/genesis.go @@ -0,0 +1,58 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/x/tokenfactory/types" +) + +// InitGenesis initializes the tokenfactory module's state from a provided genesis +// state. +func (k Keeper) InitGenesis(ctx sdk.Context, genState types.GenesisState) { + k.CreateModuleAccount(ctx) + + if genState.Params.DenomCreationFee == nil { + genState.Params.DenomCreationFee = sdk.NewCoins() + } + k.SetParams(ctx, genState.Params) + + for _, genDenom := range genState.GetFactoryDenoms() { + creator, _, err := types.DeconstructDenom(genDenom.GetDenom()) + if err != nil { + panic(err) + } + err = k.createDenomAfterValidation(ctx, creator, genDenom.GetDenom()) + if err != nil { + panic(err) + } + err = k.setAuthorityMetadata(ctx, genDenom.GetDenom(), genDenom.GetAuthorityMetadata()) + if err != nil { + panic(err) + } + } +} + +// ExportGenesis returns the tokenfactory module's exported genesis. +func (k Keeper) ExportGenesis(ctx sdk.Context) *types.GenesisState { + genDenoms := []types.GenesisDenom{} + iterator := k.GetAllDenomsIterator(ctx) + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + denom := string(iterator.Value()) + + authorityMetadata, err := k.GetAuthorityMetadata(ctx, denom) + if err != nil { + panic(err) + } + + genDenoms = append(genDenoms, types.GenesisDenom{ + Denom: denom, + AuthorityMetadata: authorityMetadata, + }) + } + + return &types.GenesisState{ + FactoryDenoms: genDenoms, + Params: k.GetParams(ctx), + } +} diff --git a/x/tokenfactory/keeper/genesis_test.go b/x/tokenfactory/keeper/genesis_test.go new file mode 100644 index 0000000..a04ef9b --- /dev/null +++ b/x/tokenfactory/keeper/genesis_test.go @@ -0,0 +1,59 @@ +package keeper_test + +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" +) + +func (suite *KeeperTestSuite) TestGenesis() { + genesisState := types.GenesisState{ + FactoryDenoms: []types.GenesisDenom{ + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + }, + }, + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/diff-admin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "cosmos15czt5nhlnvayqq37xun9s9yus0d6y26dx74r5p", + }, + }, + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/litecoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + }, + }, + }, + } + + suite.SetupTestForInitGenesis() + app := suite.App + + // Test both with bank denom metadata set, and not set. + for i, denom := range genesisState.FactoryDenoms { + // hacky, sets bank metadata to exist if i != 0, to cover both cases. + if i != 0 { + app.BankKeeper.SetDenomMetaData(suite.Ctx, banktypes.Metadata{Base: denom.GetDenom()}) + } + } + + // 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)}}) + 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)) + suite.Require().NotNil(tokenfactoryModuleAccount) + + exportedGenesis := app.TokenFactoryKeeper.ExportGenesis(suite.Ctx) + suite.Require().NotNil(exportedGenesis) + suite.Require().Equal(genesisState, *exportedGenesis) +} diff --git a/x/tokenfactory/keeper/grpc_query.go b/x/tokenfactory/keeper/grpc_query.go new file mode 100644 index 0000000..2ee7191 --- /dev/null +++ b/x/tokenfactory/keeper/grpc_query.go @@ -0,0 +1,35 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/x/tokenfactory/types" +) + +var _ types.QueryServer = Keeper{} + +func (k Keeper) Params(ctx context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + params := k.GetParams(sdkCtx) + + return &types.QueryParamsResponse{Params: params}, nil +} + +func (k Keeper) DenomAuthorityMetadata(ctx context.Context, req *types.QueryDenomAuthorityMetadataRequest) (*types.QueryDenomAuthorityMetadataResponse, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + + authorityMetadata, err := k.GetAuthorityMetadata(sdkCtx, req.GetDenom()) + if err != nil { + return nil, err + } + + return &types.QueryDenomAuthorityMetadataResponse{AuthorityMetadata: authorityMetadata}, nil +} + +func (k Keeper) DenomsFromCreator(ctx context.Context, req *types.QueryDenomsFromCreatorRequest) (*types.QueryDenomsFromCreatorResponse, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + denoms := k.GetDenomsFromCreator(sdkCtx, req.GetCreator()) + return &types.QueryDenomsFromCreatorResponse{Denoms: denoms}, nil +} diff --git a/x/tokenfactory/keeper/keeper.go b/x/tokenfactory/keeper/keeper.go new file mode 100644 index 0000000..2ce23cd --- /dev/null +++ b/x/tokenfactory/keeper/keeper.go @@ -0,0 +1,82 @@ +package keeper + +import ( + "fmt" + + "github.com/cometbft/cometbft/libs/log" + + "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" +) + +type ( + Keeper struct { + storeKey storetypes.StoreKey + + paramSpace paramtypes.Subspace + + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper + communityPoolKeeper types.CommunityPoolKeeper + } +) + +// NewKeeper returns a new instance of the x/tokenfactory keeper +func NewKeeper( + storeKey storetypes.StoreKey, + paramSpace paramtypes.Subspace, + accountKeeper types.AccountKeeper, + bankKeeper types.BankKeeper, + communityPoolKeeper types.CommunityPoolKeeper, +) Keeper { + if !paramSpace.HasKeyTable() { + paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) + } + + return Keeper{ + storeKey: storeKey, + paramSpace: paramSpace, + + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, + communityPoolKeeper: communityPoolKeeper, + } +} + +// 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)) +} + +// GetDenomPrefixStore returns the substore for a specific denom +func (k Keeper) GetDenomPrefixStore(ctx sdk.Context, denom string) sdk.KVStore { + store := ctx.KVStore(k.storeKey) + return prefix.NewStore(store, types.GetDenomPrefixStore(denom)) +} + +// GetCreatorPrefixStore returns the substore for a specific creator address +func (k Keeper) GetCreatorPrefixStore(ctx sdk.Context, creator string) sdk.KVStore { + store := ctx.KVStore(k.storeKey) + return prefix.NewStore(store, types.GetCreatorPrefix(creator)) +} + +// GetCreatorsPrefixStore returns the substore that contains a list of creators +func (k Keeper) GetCreatorsPrefixStore(ctx sdk.Context) sdk.KVStore { + store := ctx.KVStore(k.storeKey) + return prefix.NewStore(store, types.GetCreatorsPrefix()) +} + +// CreateModuleAccount creates a module account with minting and burning capabilities +// This account isn't intended to store any coins, +// it purely mints and burns them on behalf of the admin of respective denoms, +// and sends to the relevant address. +func (k Keeper) CreateModuleAccount(ctx sdk.Context) { + moduleAcc := authtypes.NewEmptyModuleAccount(types.ModuleName, authtypes.Minter, authtypes.Burner) + k.accountKeeper.SetModuleAccount(ctx, moduleAcc) +} diff --git a/x/tokenfactory/keeper/keeper_test.go b/x/tokenfactory/keeper/keeper_test.go new file mode 100644 index 0000000..75581e3 --- /dev/null +++ b/x/tokenfactory/keeper/keeper_test.go @@ -0,0 +1,64 @@ +package keeper_test + +import ( + "testing" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/suite" + + "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" +) + +type KeeperTestSuite struct { + apptesting.KeeperTestHelper + + queryClient types.QueryClient + msgServer types.MsgServer + // defaultDenom is on the suite, as it depends on the creator test address. + defaultDenom string +} + +func TestKeeperTestSuite(t *testing.T) { + suite.Run(t, new(KeeperTestSuite)) +} + +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)) + for _, acc := range suite.TestAccs { + suite.FundAcc(acc, fundAccsAmount) + } + + suite.queryClient = types.NewQueryClient(suite.QueryHelper) + suite.msgServer = keeper.NewMsgServerImpl(suite.App.TokenFactoryKeeper) +} + +func (suite *KeeperTestSuite) CreateDefaultDenom() { + res, _ := suite.msgServer.CreateDenom(sdk.WrapSDKContext(suite.Ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin")) + suite.defaultDenom = res.GetNewTokenDenom() +} + +func (suite *KeeperTestSuite) TestCreateModuleAccount() { + app := suite.App + + // remove module account + tokenfactoryModuleAccount := app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName)) + app.AccountKeeper.RemoveAccount(suite.Ctx, tokenfactoryModuleAccount) + + // ensure module account was removed + suite.Ctx = app.BaseApp.NewContext(false, tmproto.Header{}) + tokenfactoryModuleAccount = app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName)) + suite.Require().Nil(tokenfactoryModuleAccount) + + // create module account + app.TokenFactoryKeeper.CreateModuleAccount(suite.Ctx) + + // check that the module account is now initialized + tokenfactoryModuleAccount = app.AccountKeeper.GetAccount(suite.Ctx, app.AccountKeeper.GetModuleAddress(types.ModuleName)) + suite.Require().NotNil(tokenfactoryModuleAccount) +} diff --git a/x/tokenfactory/keeper/msg_server.go b/x/tokenfactory/keeper/msg_server.go new file mode 100644 index 0000000..9bd98ed --- /dev/null +++ b/x/tokenfactory/keeper/msg_server.go @@ -0,0 +1,191 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + + "github.com/terpnetwork/terp-core/x/tokenfactory/types" +) + +type msgServer struct { + Keeper +} + +// NewMsgServerImpl returns an implementation of the MsgServer interface +// for the provided Keeper. +func NewMsgServerImpl(keeper Keeper) types.MsgServer { + return &msgServer{Keeper: keeper} +} + +var _ types.MsgServer = msgServer{} + +func (server msgServer) CreateDenom(goCtx context.Context, msg *types.MsgCreateDenom) (*types.MsgCreateDenomResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + denom, err := server.Keeper.CreateDenom(ctx, msg.Sender, msg.Subdenom) + if err != nil { + return nil, err + } + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + types.TypeMsgCreateDenom, + sdk.NewAttribute(types.AttributeCreator, msg.Sender), + sdk.NewAttribute(types.AttributeNewTokenDenom, denom), + ), + }) + + return &types.MsgCreateDenomResponse{ + NewTokenDenom: denom, + }, nil +} + +func (server msgServer) Mint(goCtx context.Context, msg *types.MsgMint) (*types.MsgMintResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + // pay some extra gas cost to give a better error here. + _, denomExists := server.bankKeeper.GetDenomMetaData(ctx, msg.Amount.Denom) + if !denomExists { + return nil, types.ErrDenomDoesNotExist.Wrapf("denom: %s", msg.Amount.Denom) + } + + authorityMetadata, err := server.Keeper.GetAuthorityMetadata(ctx, msg.Amount.GetDenom()) + if err != nil { + return nil, err + } + + if msg.Sender != authorityMetadata.GetAdmin() { + return nil, types.ErrUnauthorized + } + + err = server.Keeper.mintTo(ctx, msg.Amount, msg.Sender) + if err != nil { + return nil, err + } + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + types.TypeMsgMint, + sdk.NewAttribute(types.AttributeMintToAddress, msg.Sender), + sdk.NewAttribute(types.AttributeAmount, msg.Amount.String()), + ), + }) + + return &types.MsgMintResponse{}, nil +} + +func (server msgServer) Burn(goCtx context.Context, msg *types.MsgBurn) (*types.MsgBurnResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + authorityMetadata, err := server.Keeper.GetAuthorityMetadata(ctx, msg.Amount.GetDenom()) + if err != nil { + return nil, err + } + + if msg.Sender != authorityMetadata.GetAdmin() { + return nil, types.ErrUnauthorized + } + + err = server.Keeper.burnFrom(ctx, msg.Amount, msg.Sender) + if err != nil { + return nil, err + } + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + types.TypeMsgBurn, + sdk.NewAttribute(types.AttributeBurnFromAddress, msg.Sender), + sdk.NewAttribute(types.AttributeAmount, msg.Amount.String()), + ), + }) + + return &types.MsgBurnResponse{}, nil +} + +// 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 msg.Sender != authorityMetadata.GetAdmin() { +// return nil, types.ErrUnauthorized +// } + +// err = server.Keeper.forceTransfer(ctx, msg.Amount, msg.TransferFromAddress, msg.TransferToAddress) +// if err != nil { +// return nil, err +// } + +// 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) + + authorityMetadata, err := server.Keeper.GetAuthorityMetadata(ctx, msg.Denom) + if err != nil { + return nil, err + } + + if msg.Sender != authorityMetadata.GetAdmin() { + return nil, types.ErrUnauthorized + } + + err = server.Keeper.setAdmin(ctx, msg.Denom, msg.NewAdmin) + if err != nil { + return nil, err + } + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + types.TypeMsgChangeAdmin, + sdk.NewAttribute(types.AttributeDenom, msg.GetDenom()), + sdk.NewAttribute(types.AttributeNewAdmin, msg.NewAdmin), + ), + }) + + return &types.MsgChangeAdminResponse{}, nil +} + +func (server msgServer) SetDenomMetadata(goCtx context.Context, msg *types.MsgSetDenomMetadata) (*types.MsgSetDenomMetadataResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + // Defense in depth validation of metadata + err := msg.Metadata.Validate() + if err != nil { + return nil, err + } + + authorityMetadata, err := server.Keeper.GetAuthorityMetadata(ctx, msg.Metadata.Base) + if err != nil { + return nil, err + } + + if msg.Sender != authorityMetadata.GetAdmin() { + return nil, types.ErrUnauthorized + } + + server.Keeper.bankKeeper.SetDenomMetaData(ctx, msg.Metadata) + + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + types.TypeMsgSetDenomMetadata, + sdk.NewAttribute(types.AttributeDenom, msg.Metadata.Base), + sdk.NewAttribute(types.AttributeDenomMetadata, msg.Metadata.String()), + ), + }) + + return &types.MsgSetDenomMetadataResponse{}, nil +} diff --git a/x/tokenfactory/keeper/msg_server_test.go b/x/tokenfactory/keeper/msg_server_test.go new file mode 100644 index 0000000..83f99a5 --- /dev/null +++ b/x/tokenfactory/keeper/msg_server_test.go @@ -0,0 +1,247 @@ +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" +) + +// TestMintDenomMsg tests TypeMsgMint message is emitted on a successful mint +func (suite *KeeperTestSuite) TestMintDenomMsg() { + // Create a denom + suite.CreateDefaultDenom() + + for _, tc := range []struct { + desc string + amount int64 + mintDenom string + admin string + valid bool + expectedMessageEvents int + }{ + { + desc: "denom does not exist", + amount: 10, + mintDenom: "factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", + admin: suite.TestAccs[0].String(), + valid: false, + }, + { + desc: "success case", + amount: 10, + mintDenom: suite.defaultDenom, + admin: suite.TestAccs[0].String(), + valid: true, + expectedMessageEvents: 1, + }, + } { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + ctx := suite.Ctx.WithEventManager(sdk.NewEventManager()) + suite.Require().Equal(0, len(ctx.EventManager().Events())) + // Test mint message + suite.msgServer.Mint(sdk.WrapSDKContext(ctx), types.NewMsgMint(tc.admin, sdk.NewInt64Coin(tc.mintDenom, 10))) //nolint:errcheck + // Ensure current number and type of event is emitted + suite.AssertEventEmitted(ctx, types.TypeMsgMint, tc.expectedMessageEvents) + }) + } +} + +// TestBurnDenomMsg tests TypeMsgBurn message is emitted on a successful burn +func (suite *KeeperTestSuite) TestBurnDenomMsg() { + // Create a denom. + suite.CreateDefaultDenom() + // mint 10 default token for testAcc[0] + suite.msgServer.Mint(sdk.WrapSDKContext(suite.Ctx), types.NewMsgMint(suite.TestAccs[0].String(), sdk.NewInt64Coin(suite.defaultDenom, 10))) //nolint:errcheck + + for _, tc := range []struct { + desc string + amount int64 + burnDenom string + admin string + valid bool + expectedMessageEvents int + }{ + { + desc: "denom does not exist", + burnDenom: "factory/osmo1t7egva48prqmzl59x5ngv4zx0dtrwewc9m7z44/evmos", + admin: suite.TestAccs[0].String(), + valid: false, + }, + { + desc: "success case", + burnDenom: suite.defaultDenom, + admin: suite.TestAccs[0].String(), + valid: true, + expectedMessageEvents: 1, + }, + } { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + ctx := suite.Ctx.WithEventManager(sdk.NewEventManager()) + suite.Require().Equal(0, len(ctx.EventManager().Events())) + // Test burn message + suite.msgServer.Burn(sdk.WrapSDKContext(ctx), types.NewMsgBurn(tc.admin, sdk.NewInt64Coin(tc.burnDenom, 10))) //nolint:errcheck + // Ensure current number and type of event is emitted + suite.AssertEventEmitted(ctx, types.TypeMsgBurn, tc.expectedMessageEvents) + }) + } +} + +// 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)))} + for _, tc := range []struct { + desc string + denomCreationFee types.Params + subdenom string + valid bool + expectedMessageEvents int + }{ + { + desc: "subdenom too long", + denomCreationFee: defaultDenomCreationFee, + subdenom: "assadsadsadasdasdsadsadsadsadsadsadsklkadaskkkdasdasedskhanhassyeunganassfnlksdflksafjlkasd", + valid: false, + }, + { + desc: "success case: defaultDenomCreationFee", + denomCreationFee: defaultDenomCreationFee, + subdenom: "evmos", + valid: true, + expectedMessageEvents: 1, + }, + } { + suite.SetupTest() + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + tokenFactoryKeeper := suite.App.TokenFactoryKeeper + 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) + // 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 + suite.AssertEventEmitted(ctx, types.TypeMsgCreateDenom, tc.expectedMessageEvents) + }) + } +} + +// TestChangeAdminDenomMsg tests TypeMsgChangeAdmin message is emitted on a successful admin change +func (suite *KeeperTestSuite) TestChangeAdminDenomMsg() { + for _, tc := range []struct { + desc string + msgChangeAdmin func(denom string) *types.MsgChangeAdmin + expectedChangeAdminPass bool + expectedAdminIndex int + msgMint func(denom string) *types.MsgMint + expectedMintPass bool + expectedMessageEvents int + }{ + { + desc: "non-admins can't change the existing admin", + msgChangeAdmin: func(denom string) *types.MsgChangeAdmin { + return types.NewMsgChangeAdmin(suite.TestAccs[1].String(), denom, suite.TestAccs[2].String()) + }, + expectedChangeAdminPass: false, + expectedAdminIndex: 0, + }, + { + desc: "success change admin", + msgChangeAdmin: func(denom string) *types.MsgChangeAdmin { + return types.NewMsgChangeAdmin(suite.TestAccs[0].String(), denom, suite.TestAccs[1].String()) + }, + expectedAdminIndex: 1, + expectedChangeAdminPass: true, + expectedMessageEvents: 1, + msgMint: func(denom string) *types.MsgMint { + return types.NewMsgMint(suite.TestAccs[1].String(), sdk.NewInt64Coin(denom, 5)) + }, + expectedMintPass: true, + }, + } { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + // setup test + suite.SetupTest() + ctx := suite.Ctx.WithEventManager(sdk.NewEventManager()) + suite.Require().Equal(0, len(ctx.EventManager().Events())) + // Create a denom and mint + res, err := suite.msgServer.CreateDenom(sdk.WrapSDKContext(ctx), types.NewMsgCreateDenom(suite.TestAccs[0].String(), "bitcoin")) + suite.Require().NoError(err) + testDenom := res.GetNewTokenDenom() + suite.msgServer.Mint(sdk.WrapSDKContext(ctx), types.NewMsgMint(suite.TestAccs[0].String(), sdk.NewInt64Coin(testDenom, 10))) //nolint:errcheck + // Test change admin message + suite.msgServer.ChangeAdmin(sdk.WrapSDKContext(ctx), tc.msgChangeAdmin(testDenom)) //nolint:errcheck + // Ensure current number and type of event is emitted + suite.AssertEventEmitted(ctx, types.TypeMsgChangeAdmin, tc.expectedMessageEvents) + }) + } +} + +// TestSetDenomMetaDataMsg tests TypeMsgSetDenomMetadata message is emitted on a successful denom metadata change +func (suite *KeeperTestSuite) TestSetDenomMetaDataMsg() { + // setup test + suite.SetupTest() + suite.CreateDefaultDenom() + + for _, tc := range []struct { + desc string + msgSetDenomMetadata types.MsgSetDenomMetadata + expectedPass bool + expectedMessageEvents int + }{ + { + desc: "successful set denom metadata", + msgSetDenomMetadata: *types.NewMsgSetDenomMetadata(suite.TestAccs[0].String(), banktypes.Metadata{ + Description: "yeehaw", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: suite.defaultDenom, + Exponent: 0, + }, + { + Denom: "uosmo", + Exponent: 6, + }, + }, + Base: suite.defaultDenom, + Display: "uosmo", + Name: "OSMO", + Symbol: "OSMO", + }), + expectedPass: true, + expectedMessageEvents: 1, + }, + { + desc: "non existent factory denom name", + msgSetDenomMetadata: *types.NewMsgSetDenomMetadata(suite.TestAccs[0].String(), banktypes.Metadata{ + Description: "yeehaw", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: fmt.Sprintf("factory/%s/litecoin", suite.TestAccs[0].String()), + Exponent: 0, + }, + { + Denom: "uosmo", + Exponent: 6, + }, + }, + Base: fmt.Sprintf("factory/%s/litecoin", suite.TestAccs[0].String()), + Display: "uosmo", + Name: "OSMO", + Symbol: "OSMO", + }), + expectedPass: false, + }, + } { + suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { + ctx := suite.Ctx.WithEventManager(sdk.NewEventManager()) + suite.Require().Equal(0, len(ctx.EventManager().Events())) + // Test set denom metadata message + suite.msgServer.SetDenomMetadata(sdk.WrapSDKContext(ctx), &tc.msgSetDenomMetadata) //nolint:errcheck + // Ensure current number and type of event is emitted + suite.AssertEventEmitted(ctx, types.TypeMsgSetDenomMetadata, tc.expectedMessageEvents) + }) + } +} diff --git a/x/tokenfactory/keeper/params.go b/x/tokenfactory/keeper/params.go new file mode 100644 index 0000000..9c9caf4 --- /dev/null +++ b/x/tokenfactory/keeper/params.go @@ -0,0 +1,18 @@ +package keeper + +import ( + "github.com/terpnetwork/terp-core/x/tokenfactory/types" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// GetParams returns the total set params. +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { + k.paramSpace.GetParamSet(ctx, ¶ms) + return params +} + +// SetParams sets the total set of params. +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.paramSpace.SetParamSet(ctx, ¶ms) +} diff --git a/x/tokenfactory/module.go b/x/tokenfactory/module.go new file mode 100644 index 0000000..fdac9f1 --- /dev/null +++ b/x/tokenfactory/module.go @@ -0,0 +1,220 @@ +/* +The tokenfactory module allows any account to create a new token with +the name `factory/{creator address}/{subdenom}`. + +- Mint and burn user denom to and form any account +- Create a transfer of their denom between any two accounts +- Change the admin. In the future, more admin capabilities may be added. +*/ +package tokenfactory + +import ( + "context" + "encoding/json" + "fmt" + "math/rand" + + 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" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} +) + +// ---------------------------------------------------------------------------- +// AppModuleBasic +// ---------------------------------------------------------------------------- + +// AppModuleBasic implements the AppModuleBasic interface for the capability module. +type AppModuleBasic struct{} + +func NewAppModuleBasic() AppModuleBasic { + return AppModuleBasic{} +} + +// Name returns the x/tokenfactory module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterCodec(cdc) +} + +// RegisterInterfaces registers the module's interface types +func (a AppModuleBasic) RegisterInterfaces(reg cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(reg) +} + +// DefaultGenesis returns the x/tokenfactory module's default genesis state. +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesis()) +} + +// ValidateGenesis performs genesis state validation for the x/tokenfactory module. +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var genState types.GenesisState + if err := cdc.UnmarshalJSON(bz, &genState); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return genState.Validate() +} + +// RegisterRESTRoutes registers the capability module's REST service handlers. +func (AppModuleBasic) RegisterRESTRoutes(clientCtx client.Context, rtr *mux.Router) { +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the module. +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)) //nolint:errcheck +} + +// GetTxCmd returns the x/tokenfactory module's root tx command. +func (a AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() +} + +// GetQueryCmd returns the x/tokenfactory module's root query command. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// ---------------------------------------------------------------------------- +// AppModule +// ---------------------------------------------------------------------------- + +// AppModule implements the AppModule interface for the capability module. +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper + accountKeeper types.AccountKeeper + bankKeeper types.BankKeeper +} + +func NewAppModule( + keeper keeper.Keeper, + accountKeeper types.AccountKeeper, + bankKeeper types.BankKeeper, +) AppModule { + return AppModule{ + AppModuleBasic: NewAppModuleBasic(), + keeper: keeper, + accountKeeper: accountKeeper, + bankKeeper: bankKeeper, + } +} + +// Name returns the x/tokenfactory module's name. +func (am AppModule) Name() string { + return am.AppModuleBasic.Name() +} + +// QuerierRoute returns the x/tokenfactory module's query routing key. +func (AppModule) QuerierRoute() string { return types.QuerierRoute } + +// RegisterServices registers a GRPC query service to respond to the +// module-specific GRPC queries. +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) +} + +// RegisterInvariants registers the x/tokenfactory module's invariants. +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs the x/tokenfactory module's genesis initialization. It +// returns no validator updates. +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, gs json.RawMessage) []abci.ValidatorUpdate { + var genState types.GenesisState + cdc.MustUnmarshalJSON(gs, &genState) + + am.keeper.InitGenesis(ctx, genState) + + return []abci.ValidatorUpdate{} +} + +// ExportGenesis returns the x/tokenfactory module's exported genesis state as raw +// JSON bytes. +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.RawMessage { + genState := am.keeper.ExportGenesis(ctx) + return cdc.MustMarshalJSON(genState) +} + +// ConsensusVersion implements ConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return 1 } + +// BeginBlock executes all ABCI BeginBlock logic respective to the tokenfactory module. +func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} + +// EndBlock executes all ABCI EndBlock logic respective to the tokenfactory module. It +// returns no validator updates. +func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +// ___________________________________________________________________________ + +// AppModuleSimulationV2 functions + +// // 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))) +// tfDefaultGenJson := simState.Cdc.MustMarshalJSON(tfDefaultGen) +// simState.GenState[types.ModuleName] = tfDefaultGenJson +// } + +// // WeightedOperations returns the all the lockup module operations with their respective weights. +// func (am AppModule) Actions() []simtypes.Action { +// return []simtypes.Action{ +// simtypes.NewMsgBasedAction("create token factory token", am.keeper, simulation.RandomMsgCreateDenom), +// simtypes.NewMsgBasedAction("mint token factory token", am.keeper, simulation.RandomMsgMintDenom), +// simtypes.NewMsgBasedAction("burn token factory token", am.keeper, simulation.RandomMsgBurnDenom), +// simtypes.NewMsgBasedAction("change admin token factory token", am.keeper, simulation.RandomMsgChangeAdmin), +// } +// } + +// ____________________________________________________________________________ + +// AppModuleSimulation functions +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { + simulation.RandomizedGenState(simState) +} + +// GenerateGenesisState creates a randomized GenState of the bank module. +func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { + 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) { +} + +// 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.keeper, am.accountKeeper, am.bankKeeper) +} diff --git a/x/tokenfactory/simulation/genesis.go b/x/tokenfactory/simulation/genesis.go new file mode 100644 index 0000000..f3e091b --- /dev/null +++ b/x/tokenfactory/simulation/genesis.go @@ -0,0 +1,26 @@ +package simulation + +import ( + "math/rand" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + + "github.com/terpnetwork/terp-core/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))) +} + +func RandomizedGenState(simstate *module.SimulationState) { + tfGenesis := types.DefaultGenesis() + + _, err := simstate.Cdc.MarshalJSON(tfGenesis) + if err != nil { + panic(err) + } + + simstate.GenState[types.ModuleName] = simstate.Cdc.MustMarshalJSON(tfGenesis) +} diff --git a/x/tokenfactory/simulation/operations.go b/x/tokenfactory/simulation/operations.go new file mode 100644 index 0000000..46f9a16 --- /dev/null +++ b/x/tokenfactory/simulation/operations.go @@ -0,0 +1,404 @@ +package simulation + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + 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" +) + +// Simulation operation weights constants +// +//nolint:gosec +const ( + OpWeightMsgCreateDenom = "op_weight_msg_create_denom" + OpWeightMsgMint = "op_weight_msg_mint" + OpWeightMsgBurn = "op_weight_msg_burn" + OpWeightMsgChangeAdmin = "op_weight_msg_change_admin" + OpWeightMsgSetDenomMetadata = "op_weight_msg_set_denom_metadata" +) + +type TokenfactoryKeeper interface { + GetParams(ctx sdk.Context) (params types.Params) + GetAuthorityMetadata(ctx sdk.Context, denom string) (types.DenomAuthorityMetadata, error) + GetAllDenomsIterator(ctx sdk.Context) sdk.Iterator + GetDenomsFromCreator(ctx sdk.Context, creator string) []string +} + +type BankKeeper interface { + simulation.BankKeeper + GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin +} + +func WeightedOperations( + simstate *module.SimulationState, + tfKeeper TokenfactoryKeeper, + ak types.AccountKeeper, + bk BankKeeper, +) simulation.WeightedOperations { + var ( + weightMsgCreateDenom int + weightMsgMint int + weightMsgBurn int + weightMsgChangeAdmin int + weightMsgSetDenomMetadata int + ) + + simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgCreateDenom, &weightMsgCreateDenom, nil, + func(_ *rand.Rand) { + weightMsgCreateDenom = appparams.DefaultWeightMsgCreateDenom + }, + ) + simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgMint, &weightMsgMint, nil, + func(_ *rand.Rand) { + weightMsgMint = appparams.DefaultWeightMsgMint + }, + ) + simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgBurn, &weightMsgBurn, nil, + func(_ *rand.Rand) { + weightMsgBurn = appparams.DefaultWeightMsgBurn + }, + ) + simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgChangeAdmin, &weightMsgChangeAdmin, nil, + func(_ *rand.Rand) { + weightMsgChangeAdmin = appparams.DefaultWeightMsgChangeAdmin + }, + ) + simstate.AppParams.GetOrGenerate(simstate.Cdc, OpWeightMsgSetDenomMetadata, &weightMsgSetDenomMetadata, nil, + func(_ *rand.Rand) { + weightMsgSetDenomMetadata = appparams.DefaultWeightMsgSetDenomMetadata + }, + ) + + return simulation.WeightedOperations{ + simulation.NewWeightedOperation( + weightMsgCreateDenom, + SimulateMsgCreateDenom( + tfKeeper, + ak, + bk, + ), + ), + simulation.NewWeightedOperation( + weightMsgMint, + SimulateMsgMint( + tfKeeper, + ak, + bk, + DefaultSimulationDenomSelector, + ), + ), + simulation.NewWeightedOperation( + weightMsgBurn, + SimulateMsgBurn( + tfKeeper, + ak, + bk, + DefaultSimulationDenomSelector, + ), + ), + simulation.NewWeightedOperation( + weightMsgChangeAdmin, + SimulateMsgChangeAdmin( + tfKeeper, + ak, + bk, + DefaultSimulationDenomSelector, + ), + ), + simulation.NewWeightedOperation( + weightMsgSetDenomMetadata, + SimulateMsgSetDenomMetadata( + tfKeeper, + ak, + bk, + DefaultSimulationDenomSelector, + ), + ), + } +} + +type DenomSelector = func(*rand.Rand, sdk.Context, TokenfactoryKeeper, string) (string, bool) + +func DefaultSimulationDenomSelector(r *rand.Rand, ctx sdk.Context, tfKeeper TokenfactoryKeeper, creator string) (string, bool) { + denoms := tfKeeper.GetDenomsFromCreator(ctx, creator) + if len(denoms) == 0 { + return "", false + } + randPos := r.Intn(len(denoms)) + + return denoms[randPos], true +} + +func SimulateMsgSetDenomMetadata( + tfKeeper TokenfactoryKeeper, + ak types.AccountKeeper, + bk BankKeeper, + denomSelector DenomSelector, +) simtypes.Operation { + return func( + r *rand.Rand, + app *baseapp.BaseApp, + ctx sdk.Context, + accs []simtypes.Account, + chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + // Get create denom account + createdDenomAccount, _ := simtypes.RandomAcc(r, accs) + + // Get demon + denom, hasDenom := denomSelector(r, ctx, tfKeeper, createdDenomAccount.Address.String()) + if !hasDenom { + return simtypes.NoOpMsg(types.ModuleName, types.MsgSetDenomMetadata{}.Type(), "sim account have no denom created"), nil, nil + } + + // Get admin of the denom + authData, err := tfKeeper.GetAuthorityMetadata(ctx, denom) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.MsgSetDenomMetadata{}.Type(), "err authority metadata"), nil, err + } + adminAccount, found := simtypes.FindAccount(accs, sdk.MustAccAddressFromBech32(authData.Admin)) + if !found { + return simtypes.NoOpMsg(types.ModuleName, types.MsgSetDenomMetadata{}.Type(), "admin account not found"), nil, nil + } + + metadata := banktypes.Metadata{ + Description: simtypes.RandStringOfLength(r, 10), + DenomUnits: []*banktypes.DenomUnit{{ + Denom: denom, + Exponent: 0, + }}, + Base: denom, + Display: denom, + Name: simtypes.RandStringOfLength(r, 10), + Symbol: simtypes.RandStringOfLength(r, 10), + } + + msg := types.MsgSetDenomMetadata{ + Sender: adminAccount.Address.String(), + Metadata: metadata, + } + + txCtx := BuildOperationInput(r, app, ctx, &msg, adminAccount, ak, bk, nil) + return simulation.GenAndDeliverTxWithRandFees(txCtx) + } +} + +func SimulateMsgChangeAdmin( + tfKeeper TokenfactoryKeeper, + ak types.AccountKeeper, + bk BankKeeper, + denomSelector DenomSelector, +) simtypes.Operation { + return func( + r *rand.Rand, + app *baseapp.BaseApp, + ctx sdk.Context, + accs []simtypes.Account, + chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + // Get create denom account + createdDenomAccount, _ := simtypes.RandomAcc(r, accs) + + // Get demon + denom, hasDenom := denomSelector(r, ctx, tfKeeper, createdDenomAccount.Address.String()) + if !hasDenom { + return simtypes.NoOpMsg(types.ModuleName, types.MsgChangeAdmin{}.Type(), "sim account have no denom created"), nil, nil + } + + // Get admin of the denom + authData, err := tfKeeper.GetAuthorityMetadata(ctx, denom) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.MsgChangeAdmin{}.Type(), "err authority metadata"), nil, err + } + curAdminAccount, found := simtypes.FindAccount(accs, sdk.MustAccAddressFromBech32(authData.Admin)) + if !found { + return simtypes.NoOpMsg(types.ModuleName, types.MsgChangeAdmin{}.Type(), "admin account not found"), nil, nil + } + + // Rand new admin account + newAdmin, _ := simtypes.RandomAcc(r, accs) + if newAdmin.Address.String() == curAdminAccount.Address.String() { + return simtypes.NoOpMsg(types.ModuleName, types.MsgChangeAdmin{}.Type(), "new admin cannot be the same as current admin"), nil, nil + } + + // Create msg + msg := types.MsgChangeAdmin{ + Sender: curAdminAccount.Address.String(), + Denom: denom, + NewAdmin: newAdmin.Address.String(), + } + + txCtx := BuildOperationInput(r, app, ctx, &msg, curAdminAccount, ak, bk, nil) + return simulation.GenAndDeliverTxWithRandFees(txCtx) + } +} + +func SimulateMsgBurn( + tfKeeper TokenfactoryKeeper, + ak types.AccountKeeper, + bk BankKeeper, + denomSelector DenomSelector, +) simtypes.Operation { + return func( + r *rand.Rand, + app *baseapp.BaseApp, + ctx sdk.Context, + accs []simtypes.Account, + chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + // Get create denom account + createdDenomAccount, _ := simtypes.RandomAcc(r, accs) + + // Get demon + denom, hasDenom := denomSelector(r, ctx, tfKeeper, createdDenomAccount.Address.String()) + if !hasDenom { + return simtypes.NoOpMsg(types.ModuleName, types.MsgBurn{}.Type(), "sim account have no denom created"), nil, nil + } + + // Get admin of the denom + authData, err := tfKeeper.GetAuthorityMetadata(ctx, denom) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.MsgBurn{}.Type(), "err authority metadata"), nil, err + } + adminAccount, found := simtypes.FindAccount(accs, sdk.MustAccAddressFromBech32(authData.Admin)) + if !found { + return simtypes.NoOpMsg(types.ModuleName, types.MsgBurn{}.Type(), "admin account not found"), nil, nil + } + + // Check if admin account balance = 0 + accountBalance := bk.GetBalance(ctx, adminAccount.Address, denom) + if accountBalance.Amount.LTE(sdk.ZeroInt()) { + return simtypes.NoOpMsg(types.ModuleName, types.MsgBurn{}.Type(), "sim account have no balance"), nil, nil + } + + // Rand burn amount + amount, _ := simtypes.RandPositiveInt(r, accountBalance.Amount) + burnAmount := sdk.NewCoin(denom, amount) + + // Create msg + msg := types.MsgBurn{ + Sender: adminAccount.Address.String(), + Amount: burnAmount, + } + + txCtx := BuildOperationInput(r, app, ctx, &msg, adminAccount, ak, bk, sdk.NewCoins(burnAmount)) + return simulation.GenAndDeliverTxWithRandFees(txCtx) + } +} + +// Simulate msg mint denom +func SimulateMsgMint( + tfKeeper TokenfactoryKeeper, + ak types.AccountKeeper, + bk BankKeeper, + denomSelector DenomSelector, +) simtypes.Operation { + return func( + r *rand.Rand, + app *baseapp.BaseApp, + ctx sdk.Context, + accs []simtypes.Account, + chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + // Get create denom account + createdDenomAccount, _ := simtypes.RandomAcc(r, accs) + + // Get demon + denom, hasDenom := denomSelector(r, ctx, tfKeeper, createdDenomAccount.Address.String()) + if !hasDenom { + return simtypes.NoOpMsg(types.ModuleName, types.MsgMint{}.Type(), "sim account have no denom created"), nil, nil + } + + // Get admin of the denom + authData, err := tfKeeper.GetAuthorityMetadata(ctx, denom) + if err != nil { + return simtypes.NoOpMsg(types.ModuleName, types.MsgMint{}.Type(), "err authority metadata"), nil, err + } + adminAccount, found := simtypes.FindAccount(accs, sdk.MustAccAddressFromBech32(authData.Admin)) + if !found { + return simtypes.NoOpMsg(types.ModuleName, types.MsgMint{}.Type(), "admin account not found"), nil, nil + } + + // Rand mint amount + mintAmount, _ := simtypes.RandPositiveInt(r, sdk.NewIntFromUint64(100_000_000)) + + // Create msg mint + msg := types.MsgMint{ + Sender: adminAccount.Address.String(), + Amount: sdk.NewCoin(denom, mintAmount), + } + + txCtx := BuildOperationInput(r, app, ctx, &msg, adminAccount, ak, bk, nil) + return simulation.GenAndDeliverTxWithRandFees(txCtx) + } +} + +// Simulate msg create denom +func SimulateMsgCreateDenom(tfKeeper TokenfactoryKeeper, ak types.AccountKeeper, bk BankKeeper) simtypes.Operation { + return func( + r *rand.Rand, + app *baseapp.BaseApp, + ctx sdk.Context, + accs []simtypes.Account, + chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + // Get sims account + simAccount, _ := simtypes.RandomAcc(r, accs) + + // Check if sims account enough create fee + createFee := tfKeeper.GetParams(ctx).DenomCreationFee + balances := bk.GetAllBalances(ctx, simAccount.Address) + _, hasNeg := balances.SafeSub(createFee...) + if hasNeg { + return simtypes.NoOpMsg(types.ModuleName, types.MsgCreateDenom{}.Type(), "Creator not enough creation fee"), nil, nil + } + + // Create msg create denom + msg := types.MsgCreateDenom{ + Sender: simAccount.Address.String(), + Subdenom: simtypes.RandStringOfLength(r, 10), + } + + txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, createFee) + 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 { + return simulation.OperationInput{ + R: r, + App: app, + TxGen: appparams.MakeEncodingConfig().TxConfig, + Cdc: nil, + Msg: msg, + MsgType: msg.Type(), + Context: ctx, + SimAccount: simAccount, + AccountKeeper: ak, + Bankkeeper: bk, + ModuleName: types.ModuleName, + CoinsSpentInMsg: deposit, + } +} diff --git a/x/tokenfactory/simulation/params.go b/x/tokenfactory/simulation/params.go new file mode 100644 index 0000000..886bf06 --- /dev/null +++ b/x/tokenfactory/simulation/params.go @@ -0,0 +1,24 @@ +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/consts.go b/x/tokenfactory/testhelpers/consts.go new file mode 100644 index 0000000..d7804a3 --- /dev/null +++ b/x/tokenfactory/testhelpers/consts.go @@ -0,0 +1,8 @@ +package testhelpers + +import sdk "github.com/cosmos/cosmos-sdk/types" + +var ( + SecondaryDenom = "uion" + SecondaryAmount = sdk.NewInt(100000000) +) diff --git a/x/tokenfactory/testhelpers/suite.go b/x/tokenfactory/testhelpers/suite.go new file mode 100644 index 0000000..b509a52 --- /dev/null +++ b/x/tokenfactory/testhelpers/suite.go @@ -0,0 +1,66 @@ +package testhelpers + +import ( + "encoding/json" + "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" +) + +var ( + Amino = codec.NewLegacyAmino() + AuthzModuleCdc = codec.NewAminoCodec(Amino) +) + +func init() { + cryptocodec.RegisterCrypto(Amino) + codec.RegisterEvidences(Amino) + sdk.RegisterLegacyAminoCodec(Amino) +} + +func TestMessageAuthzSerialization(t *testing.T, msg sdk.Msg) { + someDate := time.Date(1, 1, 1, 1, 1, 1, 1, time.UTC) + const ( + mockGranter string = "cosmos1abc" + mockGrantee string = "cosmos1xyz" + ) + + var ( + mockMsgGrant authz.MsgGrant + mockMsgRevoke authz.MsgRevoke + mockMsgExec authz.MsgExec + ) + + // Authz: Grant Msg + typeURL := sdk.MsgTypeURL(msg) + 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} + msgGrantBytes := json.RawMessage(sdk.MustSortJSON(AuthzModuleCdc.MustMarshalJSON(&msgGrant))) + err = AuthzModuleCdc.UnmarshalJSON(msgGrantBytes, &mockMsgGrant) + require.NoError(t, err) + + // Authz: Revoke Msg + msgRevoke := authz.MsgRevoke{Granter: mockGranter, Grantee: mockGrantee, MsgTypeUrl: typeURL} + msgRevokeByte := json.RawMessage(sdk.MustSortJSON(AuthzModuleCdc.MustMarshalJSON(&msgRevoke))) + err = AuthzModuleCdc.UnmarshalJSON(msgRevokeByte, &mockMsgRevoke) + require.NoError(t, err) + + // Authz: Exec Msg + msgAny, err := cdctypes.NewAnyWithValue(msg) + require.NoError(t, err) + msgExec := authz.MsgExec{Grantee: mockGrantee, Msgs: []*cdctypes.Any{msgAny}} + execMsgByte := json.RawMessage(sdk.MustSortJSON(AuthzModuleCdc.MustMarshalJSON(&msgExec))) + err = AuthzModuleCdc.UnmarshalJSON(execMsgByte, &mockMsgExec) + require.NoError(t, err) + require.Equal(t, msgExec.Msgs[0].Value, mockMsgExec.Msgs[0].Value) +} diff --git a/x/tokenfactory/types/authorityMetadata.go b/x/tokenfactory/types/authorityMetadata.go new file mode 100644 index 0000000..b45bffc --- /dev/null +++ b/x/tokenfactory/types/authorityMetadata.go @@ -0,0 +1,15 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +func (metadata DenomAuthorityMetadata) Validate() error { + if metadata.Admin != "" { + _, err := sdk.AccAddressFromBech32(metadata.Admin) + if err != nil { + return err + } + } + return nil +} diff --git a/x/tokenfactory/types/authorityMetadata.pb.go b/x/tokenfactory/types/authorityMetadata.pb.go new file mode 100644 index 0000000..ec7b7aa --- /dev/null +++ b/x/tokenfactory/types/authorityMetadata.pb.go @@ -0,0 +1,364 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmwasm/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" +) + +// 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 + +// 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. +type DenomAuthorityMetadata struct { + // Can be empty for no admin, or a valid terp address + Admin string `protobuf:"bytes,1,opt,name=admin,proto3" json:"admin,omitempty" yaml:"admin"` +} + +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_52db82570ee68a0a, []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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_DenomAuthorityMetadata proto.InternalMessageInfo + +func (m *DenomAuthorityMetadata) GetAdmin() string { + if m != nil { + return m.Admin + } + return "" +} + +func init() { + proto.RegisterType((*DenomAuthorityMetadata)(nil), "cosmwasm.tokenfactory.v1beta1.DenomAuthorityMetadata") +} + +func init() { + proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/authorityMetadata.proto", fileDescriptor_52db82570ee68a0a) +} + +var fileDescriptor_52db82570ee68a0a = []byte{ + // 238 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4d, 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, 0xf4, 0x4d, 0x2d, 0x49, 0x4c, 0x49, 0x2c, 0x49, 0xd4, 0x2b, 0x28, 0xca, 0x2f, + 0xc9, 0x17, 0x92, 0x85, 0x69, 0xd3, 0x43, 0xd6, 0xa6, 0x07, 0xd5, 0x26, 0x25, 0x92, 0x9e, 0x9f, + 0x9e, 0x0f, 0x56, 0xa9, 0x0f, 0x62, 0x41, 0x34, 0x49, 0xc9, 0x81, 0x34, 0xe5, 0x17, 0xeb, 0x27, + 0x25, 0x16, 0xa7, 0xc2, 0x6d, 0x48, 0xce, 0xcf, 0xcc, 0x83, 0xc8, 0x2b, 0xb9, 0x71, 0x89, 0xb9, + 0xa4, 0xe6, 0xe5, 0xe7, 0x3a, 0xa2, 0x5b, 0x2a, 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, + 0xc7, 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, 0xe9, 0xa5, 0x67, 0x96, 0x64, + 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x3b, 0xe7, 0x17, 0xe7, 0x86, 0x83, 0x3c, 0x0e, 0xf2, + 0x46, 0x8a, 0x7e, 0x05, 0x6a, 0x00, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x1d, 0x66, + 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x5e, 0xaf, 0x20, 0x19, 0x26, 0x01, 0x00, 0x00, +} + +func (this *DenomAuthorityMetadata) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*DenomAuthorityMetadata) + if !ok { + that2, ok := that.(DenomAuthorityMetadata) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Admin != that1.Admin { + return false + } + return true +} + +func (m *DenomAuthorityMetadata) 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 *DenomAuthorityMetadata) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *DenomAuthorityMetadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Admin) > 0 { + i -= len(m.Admin) + copy(dAtA[i:], m.Admin) + i = encodeVarintAuthorityMetadata(dAtA, i, uint64(len(m.Admin))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintAuthorityMetadata(dAtA []byte, offset int, v uint64) int { + offset -= sovAuthorityMetadata(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} + +func (m *DenomAuthorityMetadata) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Admin) + if l > 0 { + n += 1 + l + sovAuthorityMetadata(uint64(l)) + } + return n +} + +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 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowAuthorityMetadata + } + 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: DenomAuthorityMetadata: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: DenomAuthorityMetadata: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + 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 ErrIntOverflowAuthorityMetadata + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthAuthorityMetadata + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthAuthorityMetadata + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Admin = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipAuthorityMetadata(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthAuthorityMetadata + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func skipAuthorityMetadata(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, ErrIntOverflowAuthorityMetadata + } + 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, ErrIntOverflowAuthorityMetadata + } + 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, ErrIntOverflowAuthorityMetadata + } + 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, ErrInvalidLengthAuthorityMetadata + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupAuthorityMetadata + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthAuthorityMetadata + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthAuthorityMetadata = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowAuthorityMetadata = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupAuthorityMetadata = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/tokenfactory/types/authzcodec/codec.go b/x/tokenfactory/types/authzcodec/codec.go new file mode 100644 index 0000000..366e337 --- /dev/null +++ b/x/tokenfactory/types/authzcodec/codec.go @@ -0,0 +1,24 @@ +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/codec.go b/x/tokenfactory/types/codec.go new file mode 100644 index 0000000..b086a51 --- /dev/null +++ b/x/tokenfactory/types/codec.go @@ -0,0 +1,46 @@ +package types + +import ( + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" + + // this line is used by starport scaffolding # 1 + "github.com/cosmos/cosmos-sdk/types/msgservice" +) + +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) +} + +func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + registry.RegisterImplementations( + (*sdk.Msg)(nil), + &MsgCreateDenom{}, + &MsgMint{}, + &MsgBurn{}, + // &MsgForceTransfer{}, + &MsgChangeAdmin{}, + ) + 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() +} diff --git a/x/tokenfactory/types/denoms.go b/x/tokenfactory/types/denoms.go new file mode 100644 index 0000000..6583998 --- /dev/null +++ b/x/tokenfactory/types/denoms.go @@ -0,0 +1,68 @@ +package types + +import ( + "strings" + + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + ModuleDenomPrefix = "factory" + // See the TokenFactory readme for a derivation of these. + // TL;DR, MaxSubdenomLength + MaxHrpLength = 60 comes from SDK max denom length = 128 + // and the structure of tokenfactory denoms. + MaxSubdenomLength = 44 + MaxHrpLength = 16 + // MaxCreatorLength = 59 + MaxHrpLength + MaxCreatorLength = 59 + MaxHrpLength +) + +// GetTokenDenom constructs a denom string for tokens created by tokenfactory +// based on an input creator address and a subdenom +// The denom constructed is factory/{creator}/{subdenom} +func GetTokenDenom(creator, subdenom string) (string, error) { + if len(subdenom) > MaxSubdenomLength { + return "", ErrSubdenomTooLong + } + if len(creator) > MaxCreatorLength { + return "", ErrCreatorTooLong + } + if strings.Contains(creator, "/") { + return "", ErrInvalidCreator + } + denom := strings.Join([]string{ModuleDenomPrefix, creator, subdenom}, "/") + return denom, sdk.ValidateDenom(denom) +} + +// DeconstructDenom takes a token denom string and verifies that it is a valid +// denom of the tokenfactory module, and is of the form `factory/{creator}/{subdenom}` +// If valid, it returns the creator address and subdenom +func DeconstructDenom(denom string) (creator string, subdenom string, err error) { + err = sdk.ValidateDenom(denom) + if err != nil { + return "", "", err + } + + strParts := strings.Split(denom, "/") + if len(strParts) < 3 { + return "", "", errorsmod.Wrapf(ErrInvalidDenom, "not enough parts of denom %s", denom) + } + + if strParts[0] != ModuleDenomPrefix { + return "", "", errorsmod.Wrapf(ErrInvalidDenom, "denom prefix is incorrect. Is: %s. Should be: %s", strParts[0], ModuleDenomPrefix) + } + + creator = strParts[1] + creatorAddr, err := sdk.AccAddressFromBech32(creator) + if err != nil { + return "", "", errorsmod.Wrapf(ErrInvalidDenom, "Invalid creator address (%s)", err) + } + + // Handle the case where a denom has a slash in its subdenom. For example, + // when we did the split, we'd turn factory/accaddr/atomderivative/sikka into ["factory", "accaddr", "atomderivative", "sikka"] + // So we have to join [2:] with a "/" as the delimiter to get back the correct subdenom which should be "atomderivative/sikka" + subdenom = strings.Join(strParts[2:], "/") + + return creatorAddr.String(), subdenom, nil +} diff --git a/x/tokenfactory/types/denoms_test.go b/x/tokenfactory/types/denoms_test.go new file mode 100644 index 0000000..12f4637 --- /dev/null +++ b/x/tokenfactory/types/denoms_test.go @@ -0,0 +1,132 @@ +package types_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/terpnetwork/terp-core/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), + // which is good, but not required for these tests as they make code less reuable + // appparams.SetAddressPrefixes() + + for _, tc := range []struct { + desc string + denom string + expectedSubdenom string + err error + }{ + { + desc: "empty is invalid", + denom: "", + err: types.ErrInvalidDenom, + }, + { + desc: "normal", + denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + expectedSubdenom: "bitcoin", + }, + { + desc: "multiple slashes in subdenom", + denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin/1", + expectedSubdenom: "bitcoin/1", + }, + { + desc: "no subdenom", + denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/", + expectedSubdenom: "", + }, + { + desc: "incorrect prefix", + denom: "ibc/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + err: types.ErrInvalidDenom, + }, + { + desc: "subdenom of only slashes", + denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/////", + expectedSubdenom: "////", + }, + { + desc: "too long name", + denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/adsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsf", + err: types.ErrInvalidDenom, + }, + } { + t.Run(tc.desc, func(t *testing.T) { + expectedCreator := "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8" + creator, subdenom, err := types.DeconstructDenom(tc.denom) + if tc.err != nil { + require.ErrorContains(t, err, tc.err.Error()) + } else { + require.NoError(t, err) + require.Equal(t, expectedCreator, creator) + require.Equal(t, tc.expectedSubdenom, subdenom) + } + }) + } +} + +func TestGetTokenDenom(t *testing.T) { + // appparams.SetAddressPrefixes() + for _, tc := range []struct { + desc string + creator string + subdenom string + valid bool + }{ + { + desc: "normal", + creator: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + subdenom: "bitcoin", + valid: true, + }, + { + desc: "multiple slashes in subdenom", + creator: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + subdenom: "bitcoin/1", + valid: true, + }, + { + desc: "no subdenom", + creator: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + subdenom: "", + valid: true, + }, + { + desc: "subdenom of only slashes", + creator: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + subdenom: "/////", + valid: true, + }, + { + desc: "too long name", + creator: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + subdenom: "adsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsfadsf", + valid: false, + }, + { + desc: "subdenom is exactly max length", + creator: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + subdenom: "bitcoinfsadfsdfeadfsafwefsefsefsdfsdafasefsf", + valid: true, + }, + { + desc: "creator is exactly max length", + creator: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8jhgjhgkhjklhkjhkjhgjhgjgjghelu", + subdenom: "bitcoin", + valid: true, + }, + } { + t.Run(tc.desc, func(t *testing.T) { + _, err := types.GetTokenDenom(tc.creator, tc.subdenom) + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} diff --git a/x/tokenfactory/types/errors.go b/x/tokenfactory/types/errors.go new file mode 100644 index 0000000..7742014 --- /dev/null +++ b/x/tokenfactory/types/errors.go @@ -0,0 +1,22 @@ +package types + +// DONTCOVER + +import ( + fmt "fmt" + + errorsmod "cosmossdk.io/errors" +) + +// x/tokenfactory module sentinel errors +var ( + ErrDenomExists = errorsmod.Register(ModuleName, 2, "attempting to create a denom that already exists (has bank metadata)") + ErrUnauthorized = errorsmod.Register(ModuleName, 3, "unauthorized account") + ErrInvalidDenom = errorsmod.Register(ModuleName, 4, "invalid denom") + ErrInvalidCreator = errorsmod.Register(ModuleName, 5, "invalid creator") + ErrInvalidAuthorityMetadata = errorsmod.Register(ModuleName, 6, "invalid authority metadata") + ErrInvalidGenesis = errorsmod.Register(ModuleName, 7, "invalid genesis") + 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") +) diff --git a/x/tokenfactory/types/events.go b/x/tokenfactory/types/events.go new file mode 100644 index 0000000..48038e0 --- /dev/null +++ b/x/tokenfactory/types/events.go @@ -0,0 +1,18 @@ +package types + +// event types +// +//nolint:gosec // these are not hard-coded credentials +const ( + AttributeAmount = "amount" + AttributeCreator = "creator" + AttributeSubdenom = "subdenom" + AttributeNewTokenDenom = "new_token_denom" + AttributeMintToAddress = "mint_to_address" + AttributeBurnFromAddress = "burn_from_address" + AttributeTransferFromAddress = "transfer_from_address" + AttributeTransferToAddress = "transfer_to_address" + AttributeDenom = "denom" + AttributeNewAdmin = "new_admin" + AttributeDenomMetadata = "denom_metadata" +) diff --git a/x/tokenfactory/types/expected_keepers.go b/x/tokenfactory/types/expected_keepers.go new file mode 100644 index 0000000..15f377e --- /dev/null +++ b/x/tokenfactory/types/expected_keepers.go @@ -0,0 +1,36 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +type BankKeeper interface { + // Methods imported from bank should be defined here + GetDenomMetaData(ctx sdk.Context, denom string) (banktypes.Metadata, bool) + SetDenomMetaData(ctx sdk.Context, denomMetaData banktypes.Metadata) + + HasSupply(ctx sdk.Context, denom string) 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 + MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + + SendCoins(ctx sdk.Context, fromAddr sdk.AccAddress, toAddr sdk.AccAddress, amt sdk.Coins) error + HasBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coin) bool + 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 +} + +type AccountKeeper interface { + SetModuleAccount(ctx sdk.Context, macc authtypes.ModuleAccountI) + GetAccount(ctx sdk.Context, addr sdk.AccAddress) authtypes.AccountI +} + +// CommunityPoolKeeper defines the contract needed to be fulfilled for community pool interactions. +type CommunityPoolKeeper interface { + FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error +} diff --git a/x/tokenfactory/types/genesis.go b/x/tokenfactory/types/genesis.go new file mode 100644 index 0000000..aef9370 --- /dev/null +++ b/x/tokenfactory/types/genesis.go @@ -0,0 +1,51 @@ +package types + +import ( + errorsmod "cosmossdk.io/errors" + sdk "github.com/cosmos/cosmos-sdk/types" +) + +// this line is used by starport scaffolding # genesis/types/import + +// DefaultIndex is the default capability global index +const DefaultIndex uint64 = 1 + +// DefaultGenesis returns the default Capability genesis state +func DefaultGenesis() *GenesisState { + return &GenesisState{ + Params: DefaultParams(), + FactoryDenoms: []GenesisDenom{}, + } +} + +// Validate performs basic genesis state validation returning an error upon any +// failure. +func (gs GenesisState) Validate() error { + err := gs.Params.Validate() + if err != nil { + return err + } + + seenDenoms := map[string]bool{} + + for _, denom := range gs.GetFactoryDenoms() { + if seenDenoms[denom.GetDenom()] { + return errorsmod.Wrapf(ErrInvalidGenesis, "duplicate denom: %s", denom.GetDenom()) + } + seenDenoms[denom.GetDenom()] = true + + _, _, err := DeconstructDenom(denom.GetDenom()) + if err != nil { + return err + } + + if denom.AuthorityMetadata.Admin != "" { + _, err = sdk.AccAddressFromBech32(denom.AuthorityMetadata.Admin) + if err != nil { + return errorsmod.Wrapf(ErrInvalidAuthorityMetadata, "Invalid admin address (%s)", err) + } + } + } + + return nil +} diff --git a/x/tokenfactory/types/genesis.pb.go b/x/tokenfactory/types/genesis.pb.go new file mode 100644 index 0000000..d26fa84 --- /dev/null +++ b/x/tokenfactory/types/genesis.pb.go @@ -0,0 +1,668 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmwasm/tokenfactory/v1beta1/genesis.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 + +// GenesisState defines the tokenfactory module's genesis state. +type GenesisState struct { + // params defines the paramaters of the module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + FactoryDenoms []GenesisDenom `protobuf:"bytes,2,rep,name=factory_denoms,json=factoryDenoms,proto3" json:"factory_denoms" yaml:"factory_denoms"` +} + +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} +} + +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) GetFactoryDenoms() []GenesisDenom { + if m != nil { + return m.FactoryDenoms + } + return nil +} + +// GenesisDenom defines a tokenfactory denom that is defined within genesis +// state. The structure contains DenomAuthorityMetadata which defines the +// denom's admin. +type GenesisDenom struct { + Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty" yaml:"denom"` + AuthorityMetadata DenomAuthorityMetadata `protobuf:"bytes,2,opt,name=authority_metadata,json=authorityMetadata,proto3" json:"authority_metadata" yaml:"authority_metadata"` +} + +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_GenesisDenom proto.InternalMessageInfo + +func (m *GenesisDenom) GetDenom() string { + if m != nil { + return m.Denom + } + return "" +} + +func (m *GenesisDenom) GetAuthorityMetadata() DenomAuthorityMetadata { + if m != nil { + return m.AuthorityMetadata + } + return DenomAuthorityMetadata{} +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "cosmwasm.tokenfactory.v1beta1.GenesisState") + proto.RegisterType((*GenesisDenom)(nil), "cosmwasm.tokenfactory.v1beta1.GenesisDenom") +} + +func init() { + proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/genesis.proto", fileDescriptor_b333539769138b3e) +} + +var fileDescriptor_b333539769138b3e = []byte{ + // 363 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, 0x85, 0x29, 0xd6, 0x43, 0x56, 0xac, 0x07, + 0x55, 0x2c, 0x25, 0x92, 0x9e, 0x9f, 0x9e, 0x0f, 0x56, 0xa9, 0x0f, 0x62, 0x41, 0x34, 0x49, 0x99, + 0xe2, 0xb7, 0x21, 0xb1, 0xb4, 0x24, 0x23, 0xbf, 0x28, 0xb3, 0xa4, 0xd2, 0x37, 0xb5, 0x24, 0x31, + 0x25, 0xb1, 0x24, 0x11, 0xaa, 0x4d, 0x0b, 0xbf, 0xb6, 0x82, 0xc4, 0xa2, 0xc4, 0x5c, 0xa8, 0xbb, + 0x94, 0x8e, 0x31, 0x72, 0xf1, 0xb8, 0x43, 0x5c, 0x1a, 0x5c, 0x92, 0x58, 0x92, 0x2a, 0xe4, 0xcc, + 0xc5, 0x06, 0x51, 0x20, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x6d, 0xa4, 0xaa, 0x87, 0xd7, 0xe5, 0x7a, + 0x01, 0x60, 0xc5, 0x4e, 0x2c, 0x27, 0xee, 0xc9, 0x33, 0x04, 0x41, 0xb5, 0x0a, 0x15, 0x72, 0xf1, + 0x41, 0xd5, 0xc5, 0xa7, 0xa4, 0xe6, 0xe5, 0xe7, 0x16, 0x4b, 0x30, 0x29, 0x30, 0x6b, 0x70, 0x1b, + 0x69, 0x13, 0x30, 0x0c, 0xea, 0x12, 0x17, 0x90, 0x1e, 0x27, 0x59, 0x90, 0x91, 0x9f, 0xee, 0xc9, + 0x8b, 0x56, 0x26, 0xe6, 0xe6, 0x58, 0x29, 0xa1, 0x1a, 0xa8, 0x14, 0xc4, 0x0b, 0x15, 0x70, 0x81, + 0xf0, 0x91, 0x3c, 0x02, 0x16, 0x11, 0x52, 0xe3, 0x62, 0x05, 0x2b, 0x05, 0xfb, 0x83, 0xd3, 0x49, + 0xe0, 0xd3, 0x3d, 0x79, 0x1e, 0x88, 0x49, 0x60, 0x61, 0xa5, 0x20, 0x88, 0xb4, 0x50, 0x3b, 0x23, + 0x97, 0x10, 0x3c, 0x24, 0xe3, 0x73, 0xa1, 0x41, 0x29, 0xc1, 0x04, 0xf6, 0xbd, 0x29, 0x01, 0x07, + 0x83, 0xad, 0x72, 0x44, 0x8f, 0x07, 0x27, 0x45, 0xa8, 0xd3, 0x25, 0x21, 0x16, 0x62, 0x1a, 0xaf, + 0x14, 0x24, 0x88, 0x11, 0x7b, 0x56, 0x2c, 0x2f, 0x16, 0xc8, 0x33, 0x3a, 0x79, 0x9c, 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, 0x5e, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, + 0x72, 0x7e, 0xae, 0xbe, 0x73, 0x7e, 0x71, 0x6e, 0x38, 0x28, 0x8a, 0x41, 0x6e, 0x4b, 0xd1, 0xaf, + 0x40, 0x8d, 0xea, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, 0x70, 0x14, 0x1b, 0x03, 0x02, 0x00, + 0x00, 0xff, 0xff, 0x38, 0xec, 0xbf, 0xde, 0xa9, 0x02, 0x00, 0x00, +} + +func (this *GenesisDenom) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*GenesisDenom) + if !ok { + that2, ok := that.(GenesisDenom) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Denom != that1.Denom { + return false + } + if !this.AuthorityMetadata.Equal(&that1.AuthorityMetadata) { + return false + } + return true +} + +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.FactoryDenoms) > 0 { + for iNdEx := len(m.FactoryDenoms) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.FactoryDenoms[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 *GenesisDenom) 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 *GenesisDenom) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisDenom) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.AuthorityMetadata.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.Denom) > 0 { + i -= len(m.Denom) + copy(dAtA[i:], m.Denom) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.Denom))) + 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.FactoryDenoms) > 0 { + for _, e := range m.FactoryDenoms { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func (m *GenesisDenom) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Denom) + if l > 0 { + n += 1 + l + sovGenesis(uint64(l)) + } + l = m.AuthorityMetadata.Size() + n += 1 + l + sovGenesis(uint64(l)) + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} + +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} + +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FactoryDenoms", 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.FactoryDenoms = append(m.FactoryDenoms, GenesisDenom{}) + if err := m.FactoryDenoms[len(m.FactoryDenoms)-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 *GenesisDenom) 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: GenesisDenom: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisDenom: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 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.Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AuthorityMetadata", 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.AuthorityMetadata.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/tokenfactory/types/genesis_test.go b/x/tokenfactory/types/genesis_test.go new file mode 100644 index 0000000..c93adb4 --- /dev/null +++ b/x/tokenfactory/types/genesis_test.go @@ -0,0 +1,139 @@ +package types_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/terpnetwork/terp-core/x/tokenfactory/types" +) + +func TestGenesisState_Validate(t *testing.T) { + for _, tc := range []struct { + desc string + genState *types.GenesisState + valid bool + }{ + { + desc: "default is valid", + genState: types.DefaultGenesis(), + valid: true, + }, + { + desc: "valid genesis state", + genState: &types.GenesisState{ + FactoryDenoms: []types.GenesisDenom{ + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8", + }, + }, + }, + }, + valid: true, + }, + { + desc: "different admin from creator", + genState: &types.GenesisState{ + FactoryDenoms: []types.GenesisDenom{ + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "cosmos1ft6e5esdtdegnvcr3djd3ftk4kwpcr6jta8eyh", + }, + }, + }, + }, + valid: true, + }, + { + desc: "empty admin", + genState: &types.GenesisState{ + FactoryDenoms: []types.GenesisDenom{ + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "", + }, + }, + }, + }, + valid: true, + }, + { + desc: "no admin", + genState: &types.GenesisState{ + FactoryDenoms: []types.GenesisDenom{ + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + }, + }, + }, + valid: true, + }, + { + desc: "invalid admin", + genState: &types.GenesisState{ + FactoryDenoms: []types.GenesisDenom{ + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "moose", + }, + }, + }, + }, + valid: false, + }, + { + desc: "multiple denoms", + genState: &types.GenesisState{ + FactoryDenoms: []types.GenesisDenom{ + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "", + }, + }, + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/litecoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "", + }, + }, + }, + }, + valid: true, + }, + { + desc: "duplicate denoms", + genState: &types.GenesisState{ + FactoryDenoms: []types.GenesisDenom{ + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "", + }, + }, + { + Denom: "factory/cosmos1t7egva48prqmzl59x5ngv4zx0dtrwewcdqdjr8/bitcoin", + AuthorityMetadata: types.DenomAuthorityMetadata{ + Admin: "", + }, + }, + }, + }, + valid: false, + }, + } { + t.Run(tc.desc, func(t *testing.T) { + err := tc.genState.Validate() + if tc.valid { + require.NoError(t, err) + } else { + require.Error(t, err) + } + }) + } +} diff --git a/x/tokenfactory/types/keys.go b/x/tokenfactory/types/keys.go new file mode 100644 index 0000000..fac4a6e --- /dev/null +++ b/x/tokenfactory/types/keys.go @@ -0,0 +1,49 @@ +package types + +import ( + "strings" +) + +const ( + // ModuleName defines the module name + ModuleName = "tokenfactory" + + // StoreKey defines the primary module store key + StoreKey = ModuleName + + // RouterKey is the message route for slashing + RouterKey = ModuleName + + // QuerierRoute defines the module's query routing key + QuerierRoute = ModuleName + + // MemStoreKey defines the in-memory store key + MemStoreKey = "mem_tokenfactory" +) + +// KeySeparator is used to combine parts of the keys in the store +const KeySeparator = "|" + +var ( + DenomAuthorityMetadataKey = "authoritymetadata" + DenomsPrefixKey = "denoms" + CreatorPrefixKey = "creator" + AdminPrefixKey = "admin" +) + +// GetDenomPrefixStore returns the store prefix where all the data associated with a specific denom +// is stored +func GetDenomPrefixStore(denom string) []byte { + return []byte(strings.Join([]string{DenomsPrefixKey, denom, ""}, KeySeparator)) +} + +// GetCreatorsPrefix returns the store prefix where the list of the denoms created by a specific +// creator are stored +func GetCreatorPrefix(creator string) []byte { + return []byte(strings.Join([]string{CreatorPrefixKey, creator, ""}, KeySeparator)) +} + +// GetCreatorsPrefix returns the store prefix where a list of all creator addresses are stored +func GetCreatorsPrefix() []byte { + return []byte(strings.Join([]string{CreatorPrefixKey, ""}, KeySeparator)) +} diff --git a/x/tokenfactory/types/msgs.go b/x/tokenfactory/types/msgs.go new file mode 100644 index 0000000..e9fb237 --- /dev/null +++ b/x/tokenfactory/types/msgs.go @@ -0,0 +1,247 @@ +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" +) + +// constants +const ( + TypeMsgCreateDenom = "create_denom" + TypeMsgMint = "tf_mint" + TypeMsgBurn = "tf_burn" + TypeMsgForceTransfer = "force_transfer" + TypeMsgChangeAdmin = "change_admin" + TypeMsgSetDenomMetadata = "set_denom_metadata" +) + +var _ sdk.Msg = &MsgCreateDenom{} + +// NewMsgCreateDenom creates a msg to create a new denom +func NewMsgCreateDenom(sender, subdenom string) *MsgCreateDenom { + return &MsgCreateDenom{ + Sender: sender, + Subdenom: subdenom, + } +} + +func (m MsgCreateDenom) Route() string { return RouterKey } +func (m MsgCreateDenom) Type() string { return TypeMsgCreateDenom } +func (m MsgCreateDenom) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Sender) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) + } + + _, err = GetTokenDenom(m.Sender, m.Subdenom) + if err != nil { + return errorsmod.Wrap(ErrInvalidDenom, err.Error()) + } + + return nil +} + +func (m MsgCreateDenom) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +func (m MsgCreateDenom) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) + return []sdk.AccAddress{sender} +} + +var _ sdk.Msg = &MsgMint{} + +// NewMsgMint creates a message to mint tokens +func NewMsgMint(sender string, amount sdk.Coin) *MsgMint { + return &MsgMint{ + Sender: sender, + Amount: amount, + } +} + +func (m MsgMint) Route() string { return RouterKey } +func (m MsgMint) Type() string { return TypeMsgMint } +func (m MsgMint) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Sender) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) + } + + if !m.Amount.IsValid() || m.Amount.Amount.Equal(sdk.ZeroInt()) { + return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, m.Amount.String()) + } + + return nil +} + +func (m MsgMint) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +func (m MsgMint) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) + return []sdk.AccAddress{sender} +} + +var _ sdk.Msg = &MsgBurn{} + +// NewMsgBurn creates a message to burn tokens +func NewMsgBurn(sender string, amount sdk.Coin) *MsgBurn { + return &MsgBurn{ + Sender: sender, + Amount: amount, + } +} + +func (m MsgBurn) Route() string { return RouterKey } +func (m MsgBurn) Type() string { return TypeMsgBurn } +func (m MsgBurn) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Sender) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) + } + + if !m.Amount.IsValid() || m.Amount.Amount.Equal(sdk.ZeroInt()) { + return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, m.Amount.String()) + } + + return nil +} + +func (m MsgBurn) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +func (m MsgBurn) 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 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 = &MsgChangeAdmin{} + +// NewMsgChangeAdmin creates a message to burn tokens +func NewMsgChangeAdmin(sender, denom, newAdmin string) *MsgChangeAdmin { + return &MsgChangeAdmin{ + Sender: sender, + Denom: denom, + NewAdmin: newAdmin, + } +} + +func (m MsgChangeAdmin) Route() string { return RouterKey } +func (m MsgChangeAdmin) Type() string { return TypeMsgChangeAdmin } +func (m MsgChangeAdmin) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Sender) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) + } + + _, err = sdk.AccAddressFromBech32(m.NewAdmin) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid address (%s)", err) + } + + _, _, err = DeconstructDenom(m.Denom) + if err != nil { + return err + } + + return nil +} + +func (m MsgChangeAdmin) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +func (m MsgChangeAdmin) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) + return []sdk.AccAddress{sender} +} + +var _ sdk.Msg = &MsgSetDenomMetadata{} + +// NewMsgChangeAdmin creates a message to burn tokens +func NewMsgSetDenomMetadata(sender string, metadata banktypes.Metadata) *MsgSetDenomMetadata { + return &MsgSetDenomMetadata{ + Sender: sender, + Metadata: metadata, + } +} + +func (m MsgSetDenomMetadata) Route() string { return RouterKey } +func (m MsgSetDenomMetadata) Type() string { return TypeMsgSetDenomMetadata } +func (m MsgSetDenomMetadata) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(m.Sender) + if err != nil { + return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "Invalid sender address (%s)", err) + } + + err = m.Metadata.Validate() + if err != nil { + return err + } + + _, _, err = DeconstructDenom(m.Metadata.Base) + if err != nil { + return err + } + + return nil +} + +func (m MsgSetDenomMetadata) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +func (m MsgSetDenomMetadata) GetSigners() []sdk.AccAddress { + sender, _ := sdk.AccAddressFromBech32(m.Sender) + return []sdk.AccAddress{sender} +} diff --git a/x/tokenfactory/types/msgs_test.go b/x/tokenfactory/types/msgs_test.go new file mode 100644 index 0000000..2b71ce1 --- /dev/null +++ b/x/tokenfactory/types/msgs_test.go @@ -0,0 +1,451 @@ +package types_test + +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" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" +) + +// // 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() + addr1 := sdk.AccAddress(pk1.Address()).String() + coin := sdk.NewCoin("denom", sdk.NewInt(1)) + + testCases := []struct { + name string + msg sdk.Msg + }{ + { + name: "MsgCreateDenom", + msg: &types.MsgCreateDenom{ + Sender: addr1, + Subdenom: "valoper1xyz", + }, + }, + { + name: "MsgBurn", + msg: &types.MsgBurn{ + Sender: addr1, + Amount: coin, + }, + }, + { + name: "MsgMint", + msg: &types.MsgMint{ + Sender: addr1, + Amount: coin, + }, + }, + { + name: "MsgChangeAdmin", + msg: &types.MsgChangeAdmin{ + Sender: addr1, + Denom: "denom", + NewAdmin: "osmo1q8tq5qhrhw6t970egemuuwywhlhpnmdmts6xnu", + }, + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + testhelpers.TestMessageAuthzSerialization(t, tc.msg) + }) + } +} + +// TestMsgCreateDenom tests if valid/invalid create denom messages are properly validated/invalidated +func TestMsgCreateDenom(t *testing.T) { + // generate a private/public key pair and get the respective address + pk1 := ed25519.GenPrivKey().PubKey() + addr1 := sdk.AccAddress(pk1.Address()) + + // make a proper createDenom message + createMsg := func(after func(msg types.MsgCreateDenom) types.MsgCreateDenom) types.MsgCreateDenom { + properMsg := *types.NewMsgCreateDenom( + addr1.String(), + "bitcoin", + ) + + return after(properMsg) + } + + // validate createDenom message was created as intended + msg := createMsg(func(msg types.MsgCreateDenom) types.MsgCreateDenom { + return msg + }) + require.Equal(t, msg.Route(), types.RouterKey) + require.Equal(t, msg.Type(), "create_denom") + signers := msg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1.String()) + + tests := []struct { + name string + msg types.MsgCreateDenom + expectPass bool + }{ + { + name: "proper msg", + msg: createMsg(func(msg types.MsgCreateDenom) types.MsgCreateDenom { + return msg + }), + expectPass: true, + }, + { + name: "empty sender", + msg: createMsg(func(msg types.MsgCreateDenom) types.MsgCreateDenom { + msg.Sender = "" + return msg + }), + expectPass: false, + }, + { + name: "invalid subdenom", + msg: createMsg(func(msg types.MsgCreateDenom) types.MsgCreateDenom { + msg.Subdenom = "thissubdenomismuchtoolongasdkfjaasdfdsafsdlkfnmlksadmflksmdlfmlsakmfdsafasdfasdf" + return msg + }), + expectPass: false, + }, + } + + for _, test := range tests { + if test.expectPass { + require.NoError(t, test.msg.ValidateBasic(), "test: %v", test.name) + } else { + require.Error(t, test.msg.ValidateBasic(), "test: %v", test.name) + } + } +} + +// TestMsgMint tests if valid/invalid create denom messages are properly validated/invalidated +func TestMsgMint(t *testing.T) { + // generate a private/public key pair and get the respective address + pk1 := ed25519.GenPrivKey().PubKey() + addr1 := sdk.AccAddress(pk1.Address()) + + // make a proper mint message + createMsg := func(after func(msg types.MsgMint) types.MsgMint) types.MsgMint { + properMsg := *types.NewMsgMint( + addr1.String(), + sdk.NewCoin("bitcoin", sdk.NewInt(500000000)), + ) + + return after(properMsg) + } + + // validate mint message was created as intended + msg := createMsg(func(msg types.MsgMint) types.MsgMint { + return msg + }) + require.Equal(t, msg.Route(), types.RouterKey) + require.Equal(t, msg.Type(), "tf_mint") + signers := msg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1.String()) + + tests := []struct { + name string + msg types.MsgMint + expectPass bool + }{ + { + name: "proper msg", + msg: createMsg(func(msg types.MsgMint) types.MsgMint { + return msg + }), + expectPass: true, + }, + { + name: "empty sender", + msg: createMsg(func(msg types.MsgMint) types.MsgMint { + msg.Sender = "" + return msg + }), + expectPass: false, + }, + { + name: "zero amount", + msg: createMsg(func(msg types.MsgMint) types.MsgMint { + msg.Amount = sdk.NewCoin("bitcoin", sdk.ZeroInt()) + return msg + }), + expectPass: false, + }, + { + name: "negative amount", + msg: createMsg(func(msg types.MsgMint) types.MsgMint { + msg.Amount.Amount = sdk.NewInt(-10000000) + return msg + }), + expectPass: false, + }, + } + + for _, test := range tests { + if test.expectPass { + require.NoError(t, test.msg.ValidateBasic(), "test: %v", test.name) + } else { + require.Error(t, test.msg.ValidateBasic(), "test: %v", test.name) + } + } +} + +// TestMsgBurn tests if valid/invalid create denom messages are properly validated/invalidated +func TestMsgBurn(t *testing.T) { + // generate a private/public key pair and get the respective address + pk1 := ed25519.GenPrivKey().PubKey() + addr1 := sdk.AccAddress(pk1.Address()) + + // make a proper burn message + baseMsg := types.NewMsgBurn( + addr1.String(), + sdk.NewCoin("bitcoin", sdk.NewInt(500000000)), + ) + + // validate burn message was created as intended + require.Equal(t, baseMsg.Route(), types.RouterKey) + require.Equal(t, baseMsg.Type(), "tf_burn") + signers := baseMsg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1.String()) + + tests := []struct { + name string + msg func() *types.MsgBurn + expectPass bool + }{ + { + name: "proper msg", + msg: func() *types.MsgBurn { + msg := baseMsg + return msg + }, + expectPass: true, + }, + { + name: "empty sender", + msg: func() *types.MsgBurn { + msg := baseMsg + msg.Sender = "" + return msg + }, + expectPass: false, + }, + { + name: "zero amount", + msg: func() *types.MsgBurn { + msg := baseMsg + msg.Amount.Amount = sdk.ZeroInt() + return msg + }, + expectPass: false, + }, + { + name: "negative amount", + msg: func() *types.MsgBurn { + msg := baseMsg + msg.Amount.Amount = sdk.NewInt(-10000000) + return msg + }, + expectPass: false, + }, + } + + for _, test := range tests { + if test.expectPass { + require.NoError(t, test.msg().ValidateBasic(), "test: %v", test.name) + } else { + require.Error(t, test.msg().ValidateBasic(), "test: %v", test.name) + } + } +} + +// TestMsgChangeAdmin tests if valid/invalid create denom messages are properly validated/invalidated +func TestMsgChangeAdmin(t *testing.T) { + // generate a private/public key pair and get the respective address + pk1 := ed25519.GenPrivKey().PubKey() + addr1 := sdk.AccAddress(pk1.Address()) + pk2 := ed25519.GenPrivKey().PubKey() + addr2 := sdk.AccAddress(pk2.Address()) + tokenFactoryDenom := fmt.Sprintf("factory/%s/bitcoin", addr1.String()) + + // make a proper changeAdmin message + baseMsg := types.NewMsgChangeAdmin( + addr1.String(), + tokenFactoryDenom, + addr2.String(), + ) + + // validate changeAdmin message was created as intended + require.Equal(t, baseMsg.Route(), types.RouterKey) + require.Equal(t, baseMsg.Type(), "change_admin") + signers := baseMsg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1.String()) + + tests := []struct { + name string + msg func() *types.MsgChangeAdmin + expectPass bool + }{ + { + name: "proper msg", + msg: func() *types.MsgChangeAdmin { + msg := baseMsg + return msg + }, + expectPass: true, + }, + { + name: "empty sender", + msg: func() *types.MsgChangeAdmin { + msg := baseMsg + msg.Sender = "" + return msg + }, + expectPass: false, + }, + { + name: "empty newAdmin", + msg: func() *types.MsgChangeAdmin { + msg := baseMsg + msg.NewAdmin = "" + return msg + }, + expectPass: false, + }, + { + name: "invalid denom", + msg: func() *types.MsgChangeAdmin { + msg := baseMsg + msg.Denom = "bitcoin" + return msg + }, + expectPass: false, + }, + } + + for _, test := range tests { + if test.expectPass { + require.NoError(t, test.msg().ValidateBasic(), "test: %v", test.name) + } else { + require.Error(t, test.msg().ValidateBasic(), "test: %v", test.name) + } + } +} + +// TestMsgSetDenomMetadata tests if valid/invalid create denom messages are properly validated/invalidated +func TestMsgSetDenomMetadata(t *testing.T) { + // generate a private/public key pair and get the respective address + pk1 := ed25519.GenPrivKey().PubKey() + addr1 := sdk.AccAddress(pk1.Address()) + tokenFactoryDenom := fmt.Sprintf("factory/%s/bitcoin", addr1.String()) + denomMetadata := banktypes.Metadata{ + Description: "nakamoto", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: tokenFactoryDenom, + Exponent: 0, + }, + { + Denom: "sats", + Exponent: 6, + }, + }, + Display: "sats", + Base: tokenFactoryDenom, + Name: "bitcoin", + Symbol: "BTC", + } + invalidDenomMetadata := banktypes.Metadata{ + Description: "nakamoto", + DenomUnits: []*banktypes.DenomUnit{ + { + Denom: "bitcoin", + Exponent: 0, + }, + { + Denom: "sats", + Exponent: 6, + }, + }, + Display: "sats", + Base: "bitcoin", + Name: "bitcoin", + Symbol: "BTC", + } + + // make a proper setDenomMetadata message + baseMsg := types.NewMsgSetDenomMetadata( + addr1.String(), + denomMetadata, + ) + + // validate setDenomMetadata message was created as intended + require.Equal(t, baseMsg.Route(), types.RouterKey) + require.Equal(t, baseMsg.Type(), "set_denom_metadata") + signers := baseMsg.GetSigners() + require.Equal(t, len(signers), 1) + require.Equal(t, signers[0].String(), addr1.String()) + + tests := []struct { + name string + msg func() *types.MsgSetDenomMetadata + expectPass bool + }{ + { + name: "proper msg", + msg: func() *types.MsgSetDenomMetadata { + msg := baseMsg + return msg + }, + expectPass: true, + }, + { + name: "empty sender", + msg: func() *types.MsgSetDenomMetadata { + msg := baseMsg + msg.Sender = "" + return msg + }, + expectPass: false, + }, + { + name: "invalid metadata", + msg: func() *types.MsgSetDenomMetadata { + msg := baseMsg + msg.Metadata.Name = "" + return msg + }, + + expectPass: false, + }, + { + name: "invalid base", + msg: func() *types.MsgSetDenomMetadata { + msg := baseMsg + msg.Metadata = invalidDenomMetadata + return msg + }, + expectPass: false, + }, + } + + for _, test := range tests { + if test.expectPass { + require.NoError(t, test.msg().ValidateBasic(), "test: %v", test.name) + } else { + require.Error(t, test.msg().ValidateBasic(), "test: %v", test.name) + } + } +} diff --git a/x/tokenfactory/types/params.go b/x/tokenfactory/types/params.go new file mode 100644 index 0000000..a483078 --- /dev/null +++ b/x/tokenfactory/types/params.go @@ -0,0 +1,62 @@ +package types + +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. +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 + } +} + +// validate params. +func (p Params) Validate() error { + if err := validateDenomCreationFee(p.DenomCreationFee); err != nil { + return err + } + + return nil +} + +// Implements params.ParamSet. +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{ + paramtypes.NewParamSetPair(KeyDenomCreationFee, &p.DenomCreationFee, validateDenomCreationFee), + } +} + +func validateDenomCreationFee(i interface{}) error { + v, ok := i.(sdk.Coins) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v.Validate() != nil { + return fmt.Errorf("invalid denom creation fee: %+v", i) + } + + return nil +} diff --git a/x/terp/types/params.pb.go b/x/tokenfactory/types/params.pb.go similarity index 52% rename from x/terp/types/params.pb.go rename to x/tokenfactory/types/params.pb.go index d8145b0..4d11ce5 100644 --- a/x/terp/types/params.pb.go +++ b/x/tokenfactory/types/params.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: terp/params.proto +// source: cosmwasm/tokenfactory/v1beta1/params.proto package types @@ -9,8 +9,11 @@ import ( math "math" math_bits "math/bits" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" + _ "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" ) // Reference imports to suppress errors if they are not otherwise used. @@ -26,13 +29,16 @@ var ( // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// Params defines the parameters for the module. -type Params struct{} +// 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"` +} -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} +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_33fe6ea42a5fee55, []int{0} + return fileDescriptor_c2e403a2e90cdef7, []int{0} } func (m *Params) XXX_Unmarshal(b []byte) error { @@ -66,24 +72,43 @@ func (m *Params) XXX_DiscardUnknown() { var xxx_messageInfo_Params proto.InternalMessageInfo +func (m *Params) GetDenomCreationFee() github_com_cosmos_cosmos_sdk_types.Coins { + if m != nil { + return m.DenomCreationFee + } + return nil +} + func init() { - proto.RegisterType((*Params)(nil), "terpnetwork.terp.terp.Params") + proto.RegisterType((*Params)(nil), "cosmwasm.tokenfactory.v1beta1.Params") } -func init() { proto.RegisterFile("terp/params.proto", fileDescriptor_33fe6ea42a5fee55) } +func init() { + proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/params.proto", fileDescriptor_c2e403a2e90cdef7) +} -var fileDescriptor_33fe6ea42a5fee55 = []byte{ - // 155 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4c, 0x4a, 0xce, 0x4b, - 0xd4, 0x2f, 0x48, 0x2c, 0x4a, 0xcc, 0x2d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x92, 0x48, - 0xca, 0x2c, 0x49, 0x4e, 0xcc, 0xcb, 0x4b, 0x4c, 0xcf, 0xc9, 0x4f, 0x4a, 0xcc, 0xd1, 0x03, 0xa9, - 0x00, 0x13, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, 0x60, 0x45, 0xfa, 0x20, 0x16, 0x44, 0xbd, 0x12, - 0x1f, 0x17, 0x5b, 0x00, 0x58, 0xbf, 0x15, 0xcb, 0x8c, 0x05, 0xf2, 0x0c, 0x4e, 0xae, 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, 0x9d, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, - 0x97, 0x9c, 0x9f, 0xab, 0xef, 0x94, 0x59, 0xe2, 0x0c, 0xb2, 0xc4, 0x1d, 0x6c, 0x89, 0x3e, 0xd8, - 0x19, 0x15, 0x10, 0xaa, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x6c, 0xba, 0x31, 0x20, 0x00, - 0x00, 0xff, 0xff, 0xfb, 0xe9, 0x74, 0xd6, 0xa2, 0x00, 0x00, 0x00, +var fileDescriptor_c2e403a2e90cdef7 = []byte{ + // 309 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x90, 0x31, 0x4b, 0xc3, 0x40, + 0x14, 0xc7, 0x73, 0x08, 0x1d, 0xea, 0x22, 0xc5, 0xc1, 0x16, 0xbc, 0x48, 0xa6, 0x22, 0x78, 0x47, + 0x15, 0x17, 0xc7, 0x06, 0xc4, 0xa5, 0x20, 0x2e, 0x82, 0x4b, 0x78, 0x49, 0xae, 0x69, 0xa8, 0x97, + 0x17, 0x72, 0x57, 0x35, 0xdf, 0xc2, 0xc9, 0xdd, 0xd5, 0x4f, 0xd2, 0xb1, 0xa3, 0x53, 0x95, 0xe4, + 0x1b, 0xf8, 0x09, 0x24, 0x97, 0xab, 0x54, 0x04, 0xa7, 0xbb, 0xc7, 0xfb, 0xff, 0x7f, 0xef, 0xbd, + 0x7f, 0xf7, 0x38, 0x42, 0x25, 0x1f, 0x41, 0x49, 0xae, 0x71, 0x2e, 0xb2, 0x29, 0x44, 0x1a, 0x8b, + 0x92, 0x3f, 0x8c, 0x42, 0xa1, 0x61, 0xc4, 0x73, 0x28, 0x40, 0x2a, 0x96, 0x17, 0xa8, 0xb1, 0x77, + 0xb8, 0xd1, 0xb2, 0x6d, 0x2d, 0xb3, 0xda, 0xc1, 0x7e, 0x82, 0x09, 0x1a, 0x25, 0x6f, 0x7e, 0xad, + 0x69, 0x70, 0xfe, 0xff, 0x00, 0x58, 0xe8, 0x19, 0x16, 0xa9, 0x2e, 0x27, 0x42, 0x43, 0x0c, 0x1a, + 0xac, 0xad, 0xdf, 0xd8, 0x50, 0x05, 0x2d, 0xaf, 0x2d, 0x6c, 0x8b, 0xb6, 0x15, 0x0f, 0x41, 0x89, + 0x1f, 0x4e, 0x84, 0x69, 0xd6, 0xf6, 0xbd, 0x57, 0xd2, 0xed, 0x5c, 0x9b, 0xbd, 0x7b, 0x2f, 0xa4, + 0xdb, 0x8b, 0x45, 0x86, 0x32, 0x88, 0x0a, 0x01, 0x3a, 0xc5, 0x2c, 0x98, 0x0a, 0x71, 0x40, 0x8e, + 0x76, 0x86, 0xbb, 0xa7, 0x7d, 0x66, 0xb1, 0x0d, 0x68, 0x73, 0x05, 0xf3, 0x31, 0xcd, 0xc6, 0x93, + 0xe5, 0xda, 0x75, 0xbe, 0xd6, 0x6e, 0xbf, 0x04, 0x79, 0x7f, 0xe1, 0xfd, 0x45, 0x78, 0x6f, 0x1f, + 0xee, 0x30, 0x49, 0xf5, 0x6c, 0x11, 0xb2, 0x08, 0xa5, 0x5d, 0xd0, 0x3e, 0x27, 0x2a, 0x9e, 0x73, + 0x5d, 0xe6, 0x42, 0x19, 0x9a, 0xba, 0xd9, 0x33, 0x00, 0xdf, 0xfa, 0x2f, 0x85, 0x18, 0x5f, 0x2d, + 0x2b, 0x4a, 0x56, 0x15, 0x25, 0x9f, 0x15, 0x25, 0xcf, 0x35, 0x75, 0x56, 0x35, 0x75, 0xde, 0x6b, + 0xea, 0xdc, 0xb1, 0x2d, 0xaa, 0x8f, 0x4a, 0xde, 0x36, 0xd1, 0x35, 0xf9, 0xc5, 0xfc, 0xe9, 0x77, + 0x84, 0x66, 0x42, 0xd8, 0x31, 0x47, 0x9f, 0x7d, 0x07, 0x00, 0x00, 0xff, 0xff, 0xad, 0xc5, 0x5a, + 0xa9, 0xc9, 0x01, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -106,6 +131,20 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.DenomCreationFee) > 0 { + for iNdEx := len(m.DenomCreationFee) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.DenomCreationFee[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintParams(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } return len(dAtA) - i, nil } @@ -127,6 +166,12 @@ func (m *Params) Size() (n int) { } var l int _ = l + if len(m.DenomCreationFee) > 0 { + for _, e := range m.DenomCreationFee { + l = e.Size() + n += 1 + l + sovParams(uint64(l)) + } + } return n } @@ -167,6 +212,40 @@ func (m *Params) Unmarshal(dAtA []byte) error { 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 DenomCreationFee", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowParams + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthParams + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthParams + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DenomCreationFee = append(m.DenomCreationFee, types.Coin{}) + if err := m.DenomCreationFee[len(m.DenomCreationFee)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipParams(dAtA[iNdEx:]) diff --git a/x/tokenfactory/types/query.pb.go b/x/tokenfactory/types/query.pb.go new file mode 100644 index 0000000..5ae450f --- /dev/null +++ b/x/tokenfactory/types/query.pb.go @@ -0,0 +1,1377 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmwasm/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" + 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 + +// 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_d8606ce711f56ea6, []int{0} +} + +func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} + +func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsRequest.Merge(m, src) +} + +func (m *QueryParamsRequest) XXX_Size() int { + return m.Size() +} + +func (m *QueryParamsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo + +// QueryParamsResponse is 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_d8606ce711f56ea6, []int{1} +} + +func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} + +func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} + +func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsResponse.Merge(m, src) +} + +func (m *QueryParamsResponse) XXX_Size() int { + return m.Size() +} + +func (m *QueryParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo + +func (m *QueryParamsResponse) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +// QueryDenomAuthorityMetadataRequest defines the request structure for the +// DenomAuthorityMetadata gRPC query. +type QueryDenomAuthorityMetadataRequest struct { + Denom string `protobuf:"bytes,1,opt,name=denom,proto3" json:"denom,omitempty" yaml:"denom"` +} + +func (m *QueryDenomAuthorityMetadataRequest) Reset() { *m = QueryDenomAuthorityMetadataRequest{} } +func (m *QueryDenomAuthorityMetadataRequest) String() string { return proto.CompactTextString(m) } +func (*QueryDenomAuthorityMetadataRequest) ProtoMessage() {} +func (*QueryDenomAuthorityMetadataRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_d8606ce711f56ea6, []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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_QueryDenomAuthorityMetadataRequest proto.InternalMessageInfo + +func (m *QueryDenomAuthorityMetadataRequest) GetDenom() string { + if m != nil { + return m.Denom + } + return "" +} + +// QueryDenomAuthorityMetadataResponse defines the response structure for the +// DenomAuthorityMetadata gRPC query. +type QueryDenomAuthorityMetadataResponse struct { + AuthorityMetadata DenomAuthorityMetadata `protobuf:"bytes,1,opt,name=authority_metadata,json=authorityMetadata,proto3" json:"authority_metadata" yaml:"authority_metadata"` +} + +func (m *QueryDenomAuthorityMetadataResponse) Reset() { *m = QueryDenomAuthorityMetadataResponse{} } +func (m *QueryDenomAuthorityMetadataResponse) String() string { return proto.CompactTextString(m) } +func (*QueryDenomAuthorityMetadataResponse) ProtoMessage() {} +func (*QueryDenomAuthorityMetadataResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_d8606ce711f56ea6, []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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_QueryDenomAuthorityMetadataResponse proto.InternalMessageInfo + +func (m *QueryDenomAuthorityMetadataResponse) GetAuthorityMetadata() DenomAuthorityMetadata { + if m != nil { + return m.AuthorityMetadata + } + return DenomAuthorityMetadata{} +} + +// QueryDenomsFromCreatorRequest defines the request structure for the +// DenomsFromCreator gRPC query. +type QueryDenomsFromCreatorRequest struct { + Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty" yaml:"creator"` +} + +func (m *QueryDenomsFromCreatorRequest) Reset() { *m = QueryDenomsFromCreatorRequest{} } +func (m *QueryDenomsFromCreatorRequest) String() string { return proto.CompactTextString(m) } +func (*QueryDenomsFromCreatorRequest) ProtoMessage() {} +func (*QueryDenomsFromCreatorRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_d8606ce711f56ea6, []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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_QueryDenomsFromCreatorRequest proto.InternalMessageInfo + +func (m *QueryDenomsFromCreatorRequest) GetCreator() string { + if m != nil { + return m.Creator + } + return "" +} + +// QueryDenomsFromCreatorRequest defines the response structure for the +// DenomsFromCreator gRPC query. +type QueryDenomsFromCreatorResponse struct { + Denoms []string `protobuf:"bytes,1,rep,name=denoms,proto3" json:"denoms,omitempty" yaml:"denoms"` +} + +func (m *QueryDenomsFromCreatorResponse) Reset() { *m = QueryDenomsFromCreatorResponse{} } +func (m *QueryDenomsFromCreatorResponse) String() string { return proto.CompactTextString(m) } +func (*QueryDenomsFromCreatorResponse) ProtoMessage() {} +func (*QueryDenomsFromCreatorResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_d8606ce711f56ea6, []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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_QueryDenomsFromCreatorResponse proto.InternalMessageInfo + +func (m *QueryDenomsFromCreatorResponse) GetDenoms() []string { + if m != nil { + return m.Denoms + } + return nil +} + +func init() { + proto.RegisterType((*QueryParamsRequest)(nil), "cosmwasm.tokenfactory.v1beta1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "cosmwasm.tokenfactory.v1beta1.QueryParamsResponse") + proto.RegisterType((*QueryDenomAuthorityMetadataRequest)(nil), "cosmwasm.tokenfactory.v1beta1.QueryDenomAuthorityMetadataRequest") + proto.RegisterType((*QueryDenomAuthorityMetadataResponse)(nil), "cosmwasm.tokenfactory.v1beta1.QueryDenomAuthorityMetadataResponse") + proto.RegisterType((*QueryDenomsFromCreatorRequest)(nil), "cosmwasm.tokenfactory.v1beta1.QueryDenomsFromCreatorRequest") + proto.RegisterType((*QueryDenomsFromCreatorResponse)(nil), "cosmwasm.tokenfactory.v1beta1.QueryDenomsFromCreatorResponse") +} + +func init() { + proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/query.proto", fileDescriptor_d8606ce711f56ea6) +} + +var fileDescriptor_d8606ce711f56ea6 = []byte{ + // 580 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0xcf, 0x6b, 0x13, 0x41, + 0x14, 0xce, 0x6a, 0x1b, 0xe9, 0xf8, 0x03, 0x3b, 0x16, 0xd1, 0x60, 0x37, 0x3a, 0x6a, 0x69, 0xa5, + 0xec, 0x90, 0x48, 0x2f, 0x6a, 0x91, 0x6c, 0x44, 0x05, 0x2d, 0xe8, 0x5e, 0x84, 0x5e, 0xc2, 0x24, + 0x99, 0x6e, 0x17, 0xbb, 0xfb, 0xb6, 0x3b, 0x13, 0x35, 0x94, 0x5e, 0xbc, 0x78, 0x15, 0x3c, 0xfb, + 0x37, 0xf8, 0x6f, 0xf4, 0x58, 0x10, 0xc1, 0x53, 0x90, 0xc4, 0x83, 0x78, 0xcc, 0x5f, 0x20, 0x3b, + 0x33, 0xa9, 0xa9, 0x49, 0xb7, 0x51, 0x4f, 0x59, 0xde, 0xfb, 0xde, 0xf7, 0xbe, 0xef, 0xbd, 0x97, + 0x41, 0x4b, 0x0d, 0x10, 0xe1, 0x6b, 0x26, 0x42, 0x2a, 0xe1, 0x25, 0x8f, 0x36, 0x58, 0x43, 0x42, + 0xd2, 0xa6, 0xaf, 0x4a, 0x75, 0x2e, 0x59, 0x89, 0x6e, 0xb7, 0x78, 0xd2, 0x76, 0xe2, 0x04, 0x24, + 0xe0, 0xf9, 0x01, 0xd4, 0x19, 0x86, 0x3a, 0x06, 0x5a, 0x98, 0xf3, 0xc1, 0x07, 0x85, 0xa4, 0xe9, + 0x97, 0x2e, 0x2a, 0x5c, 0xf1, 0x01, 0xfc, 0x2d, 0x4e, 0x59, 0x1c, 0x50, 0x16, 0x45, 0x20, 0x99, + 0x0c, 0x20, 0x12, 0x26, 0x7b, 0x2b, 0xa5, 0x04, 0x41, 0xeb, 0x4c, 0x70, 0xdd, 0xeb, 0xa0, 0x73, + 0xcc, 0xfc, 0x20, 0x52, 0x60, 0x83, 0x5d, 0xc9, 0x56, 0xca, 0x5a, 0x72, 0x13, 0x92, 0x40, 0xb6, + 0xd7, 0xb8, 0x64, 0x4d, 0x26, 0xd9, 0x70, 0x8b, 0xa3, 0xcb, 0x62, 0x96, 0xb0, 0xd0, 0xc8, 0x21, + 0x73, 0x08, 0x3f, 0x4f, 0x45, 0x3c, 0x53, 0x41, 0x8f, 0x6f, 0xb7, 0xb8, 0x90, 0x64, 0x1d, 0x5d, + 0x38, 0x14, 0x15, 0x31, 0x44, 0x82, 0xe3, 0x2a, 0xca, 0xeb, 0xe2, 0x4b, 0xd6, 0x55, 0x6b, 0xf1, + 0x74, 0xf9, 0xa6, 0x93, 0x39, 0x1f, 0x47, 0x97, 0xbb, 0x53, 0x7b, 0x9d, 0x62, 0xce, 0x33, 0xa5, + 0xe4, 0x29, 0x22, 0x8a, 0xfb, 0x01, 0x8f, 0x20, 0xac, 0xfc, 0x69, 0xc1, 0x28, 0xc0, 0x0b, 0x68, + 0xba, 0x99, 0x02, 0x54, 0xa7, 0x19, 0xf7, 0x7c, 0xbf, 0x53, 0x3c, 0xd3, 0x66, 0xe1, 0xd6, 0x1d, + 0xa2, 0xc2, 0xc4, 0xd3, 0x69, 0xf2, 0xc9, 0x42, 0xd7, 0x33, 0xe9, 0x8c, 0xf4, 0x77, 0x16, 0xc2, + 0x07, 0xf3, 0xaa, 0x85, 0x26, 0x6d, 0x7c, 0xac, 0x1c, 0xe3, 0x63, 0x3c, 0xb7, 0x7b, 0x2d, 0xf5, + 0xd5, 0xef, 0x14, 0x2f, 0x6b, 0x61, 0xa3, 0xf4, 0xc4, 0x9b, 0x1d, 0xd9, 0x11, 0x59, 0x43, 0xf3, + 0xbf, 0x05, 0x8b, 0x87, 0x09, 0x84, 0xd5, 0x84, 0x33, 0x09, 0xc9, 0xc0, 0xfa, 0x32, 0x3a, 0xd5, + 0xd0, 0x11, 0x63, 0x1e, 0xf7, 0x3b, 0xc5, 0x73, 0xba, 0x87, 0x49, 0x10, 0x6f, 0x00, 0x21, 0x4f, + 0x90, 0x7d, 0x14, 0x9d, 0xb1, 0xbe, 0x84, 0xf2, 0x6a, 0x56, 0xe9, 0xd6, 0x4e, 0x2e, 0xce, 0xb8, + 0xb3, 0xfd, 0x4e, 0xf1, 0xec, 0xd0, 0x2c, 0x05, 0xf1, 0x0c, 0xa0, 0xfc, 0x73, 0x0a, 0x4d, 0x2b, + 0x36, 0xfc, 0xd1, 0x42, 0x79, 0xbd, 0x3e, 0x5c, 0x3a, 0x66, 0x3a, 0xa3, 0xf7, 0x53, 0x28, 0xff, + 0x4d, 0x89, 0x96, 0x49, 0x96, 0xdf, 0x7e, 0xfe, 0xfe, 0xe1, 0xc4, 0x02, 0xbe, 0x41, 0xd5, 0x1f, + 0x24, 0x10, 0x59, 0xd7, 0x8b, 0x7f, 0x58, 0xe8, 0xe2, 0xf8, 0xb5, 0xe0, 0xca, 0x24, 0xcd, 0x33, + 0xaf, 0xaf, 0xe0, 0xfe, 0x0f, 0x85, 0xf1, 0xf3, 0x48, 0xf9, 0xa9, 0xe0, 0xfb, 0xd9, 0x7e, 0xf4, + 0xe4, 0xe9, 0x8e, 0xfa, 0xdd, 0xa5, 0xa3, 0x47, 0x84, 0xbf, 0x58, 0x68, 0x76, 0x64, 0xbb, 0xf8, + 0xde, 0xc4, 0x12, 0xc7, 0xdc, 0x58, 0x61, 0xf5, 0x1f, 0xab, 0x8d, 0xb7, 0xaa, 0xf2, 0xb6, 0x8a, + 0xef, 0x4e, 0xe2, 0xad, 0xb6, 0x91, 0x40, 0x58, 0x33, 0xf7, 0x4a, 0x77, 0xcc, 0xc7, 0xae, 0xfb, + 0x78, 0xaf, 0x6b, 0x5b, 0xfb, 0x5d, 0xdb, 0xfa, 0xd6, 0xb5, 0xad, 0xf7, 0x3d, 0x3b, 0xb7, 0xdf, + 0xb3, 0x73, 0x5f, 0x7b, 0x76, 0x6e, 0xdd, 0xf1, 0x03, 0xb9, 0xd9, 0xaa, 0x3b, 0x0d, 0x08, 0x69, + 0x15, 0x44, 0xf8, 0x22, 0x7d, 0xcb, 0x52, 0xb1, 0x4d, 0xfa, 0xe6, 0x70, 0x27, 0xd9, 0x8e, 0xb9, + 0xa8, 0xe7, 0xd5, 0x5b, 0x76, 0xfb, 0x57, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa5, 0xea, 0x8e, 0xf0, + 0xda, 0x05, 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 + +// 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 { + // Params defines a gRPC query method that returns the tokenfactory module's + // parameters. + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + // DenomAuthorityMetadata defines a gRPC query method for fetching + // DenomAuthorityMetadata for a particular denom. + DenomAuthorityMetadata(ctx context.Context, in *QueryDenomAuthorityMetadataRequest, opts ...grpc.CallOption) (*QueryDenomAuthorityMetadataResponse, error) + // DenomsFromCreator defines a gRPC query method for fetching all + // denominations created by a specific admin/creator. + DenomsFromCreator(ctx context.Context, in *QueryDenomsFromCreatorRequest, opts ...grpc.CallOption) (*QueryDenomsFromCreatorResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/cosmwasm.tokenfactory.v1beta1.Query/Params", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) DenomAuthorityMetadata(ctx context.Context, in *QueryDenomAuthorityMetadataRequest, opts ...grpc.CallOption) (*QueryDenomAuthorityMetadataResponse, error) { + out := new(QueryDenomAuthorityMetadataResponse) + err := c.cc.Invoke(ctx, "/cosmwasm.tokenfactory.v1beta1.Query/DenomAuthorityMetadata", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) DenomsFromCreator(ctx context.Context, in *QueryDenomsFromCreatorRequest, opts ...grpc.CallOption) (*QueryDenomsFromCreatorResponse, error) { + out := new(QueryDenomsFromCreatorResponse) + err := c.cc.Invoke(ctx, "/cosmwasm.tokenfactory.v1beta1.Query/DenomsFromCreator", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Params defines a gRPC query method that returns the tokenfactory module's + // parameters. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + // DenomAuthorityMetadata defines a gRPC query method for fetching + // DenomAuthorityMetadata for a particular denom. + DenomAuthorityMetadata(context.Context, *QueryDenomAuthorityMetadataRequest) (*QueryDenomAuthorityMetadataResponse, error) + // DenomsFromCreator defines a gRPC query method for fetching all + // denominations created by a specific admin/creator. + DenomsFromCreator(context.Context, *QueryDenomsFromCreatorRequest) (*QueryDenomsFromCreatorResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct{} + +func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") +} + +func (*UnimplementedQueryServer) 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") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryParamsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Params(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.tokenfactory.v1beta1.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_DenomAuthorityMetadata_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryDenomAuthorityMetadataRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).DenomAuthorityMetadata(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.tokenfactory.v1beta1.Query/DenomAuthorityMetadata", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).DenomAuthorityMetadata(ctx, req.(*QueryDenomAuthorityMetadataRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_DenomsFromCreator_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryDenomsFromCreatorRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).DenomsFromCreator(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.tokenfactory.v1beta1.Query/DenomsFromCreator", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).DenomsFromCreator(ctx, req.(*QueryDenomsFromCreatorRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cosmwasm.tokenfactory.v1beta1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + { + MethodName: "DenomAuthorityMetadata", + Handler: _Query_DenomAuthorityMetadata_Handler, + }, + { + MethodName: "DenomsFromCreator", + Handler: _Query_DenomsFromCreator_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmwasm/tokenfactory/v1beta1/query.proto", +} + +func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *QueryDenomAuthorityMetadataRequest) 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 *QueryDenomAuthorityMetadataRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryDenomAuthorityMetadataRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Denom) > 0 { + i -= len(m.Denom) + copy(dAtA[i:], m.Denom) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Denom))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryDenomAuthorityMetadataResponse) 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 *QueryDenomAuthorityMetadataResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryDenomAuthorityMetadataResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.AuthorityMetadata.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 *QueryDenomsFromCreatorRequest) 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 *QueryDenomsFromCreatorRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryDenomsFromCreatorRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Creator) > 0 { + i -= len(m.Creator) + copy(dAtA[i:], m.Creator) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Creator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryDenomsFromCreatorResponse) 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 *QueryDenomsFromCreatorResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryDenomsFromCreatorResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Denoms) > 0 { + for iNdEx := len(m.Denoms) - 1; iNdEx >= 0; iNdEx-- { + i -= len(m.Denoms[iNdEx]) + copy(dAtA[i:], m.Denoms[iNdEx]) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Denoms[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 *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 *QueryDenomAuthorityMetadataRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Denom) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryDenomAuthorityMetadataResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.AuthorityMetadata.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryDenomsFromCreatorRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Creator) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryDenomsFromCreatorResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Denoms) > 0 { + for _, s := range m.Denoms { + l = len(s) + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} + +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} + +func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func (m *QueryDenomAuthorityMetadataRequest) 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: QueryDenomAuthorityMetadataRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryDenomAuthorityMetadataRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 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.Denom = 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 *QueryDenomAuthorityMetadataResponse) 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: QueryDenomAuthorityMetadataResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryDenomAuthorityMetadataResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AuthorityMetadata", 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.AuthorityMetadata.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 *QueryDenomsFromCreatorRequest) 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: QueryDenomsFromCreatorRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryDenomsFromCreatorRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Creator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + 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 *QueryDenomsFromCreatorResponse) 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: QueryDenomsFromCreatorResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryDenomsFromCreatorResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Denoms", 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.Denoms = append(m.Denoms, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} + +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/tokenfactory/types/query.pb.gw.go b/x/tokenfactory/types/query.pb.gw.go new file mode 100644 index 0000000..af07c01 --- /dev/null +++ b/x/tokenfactory/types/query.pb.gw.go @@ -0,0 +1,343 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: cosmwasm/tokenfactory/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 + _ io.Reader + _ status.Status + _ = runtime.String + _ = utilities.NewDoubleArray + _ = descriptor.ForMessage + _ = metadata.Join +) + +func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err +} + +func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := server.Params(ctx, &protoReq) + return msg, metadata, err +} + +func request_Query_DenomAuthorityMetadata_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryDenomAuthorityMetadataRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["denom"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") + } + + protoReq.Denom, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) + } + + 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) { + var protoReq QueryDenomAuthorityMetadataRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["denom"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "denom") + } + + protoReq.Denom, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "denom", err) + } + + 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) { + var protoReq QueryDenomsFromCreatorRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["creator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "creator") + } + + protoReq.Creator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "creator", err) + } + + 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) { + var protoReq QueryDenomsFromCreatorRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["creator"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "creator") + } + + protoReq.Creator, err = runtime.String(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "creator", err) + } + + msg, err := server.DenomsFromCreator(ctx, &protoReq) + return msg, metadata, err +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_DenomAuthorityMetadata_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_DenomAuthorityMetadata_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_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) { + 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_DenomsFromCreator_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_DenomsFromCreator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + mux.Handle("GET", pattern_Query_DenomAuthorityMetadata_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_DenomAuthorityMetadata_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_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) { + 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_DenomsFromCreator_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_DenomsFromCreator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + }) + + return nil +} + +var ( + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"osmosis", "tokenfactory", "v1beta1", "params"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_DenomAuthorityMetadata_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4, 2, 5}, []string{"osmosis", "tokenfactory", "v1beta1", "denoms", "denom", "authority_metadata"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_DenomsFromCreator_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 1, 0, 4, 1, 5, 4}, []string{"osmosis", "tokenfactory", "v1beta1", "denoms_from_creator", "creator"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_Params_0 = runtime.ForwardResponseMessage + + forward_Query_DenomAuthorityMetadata_0 = runtime.ForwardResponseMessage + + forward_Query_DenomsFromCreator_0 = runtime.ForwardResponseMessage +) diff --git a/x/tokenfactory/types/tx.pb.go b/x/tokenfactory/types/tx.pb.go new file mode 100644 index 0000000..0f583f8 --- /dev/null +++ b/x/tokenfactory/types/tx.pb.go @@ -0,0 +1,2304 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmwasm/tokenfactory/v1beta1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + io "io" + math "math" + math_bits "math/bits" + + types "github.com/cosmos/cosmos-sdk/types" + types1 "github.com/cosmos/cosmos-sdk/x/bank/types" + _ "github.com/cosmos/gogoproto/gogoproto" + grpc1 "github.com/cosmos/gogoproto/grpc" + proto "github.com/cosmos/gogoproto/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// 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 + +// 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. +type MsgCreateDenom struct { + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` + // subdenom can be up to 44 "alphanumeric" characters long. + Subdenom string `protobuf:"bytes,2,opt,name=subdenom,proto3" json:"subdenom,omitempty" yaml:"subdenom"` +} + +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_MsgCreateDenom proto.InternalMessageInfo + +func (m *MsgCreateDenom) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgCreateDenom) GetSubdenom() string { + if m != nil { + return m.Subdenom + } + return "" +} + +// MsgCreateDenomResponse is the return value of MsgCreateDenom +// 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"` +} + +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_MsgCreateDenomResponse proto.InternalMessageInfo + +func (m *MsgCreateDenomResponse) GetNewTokenDenom() string { + if m != nil { + return m.NewTokenDenom + } + return "" +} + +// 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"` +} + +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_MsgMint proto.InternalMessageInfo + +func (m *MsgMint) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgMint) GetAmount() types.Coin { + if m != nil { + return m.Amount + } + return types.Coin{} +} + +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, 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) +} + +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"` +} + +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_MsgBurn proto.InternalMessageInfo + +func (m *MsgBurn) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgBurn) GetAmount() types.Coin { + if m != nil { + return m.Amount + } + return types.Coin{} +} + +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, 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) +} + +var xxx_messageInfo_MsgBurnResponse proto.InternalMessageInfo + +// MsgChangeAdmin is the sdk.Msg type for allowing an admin account to reassign +// adminship of a denom to a new account +type MsgChangeAdmin struct { + Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"` + Denom string `protobuf:"bytes,2,opt,name=denom,proto3" json:"denom,omitempty" yaml:"denom"` + NewAdmin string `protobuf:"bytes,3,opt,name=new_admin,json=newAdmin,proto3" json:"new_admin,omitempty" yaml:"new_admin"` +} + +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_MsgChangeAdmin proto.InternalMessageInfo + +func (m *MsgChangeAdmin) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgChangeAdmin) GetDenom() string { + if m != nil { + return m.Denom + } + return "" +} + +func (m *MsgChangeAdmin) GetNewAdmin() string { + if m != nil { + return m.NewAdmin + } + return "" +} + +// MsgChangeAdminResponse defines the response structure for an executed +// MsgChangeAdmin message. +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_MsgChangeAdminResponse proto.InternalMessageInfo + +// MsgSetDenomMetadata is the sdk.Msg type for allowing an admin account to set +// 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"` +} + +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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) +} + +var xxx_messageInfo_MsgSetDenomMetadata proto.InternalMessageInfo + +func (m *MsgSetDenomMetadata) GetSender() string { + if m != nil { + return m.Sender + } + return "" +} + +func (m *MsgSetDenomMetadata) GetMetadata() types1.Metadata { + if m != nil { + return m.Metadata + } + return types1.Metadata{} +} + +// MsgSetDenomMetadataResponse defines the response structure for an executed +// MsgSetDenomMetadata message. +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} +} + +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) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + 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 + +func init() { + proto.RegisterType((*MsgCreateDenom)(nil), "cosmwasm.tokenfactory.v1beta1.MsgCreateDenom") + proto.RegisterType((*MsgCreateDenomResponse)(nil), "cosmwasm.tokenfactory.v1beta1.MsgCreateDenomResponse") + proto.RegisterType((*MsgMint)(nil), "cosmwasm.tokenfactory.v1beta1.MsgMint") + proto.RegisterType((*MsgMintResponse)(nil), "cosmwasm.tokenfactory.v1beta1.MsgMintResponse") + proto.RegisterType((*MsgBurn)(nil), "cosmwasm.tokenfactory.v1beta1.MsgBurn") + proto.RegisterType((*MsgBurnResponse)(nil), "cosmwasm.tokenfactory.v1beta1.MsgBurnResponse") + proto.RegisterType((*MsgChangeAdmin)(nil), "cosmwasm.tokenfactory.v1beta1.MsgChangeAdmin") + proto.RegisterType((*MsgChangeAdminResponse)(nil), "cosmwasm.tokenfactory.v1beta1.MsgChangeAdminResponse") + proto.RegisterType((*MsgSetDenomMetadata)(nil), "cosmwasm.tokenfactory.v1beta1.MsgSetDenomMetadata") + proto.RegisterType((*MsgSetDenomMetadataResponse)(nil), "cosmwasm.tokenfactory.v1beta1.MsgSetDenomMetadataResponse") +} + +func init() { + proto.RegisterFile("cosmwasm/tokenfactory/v1beta1/tx.proto", fileDescriptor_345508fcea0bfc02) +} + +var fileDescriptor_345508fcea0bfc02 = []byte{ + // 592 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x55, 0xbf, 0x6e, 0xd3, 0x40, + 0x1c, 0x8e, 0x69, 0x09, 0xe9, 0x95, 0x92, 0xd4, 0x2d, 0x25, 0x18, 0xc5, 0x46, 0x37, 0x44, 0x30, + 0x60, 0x2b, 0x41, 0x2c, 0xdd, 0x70, 0x18, 0xba, 0x78, 0x31, 0x48, 0x48, 0x08, 0x51, 0x5d, 0x92, + 0xc3, 0x8d, 0x52, 0xdf, 0x45, 0xb9, 0x0b, 0x69, 0x16, 0x06, 0x9e, 0x80, 0x01, 0xf1, 0x24, 0x3c, + 0x44, 0xc7, 0x8e, 0x4c, 0x16, 0x4a, 0xde, 0x20, 0x4f, 0x80, 0xee, 0x8f, 0x1d, 0xa7, 0x41, 0x34, + 0x99, 0xba, 0x25, 0xfe, 0x7d, 0xdf, 0x77, 0xdf, 0x7d, 0xbf, 0xdf, 0xcf, 0x06, 0xf5, 0x0e, 0x65, + 0xf1, 0x18, 0xb1, 0xd8, 0xe3, 0xb4, 0x8f, 0xc9, 0x67, 0xd4, 0xe1, 0x74, 0x38, 0xf1, 0xbe, 0x34, + 0xda, 0x98, 0xa3, 0x86, 0xc7, 0x2f, 0xdc, 0xc1, 0x90, 0x72, 0x6a, 0xd6, 0x52, 0x9c, 0x9b, 0xc7, + 0xb9, 0x1a, 0x67, 0x1d, 0x46, 0x34, 0xa2, 0x12, 0xe9, 0x89, 0x5f, 0x8a, 0x64, 0xd9, 0x82, 0x44, + 0x99, 0xd7, 0x46, 0x0c, 0x67, 0x92, 0x1d, 0xda, 0x23, 0x2b, 0x75, 0xd2, 0xcf, 0xea, 0xe2, 0x8f, + 0xaa, 0xc3, 0x73, 0xf0, 0x20, 0x60, 0x51, 0x6b, 0x88, 0x11, 0xc7, 0x6f, 0x30, 0xa1, 0xb1, 0xf9, + 0x1c, 0x14, 0x19, 0x26, 0x5d, 0x3c, 0xac, 0x1a, 0x4f, 0x8d, 0x67, 0x3b, 0xfe, 0xfe, 0x3c, 0x71, + 0xf6, 0x26, 0x28, 0x3e, 0x3f, 0x86, 0xea, 0x39, 0x0c, 0x35, 0xc0, 0xf4, 0x40, 0x89, 0x8d, 0xda, + 0x5d, 0x41, 0xab, 0xde, 0x91, 0xe0, 0x83, 0x79, 0xe2, 0x94, 0x35, 0x58, 0x57, 0x60, 0x98, 0x81, + 0xe0, 0x47, 0x70, 0xb4, 0x7c, 0x5a, 0x88, 0xd9, 0x80, 0x12, 0x86, 0x4d, 0x1f, 0x94, 0x09, 0x1e, + 0x9f, 0xca, 0x9b, 0x9f, 0x2a, 0x45, 0x75, 0xbc, 0x35, 0x4f, 0x9c, 0x23, 0xa5, 0x78, 0x0d, 0x00, + 0xc3, 0x3d, 0x82, 0xc7, 0xef, 0xc4, 0x03, 0xa9, 0x05, 0xbf, 0x82, 0x7b, 0x01, 0x8b, 0x82, 0x1e, + 0xe1, 0x9b, 0x5c, 0xe2, 0x04, 0x14, 0x51, 0x4c, 0x47, 0x84, 0xcb, 0x2b, 0xec, 0x36, 0x1f, 0xbb, + 0x2a, 0x32, 0x57, 0x44, 0x9a, 0xa6, 0xef, 0xb6, 0x68, 0x8f, 0xf8, 0x0f, 0x2f, 0x13, 0xa7, 0xb0, + 0x50, 0x52, 0x34, 0x18, 0x6a, 0x3e, 0xdc, 0x07, 0x65, 0x7d, 0x7e, 0x7a, 0x2d, 0x6d, 0xc9, 0x1f, + 0x0d, 0xc9, 0x6d, 0x5a, 0x12, 0xe7, 0x67, 0x96, 0x7e, 0x1a, 0xaa, 0xe5, 0x67, 0x88, 0x44, 0xf8, + 0x75, 0x37, 0xee, 0x6d, 0x64, 0xad, 0x0e, 0xee, 0xe6, 0xfb, 0x5d, 0x99, 0x27, 0xce, 0x7d, 0x85, + 0xd4, 0x3d, 0x51, 0x65, 0xb3, 0x01, 0x76, 0x44, 0xbb, 0x90, 0xd0, 0xaf, 0x6e, 0x49, 0xec, 0xe1, + 0x3c, 0x71, 0x2a, 0x8b, 0x4e, 0xca, 0x12, 0x0c, 0x4b, 0x04, 0x8f, 0xa5, 0x0b, 0x58, 0x55, 0xc3, + 0xb1, 0xf0, 0x95, 0x59, 0xfe, 0x61, 0x80, 0x83, 0x80, 0x45, 0x6f, 0x31, 0x97, 0x8d, 0x0e, 0x30, + 0x47, 0x5d, 0xc4, 0xd1, 0x26, 0xbe, 0x43, 0x50, 0x8a, 0x35, 0x4d, 0x87, 0x5a, 0x5b, 0x84, 0x4a, + 0xfa, 0x59, 0xa8, 0xa9, 0xb6, 0xff, 0x48, 0x07, 0xab, 0xa7, 0x39, 0x25, 0xc3, 0x30, 0xd3, 0x81, + 0x35, 0xf0, 0xe4, 0x1f, 0xae, 0x52, 0xd7, 0xcd, 0x5f, 0xdb, 0x60, 0x2b, 0x60, 0x91, 0xc9, 0xc0, + 0x6e, 0x7e, 0xbf, 0x5e, 0xb8, 0xff, 0xdd, 0x73, 0x77, 0x79, 0x41, 0xac, 0x57, 0x1b, 0xc1, 0xb3, + 0x7d, 0xfa, 0x04, 0xb6, 0xe5, 0x22, 0xd4, 0x6f, 0xa6, 0x0b, 0x9c, 0xe5, 0xae, 0x87, 0xcb, 0xeb, + 0xcb, 0xa9, 0x5e, 0x43, 0x5f, 0xe0, 0xd6, 0xd1, 0xcf, 0x4f, 0xa9, 0x0c, 0x2d, 0x37, 0xa1, 0xeb, + 0x84, 0xb6, 0x80, 0xaf, 0x15, 0xda, 0xea, 0x9c, 0x99, 0xdf, 0x0c, 0x50, 0x59, 0x19, 0xb2, 0xe6, + 0xcd, 0x5a, 0xd7, 0x39, 0xd6, 0xf1, 0xe6, 0x9c, 0xd4, 0x84, 0x7f, 0x72, 0x39, 0xb5, 0x8d, 0xab, + 0xa9, 0x6d, 0xfc, 0x99, 0xda, 0xc6, 0xf7, 0x99, 0x5d, 0xb8, 0x9a, 0xd9, 0x85, 0xdf, 0x33, 0xbb, + 0xf0, 0xc1, 0x8d, 0x7a, 0xfc, 0x6c, 0xd4, 0x76, 0x3b, 0x34, 0xf6, 0x5a, 0x94, 0xc5, 0xef, 0xc5, + 0x37, 0x45, 0x1c, 0xd2, 0xf5, 0x2e, 0x96, 0xbf, 0x2d, 0x7c, 0x32, 0xc0, 0xac, 0x5d, 0x94, 0xaf, + 0xf8, 0x97, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xf8, 0x7f, 0x91, 0x62, 0x81, 0x06, 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 { + CreateDenom(ctx context.Context, in *MsgCreateDenom, opts ...grpc.CallOption) (*MsgCreateDenomResponse, error) + Mint(ctx context.Context, in *MsgMint, opts ...grpc.CallOption) (*MsgMintResponse, error) + Burn(ctx context.Context, in *MsgBurn, opts ...grpc.CallOption) (*MsgBurnResponse, error) + ChangeAdmin(ctx context.Context, in *MsgChangeAdmin, opts ...grpc.CallOption) (*MsgChangeAdminResponse, error) + SetDenomMetadata(ctx context.Context, in *MsgSetDenomMetadata, opts ...grpc.CallOption) (*MsgSetDenomMetadataResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) CreateDenom(ctx context.Context, in *MsgCreateDenom, opts ...grpc.CallOption) (*MsgCreateDenomResponse, error) { + out := new(MsgCreateDenomResponse) + err := c.cc.Invoke(ctx, "/cosmwasm.tokenfactory.v1beta1.Msg/CreateDenom", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) Mint(ctx context.Context, in *MsgMint, opts ...grpc.CallOption) (*MsgMintResponse, error) { + out := new(MsgMintResponse) + err := c.cc.Invoke(ctx, "/cosmwasm.tokenfactory.v1beta1.Msg/Mint", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) Burn(ctx context.Context, in *MsgBurn, opts ...grpc.CallOption) (*MsgBurnResponse, error) { + out := new(MsgBurnResponse) + err := c.cc.Invoke(ctx, "/cosmwasm.tokenfactory.v1beta1.Msg/Burn", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) ChangeAdmin(ctx context.Context, in *MsgChangeAdmin, opts ...grpc.CallOption) (*MsgChangeAdminResponse, error) { + out := new(MsgChangeAdminResponse) + err := c.cc.Invoke(ctx, "/cosmwasm.tokenfactory.v1beta1.Msg/ChangeAdmin", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *msgClient) SetDenomMetadata(ctx context.Context, in *MsgSetDenomMetadata, opts ...grpc.CallOption) (*MsgSetDenomMetadataResponse, error) { + out := new(MsgSetDenomMetadataResponse) + err := c.cc.Invoke(ctx, "/cosmwasm.tokenfactory.v1beta1.Msg/SetDenomMetadata", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + CreateDenom(context.Context, *MsgCreateDenom) (*MsgCreateDenomResponse, error) + Mint(context.Context, *MsgMint) (*MsgMintResponse, error) + Burn(context.Context, *MsgBurn) (*MsgBurnResponse, error) + ChangeAdmin(context.Context, *MsgChangeAdmin) (*MsgChangeAdminResponse, error) + SetDenomMetadata(context.Context, *MsgSetDenomMetadata) (*MsgSetDenomMetadataResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +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 RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_CreateDenom_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgCreateDenom) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).CreateDenom(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.tokenfactory.v1beta1.Msg/CreateDenom", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).CreateDenom(ctx, req.(*MsgCreateDenom)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_Mint_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgMint) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).Mint(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.tokenfactory.v1beta1.Msg/Mint", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).Mint(ctx, req.(*MsgMint)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_Burn_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgBurn) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).Burn(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.tokenfactory.v1beta1.Msg/Burn", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).Burn(ctx, req.(*MsgBurn)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_ChangeAdmin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgChangeAdmin) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).ChangeAdmin(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.tokenfactory.v1beta1.Msg/ChangeAdmin", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).ChangeAdmin(ctx, req.(*MsgChangeAdmin)) + } + return interceptor(ctx, in, info, handler) +} + +func _Msg_SetDenomMetadata_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgSetDenomMetadata) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).SetDenomMetadata(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.tokenfactory.v1beta1.Msg/SetDenomMetadata", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).SetDenomMetadata(ctx, req.(*MsgSetDenomMetadata)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cosmwasm.tokenfactory.v1beta1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "CreateDenom", + Handler: _Msg_CreateDenom_Handler, + }, + { + MethodName: "Mint", + Handler: _Msg_Mint_Handler, + }, + { + MethodName: "Burn", + Handler: _Msg_Burn_Handler, + }, + { + MethodName: "ChangeAdmin", + Handler: _Msg_ChangeAdmin_Handler, + }, + { + MethodName: "SetDenomMetadata", + Handler: _Msg_SetDenomMetadata_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmwasm/tokenfactory/v1beta1/tx.proto", +} + +func (m *MsgCreateDenom) 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 *MsgCreateDenom) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCreateDenom) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Subdenom) > 0 { + i -= len(m.Subdenom) + copy(dAtA[i:], m.Subdenom) + i = encodeVarintTx(dAtA, i, uint64(len(m.Subdenom))) + 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 *MsgCreateDenomResponse) 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 *MsgCreateDenomResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgCreateDenomResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.NewTokenDenom) > 0 { + i -= len(m.NewTokenDenom) + copy(dAtA[i:], m.NewTokenDenom) + i = encodeVarintTx(dAtA, i, uint64(len(m.NewTokenDenom))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgMint) 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 *MsgMint) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgMint) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + 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 *MsgMintResponse) 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 *MsgMintResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgMintResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgBurn) 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 *MsgBurn) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgBurn) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + 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 *MsgBurnResponse) 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 *MsgBurnResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgBurnResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgChangeAdmin) 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 *MsgChangeAdmin) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgChangeAdmin) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + 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] = 0x1a + } + if len(m.Denom) > 0 { + i -= len(m.Denom) + copy(dAtA[i:], m.Denom) + i = encodeVarintTx(dAtA, i, uint64(len(m.Denom))) + i-- + dAtA[i] = 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 *MsgChangeAdminResponse) 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 *MsgChangeAdminResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgChangeAdminResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *MsgSetDenomMetadata) 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 *MsgSetDenomMetadata) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSetDenomMetadata) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Metadata.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 *MsgSetDenomMetadataResponse) 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 *MsgSetDenomMetadataResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgSetDenomMetadataResponse) 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 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.Subdenom) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgCreateDenomResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.NewTokenDenom) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgMint) 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)) + return n +} + +func (m *MsgMintResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgBurn) 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)) + return n +} + +func (m *MsgBurnResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgChangeAdmin) 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.Denom) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + l = len(m.NewAdmin) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgChangeAdminResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *MsgSetDenomMetadata) 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.Metadata.Size() + n += 1 + l + sovTx(uint64(l)) + return n +} + +func (m *MsgSetDenomMetadataResponse) 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 + 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: MsgCreateDenom: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgCreateDenom: 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 Subdenom", 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.Subdenom = 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 *MsgCreateDenomResponse) 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: MsgCreateDenomResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgCreateDenomResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NewTokenDenom", 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.NewTokenDenom = 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 *MsgMint) 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: MsgMint: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgMint: 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 + 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 *MsgMintResponse) 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: MsgMintResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgMintResponse: 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 *MsgBurn) 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: MsgBurn: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgBurn: 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 + 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 *MsgBurnResponse) 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: MsgBurnResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgBurnResponse: 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 *MsgChangeAdmin) 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: MsgChangeAdmin: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgChangeAdmin: 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 Denom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Denom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 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 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 + 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 *MsgChangeAdminResponse) 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: MsgChangeAdminResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgChangeAdminResponse: 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 *MsgSetDenomMetadata) 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: MsgSetDenomMetadata: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSetDenomMetadata: 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 Metadata", 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.Metadata.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 *MsgSetDenomMetadataResponse) 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: MsgSetDenomMetadataResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgSetDenomMetadataResponse: 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/wasm/Governance.md b/x/wasm/Governance.md index a287cb4..8760412 100644 --- a/x/wasm/Governance.md +++ b/x/wasm/Governance.md @@ -3,60 +3,53 @@ 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. +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/CosmWasm/wasmd/blob/master/x/wasm/types/proposal.go) + +* `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/CosmWasm/wasmd/blob/master/x/wasm/types/proposal_test.go) +[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/CosmWasm/wasmd/blob/master/x/wasm/keeper/proposal_handler.go) implements the `gov.Handler` function +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/CosmWasm/wasmd/blob/master/x/wasm/keeper/authz_policy.go#L29) to bypass the existing contract's authorization policy. + +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/CosmWasm/wasmd/blob/master/x/wasm/keeper/proposal_integration_test.go) +* [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/CosmWasm/wasmd/blob/master/app/app.go#L306) -to receive proposal execution calls. - +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)) ``` -## Terpd Authorization Settings - -Settings via sdk `params` module: +## 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 +- `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/CosmWasm/wasmd/blob/master/x/wasm/types/params.go) +See [params.go](https://github.com/terpnetwork/terp-core/blob/master/x/wasm/types/params.go) -### Init Params Via Genesis +### Init Params Via Genesis ```json "wasm": { @@ -66,23 +59,18 @@ See [params.go](https://github.com/CosmWasm/wasmd/blob/master/x/wasm/types/param }, "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 - +* Disable wasm code uploads ```json { "title": "Foo", @@ -99,9 +87,7 @@ wasmd tx gov submit-proposal param-change --from validator "deposit": "" } ``` - -- Allow wasm code uploads for everybody - +* Allow wasm code uploads for everybody ```json { "title": "Foo", @@ -119,8 +105,7 @@ wasmd tx gov submit-proposal param-change --from validator } ``` -- Restrict code uploads to a single address - +* Restrict code uploads to a single address ```json { "title": "Foo", @@ -138,9 +123,7 @@ wasmd tx gov submit-proposal param-change --from validator "deposit": "" } ``` - -- Set chain **default** instantiation settings to nobody - +* Set chain **default** instantiation settings to nobody ```json { "title": "Foo", @@ -155,9 +138,7 @@ wasmd tx gov submit-proposal param-change --from validator "deposit": "" } ``` - -- Set chain **default** instantiation settings to everybody - +* Set chain **default** instantiation settings to everybody ```json { "title": "Foo", @@ -173,22 +154,19 @@ wasmd tx gov submit-proposal param-change --from validator } ``` -### 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. - +### 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/CosmWasm/wasmd/app.ProposalsEnabled=true - enable all x/wasm governance proposals (default false) --X github.com/CosmWasm/wasmd/app.EnableSpecificProposals=MigrateContract,UpdateAdmin,ClearAdmin - enable a subset of the x/wasm governance proposal types (overrides ProposalsEnabled) +-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/CosmWasm/wasmd/blob/master/x/wasm/types/params_test.go) -- [genesis validation tests](https://github.com/CosmWasm/wasmd/blob/master/x/wasm/types/genesis_test.go) -- [policy integration tests](https://github.com/CosmWasm/wasmd/blob/master/x/wasm/keeper/keeper_test.go) +* [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 @@ -203,29 +181,25 @@ Available Commands: 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) -New [`ProposalHandlers`](https://github.com/CosmWasm/wasmd/blob/master/x/wasm/client/proposal_handler.go) - -- Integration - +* Integration ```shell script gov.NewAppModuleBasic(append(wasmclient.ProposalHandlers, paramsclient.ProposalHandler, distr.ProposalHandler, upgradeclient.ProposalHandler)...), ``` - -In [abci app](https://github.com/CosmWasm/wasmd/blob/master/app/app.go#L109) +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) -- [Rest Unit tests](https://github.com/CosmWasm/wasmd/blob/master/x/wasm/client/proposal_handler_test.go) -- [Rest smoke LCD test](https://github.com/CosmWasm/wasmd/blob/master/lcd_test/wasm_test.go) -## Pull requests -- https://github.com/CosmWasm/wasmd/pull/190 -- https://github.com/CosmWasm/wasmd/pull/186 -- https://github.com/CosmWasm/wasmd/pull/183 -- https://github.com/CosmWasm/wasmd/pull/180 -- https://github.com/CosmWasm/wasmd/pull/179 -- https://github.com/CosmWasm/wasmd/pull/173 +## 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/alias.go b/x/wasm/alias.go index d22a65d..8f952e2 100644 --- a/x/wasm/alias.go +++ b/x/wasm/alias.go @@ -1,8 +1,7 @@ -// nolint // autogenerated code using github.com/rigelrozanski/multitool // aliases generated for the following subdirectories: // ALIASGEN: github.com/Cosmwasm/wasmd/x/wasm/types -// ALIASGEN: github.com/CosmWasm/wasmd/x/wasm/keeper +// ALIASGEN: github.com/terpnetwork/terp-core/x/wasm/keeper package wasm import ( @@ -24,14 +23,6 @@ const ( ProposalTypeMigrateContract = types.ProposalTypeMigrateContract ProposalTypeUpdateAdmin = types.ProposalTypeUpdateAdmin ProposalTypeClearAdmin = types.ProposalTypeClearAdmin - QueryListContractByCode = keeper.QueryListContractByCode - QueryGetContract = keeper.QueryGetContract - QueryGetContractState = keeper.QueryGetContractState - QueryGetCode = keeper.QueryGetCode - QueryListCode = keeper.QueryListCode - QueryMethodContractStateSmart = keeper.QueryMethodContractStateSmart - QueryMethodContractStateAll = keeper.QueryMethodContractStateAll - QueryMethodContractStateRaw = keeper.QueryMethodContractStateRaw ) var ( @@ -66,7 +57,7 @@ var ( WasmQuerier = keeper.WasmQuerier CreateTestInput = keeper.CreateTestInput TestHandler = keeper.TestHandler - NewWasmProposalHandler = keeper.NewWasmProposalHandler + NewWasmProposalHandler = keeper.NewWasmProposalHandler //nolint:staticcheck NewQuerier = keeper.Querier ContractFromPortID = keeper.ContractFromPortID WithWasmEngine = keeper.WithWasmEngine diff --git a/x/wasm/client/cli/gov_tx.go b/x/wasm/client/cli/gov_tx.go deleted file mode 100644 index 30d807a..0000000 --- a/x/wasm/client/cli/gov_tx.go +++ /dev/null @@ -1,841 +0,0 @@ -package cli - -import ( - "bytes" - "crypto/sha256" - "encoding/hex" - "fmt" - "net/url" - "strconv" - "strings" - - "github.com/docker/distribution/reference" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/gov/client/cli" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - "github.com/pkg/errors" - "github.com/spf13/cobra" - flag "github.com/spf13/pflag" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func ProposalStoreCodeCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "wasm-store [wasm file] --title [text] --description [text] --run-as [address] --unpin-code [unpin_code] --source [source] --builder [builder] --code-hash [code_hash]", - Short: "Submit a wasm binary proposal", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - src, err := parseStoreCodeArgs(args[0], clientCtx.FromAddress, cmd.Flags()) - if err != nil { - return err - } - runAs, err := cmd.Flags().GetString(flagRunAs) - if err != nil { - return fmt.Errorf("run-as: %s", err) - } - if len(runAs) == 0 { - return errors.New("run-as address is required") - } - - unpinCode, err := cmd.Flags().GetBool(flagUnpinCode) - if err != nil { - return err - } - - source, builder, codeHash, err := parseVerificationFlags(src.WASMByteCode, cmd.Flags()) - if err != nil { - return err - } - content := types.StoreCodeProposal{ - Title: proposalTitle, - Description: proposalDescr, - RunAs: runAs, - WASMByteCode: src.WASMByteCode, - InstantiatePermission: src.InstantiatePermission, - UnpinCode: unpinCode, - Source: source, - Builder: builder, - CodeHash: codeHash, - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - 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(flagRunAs, "", "The address that is stored as code creator") - 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, "", "Only this address can instantiate a contract instance from the code, optional") - cmd.Flags().Bool(flagUnpinCode, false, "Unpin code on upload, optional") - cmd.Flags().StringSlice(flagInstantiateByAnyOfAddress, []string{}, "Any of the addresses can instantiate a contract from the code, optional") - cmd.Flags().String(flagSource, "", "Code Source URL is a valid absolute HTTPS URI to the contract's source code,") - cmd.Flags().String(flagBuilder, "", "Builder is a valid docker image name with tag, such as \"cosmwasm/workspace-optimizer:0.12.9\"") - cmd.Flags().BytesHex(flagCodeHash, nil, "CodeHash is the sha256 hash of the wasm code") - - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func parseVerificationFlags(wasm []byte, flags *flag.FlagSet) (string, string, []byte, error) { - source, err := flags.GetString(flagSource) - if err != nil { - return "", "", nil, fmt.Errorf("source: %s", err) - } - builder, err := flags.GetString(flagBuilder) - if err != nil { - return "", "", nil, fmt.Errorf("builder: %s", err) - } - codeHash, err := flags.GetBytesHex(flagCodeHash) - if err != nil { - return "", "", nil, fmt.Errorf("codeHash: %s", err) - } - - // if any set require others to be set - if len(source) != 0 || len(builder) != 0 || len(codeHash) != 0 { - if source == "" { - return "", "", nil, fmt.Errorf("source is required") - } - if _, err = url.ParseRequestURI(source); err != nil { - return "", "", nil, fmt.Errorf("source: %s", err) - } - if builder == "" { - return "", "", nil, fmt.Errorf("builder is required") - } - if _, err := reference.ParseDockerRef(builder); err != nil { - return "", "", nil, fmt.Errorf("builder: %s", err) - } - if len(codeHash) == 0 { - return "", "", nil, fmt.Errorf("code hash is required") - } - // wasm is unzipped in parseStoreCodeArgs - // checksum generation will be decoupled here - // reference https://github.com/CosmWasm/wasmvm/issues/359 - checksum := sha256.Sum256(wasm) - if !bytes.Equal(checksum[:], codeHash) { - return "", "", nil, fmt.Errorf("code-hash mismatch: %X, checksum: %X", codeHash, checksum) - } - } - return source, builder, codeHash, nil -} - -func ProposalInstantiateContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "instantiate-contract [code_id_int64] [json_encoded_init_args] --label [text] --title [text] --description [text] --run-as [address] --admin [address,optional] --amount [coins,optional]", - Short: "Submit an instantiate wasm contract proposal", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - src, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.FromAddress, cmd.Flags()) - if err != nil { - return err - } - - runAs, err := cmd.Flags().GetString(flagRunAs) - if err != nil { - return fmt.Errorf("run-as: %s", err) - } - if len(runAs) == 0 { - return errors.New("run-as address is required") - } - - content := types.InstantiateContractProposal{ - Title: proposalTitle, - Description: proposalDescr, - RunAs: runAs, - Admin: src.Admin, - CodeID: src.CodeID, - Label: src.Label, - Msg: src.Msg, - Funds: src.Funds, - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - 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().String(flagRunAs, "", "The address that pays the init funds. It is the creator of the contract and passed to the contract as sender on proposal execution") - cmd.Flags().Bool(flagNoAdmin, false, "You must set this explicitly if you don't want an admin") - - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func ProposalInstantiateContract2Cmd() *cobra.Command { - decoder := newArgDecoder(hex.DecodeString) - cmd := &cobra.Command{ - Use: "instantiate-contract-2 [code_id_int64] [json_encoded_init_args] [salt] --label [text] --title [text] --description [text] --run-as [address] --admin [address,optional] --amount [coins,optional] --fix-msg [bool,optional]", - Short: "Submit an instantiate wasm contract proposal with predictable address", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - src, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.FromAddress, cmd.Flags()) - if err != nil { - return err - } - - runAs, err := cmd.Flags().GetString(flagRunAs) - if err != nil { - return fmt.Errorf("run-as: %s", err) - } - if len(runAs) == 0 { - return errors.New("run-as address is required") - } - - 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) - } - - content := types.NewInstantiateContract2Proposal(proposalTitle, proposalDescr, runAs, src.Admin, src.CodeID, src.Label, src.Msg, src.Funds, salt, fixMsg) - - msg, err := govtypes.NewMsgSubmitProposal(content, deposit, clientCtx.GetFromAddress()) - 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 of an admin") - cmd.Flags().String(flagRunAs, "", "The address that pays the init funds. It is the creator of the contract and passed to the contract as sender on proposal execution") - 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") - - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func ProposalStoreAndInstantiateContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "store-instantiate [wasm file] [json_encoded_init_args] --label [text] --title [text] --description [text] --run-as [address]" + - "--unpin-code [unpin_code,optional] --source [source,optional] --builder [builder,optional] --code-hash [code_hash,optional] --admin [address,optional] --amount [coins,optional]", - Short: "Submit and instantiate a wasm contract proposal", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - src, err := parseStoreCodeArgs(args[0], clientCtx.FromAddress, cmd.Flags()) - if err != nil { - return err - } - runAs, err := cmd.Flags().GetString(flagRunAs) - if err != nil { - return fmt.Errorf("run-as: %s", err) - } - if len(runAs) == 0 { - return errors.New("run-as address is required") - } - - unpinCode, err := cmd.Flags().GetBool(flagUnpinCode) - if err != nil { - return err - } - - source, builder, codeHash, err := parseVerificationFlags(src.WASMByteCode, cmd.Flags()) - if err != nil { - return err - } - - amountStr, err := cmd.Flags().GetString(flagAmount) - if err != nil { - return fmt.Errorf("amount: %s", err) - } - amount, err := sdk.ParseCoinsNormalized(amountStr) - if err != nil { - return fmt.Errorf("amount: %s", err) - } - label, err := cmd.Flags().GetString(flagLabel) - if err != nil { - return fmt.Errorf("label: %s", err) - } - if label == "" { - return errors.New("label is required on all contracts") - } - adminStr, err := cmd.Flags().GetString(flagAdmin) - if err != nil { - return fmt.Errorf("admin: %s", err) - } - noAdmin, err := cmd.Flags().GetBool(flagNoAdmin) - if err != nil { - return fmt.Errorf("no-admin: %s", err) - } - - // ensure sensible admin is set (or explicitly immutable) - if adminStr == "" && !noAdmin { - return fmt.Errorf("you must set an admin or explicitly pass --no-admin to make it immutible (wasmd issue #719)") - } - if adminStr != "" && noAdmin { - return 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 := clientCtx.Keyring.Key(adminStr) - if err != nil { - return fmt.Errorf("admin %s", err) - } - adminStr = info.GetAddress().String() - } else { - adminStr = addr.String() - } - } - - content := types.StoreAndInstantiateContractProposal{ - Title: proposalTitle, - Description: proposalDescr, - RunAs: runAs, - WASMByteCode: src.WASMByteCode, - InstantiatePermission: src.InstantiatePermission, - UnpinCode: unpinCode, - Source: source, - Builder: builder, - CodeHash: codeHash, - Admin: adminStr, - Label: label, - Msg: []byte(args[1]), - Funds: amount, - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - 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(flagRunAs, "", "The address that is stored as code creator. It is the creator of the contract and passed to the contract as sender on proposal execution") - 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, "", "Only this address can instantiate a contract instance from the code, optional") - cmd.Flags().Bool(flagUnpinCode, false, "Unpin code on upload, optional") - cmd.Flags().String(flagSource, "", "Code Source URL is a valid absolute HTTPS URI to the contract's source code,") - cmd.Flags().String(flagBuilder, "", "Builder is a valid docker image name with tag, such as \"cosmwasm/workspace-optimizer:0.12.9\"") - cmd.Flags().BytesHex(flagCodeHash, nil, "CodeHash is the sha256 hash of the wasm code") - cmd.Flags().StringSlice(flagInstantiateByAnyOfAddress, []string{}, "Any of the addresses can instantiate a contract from the code, optional") - 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") - - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func ProposalMigrateContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "migrate-contract [contract_addr_bech32] [new_code_id_int64] [json_encoded_migration_args]", - Short: "Submit a migrate wasm contract to a new code version proposal", - Args: cobra.ExactArgs(3), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - src, err := parseMigrateContractArgs(args, clientCtx) - if err != nil { - return err - } - - content := types.MigrateContractProposal{ - Title: proposalTitle, - Description: proposalDescr, - Contract: src.Contract, - CodeID: src.CodeID, - Msg: src.Msg, - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - if err != nil { - return err - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func ProposalExecuteContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "execute-contract [contract_addr_bech32] [json_encoded_migration_args]", - Short: "Submit a execute wasm contract proposal (run by any address)", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - contract := args[0] - execMsg := []byte(args[1]) - amountStr, err := cmd.Flags().GetString(flagAmount) - if err != nil { - return fmt.Errorf("amount: %s", err) - } - funds, err := sdk.ParseCoinsNormalized(amountStr) - if err != nil { - return fmt.Errorf("amount: %s", err) - } - runAs, err := cmd.Flags().GetString(flagRunAs) - if err != nil { - return fmt.Errorf("run-as: %s", err) - } - - if len(runAs) == 0 { - return errors.New("run-as address is required") - } - - content := types.ExecuteContractProposal{ - Title: proposalTitle, - Description: proposalDescr, - Contract: contract, - Msg: execMsg, - RunAs: runAs, - Funds: funds, - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - 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(flagRunAs, "", "The address that is passed as sender to the contract on proposal execution") - cmd.Flags().String(flagAmount, "", "Coins to send to the contract during instantiation") - - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func ProposalSudoContractCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "sudo-contract [contract_addr_bech32] [json_encoded_migration_args]", - Short: "Submit a sudo wasm contract proposal (to call privileged commands)", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - contract := args[0] - sudoMsg := []byte(args[1]) - - content := types.SudoContractProposal{ - Title: proposalTitle, - Description: proposalDescr, - Contract: contract, - Msg: sudoMsg, - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - if err != nil { - return err - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - - // proposal flagsExecute - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func ProposalUpdateContractAdminCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "set-contract-admin [contract_addr_bech32] [new_admin_addr_bech32]", - Short: "Submit a new admin for a contract proposal", - Args: cobra.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - src, err := parseUpdateContractAdminArgs(args, clientCtx) - if err != nil { - return err - } - - content := types.UpdateAdminProposal{ - Title: proposalTitle, - Description: proposalDescr, - Contract: src.Contract, - NewAdmin: src.NewAdmin, - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - if err != nil { - return err - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func ProposalClearContractAdminCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "clear-contract-admin [contract_addr_bech32]", - Short: "Submit a clear admin for a contract to prevent further migrations proposal", - Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - content := types.ClearAdminProposal{ - Title: proposalTitle, - Description: proposalDescr, - Contract: args[0], - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - if err != nil { - return err - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func ProposalPinCodesCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "pin-codes [code-ids]", - Short: "Submit a pin code proposal for pinning a code to cache", - Args: cobra.MinimumNArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - codeIds, err := parsePinCodesArgs(args) - if err != nil { - return err - } - - content := types.PinCodesProposal{ - Title: proposalTitle, - Description: proposalDescr, - CodeIDs: codeIds, - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - if err != nil { - return err - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func parsePinCodesArgs(args []string) ([]uint64, error) { - codeIDs := make([]uint64, len(args)) - for i, c := range args { - codeID, err := strconv.ParseUint(c, 10, 64) - if err != nil { - return codeIDs, fmt.Errorf("code IDs: %s", err) - } - codeIDs[i] = codeID - } - return codeIDs, nil -} - -func ProposalUnpinCodesCmd() *cobra.Command { - cmd := &cobra.Command{ - Use: "unpin-codes [code-ids]", - Short: "Submit a unpin code proposal for unpinning a code to cache", - Args: cobra.MinimumNArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - - codeIds, err := parsePinCodesArgs(args) - if err != nil { - return err - } - - content := types.UnpinCodesProposal{ - Title: proposalTitle, - Description: proposalDescr, - CodeIDs: codeIds, - } - - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - if err != nil { - return err - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func parseAccessConfig(raw string) (c types.AccessConfig, err error) { - switch raw { - case "nobody": - return types.AllowNobody, nil - case "everybody": - return types.AllowEverybody, nil - default: - parts := strings.Split(raw, ",") - addrs := make([]sdk.AccAddress, len(parts)) - for i, v := range parts { - addr, err := sdk.AccAddressFromBech32(v) - if err != nil { - return types.AccessConfig{}, fmt.Errorf("unable to parse address %q: %s", v, err) - } - addrs[i] = addr - } - defer func() { // convert panic in ".With" to error for better output - if r := recover(); r != nil { - err = r.(error) - } - }() - cfg := types.AccessTypeAnyOfAddresses.With(addrs...) - return cfg, cfg.ValidateBasic() - } -} - -func parseAccessConfigUpdates(args []string) ([]types.AccessConfigUpdate, error) { - updates := make([]types.AccessConfigUpdate, len(args)) - for i, c := range args { - // format: code_id:access_config - // access_config: nobody|everybody|address(es) - parts := strings.Split(c, ":") - if len(parts) != 2 { - return nil, fmt.Errorf("invalid format") - } - - codeID, err := strconv.ParseUint(parts[0], 10, 64) - if err != nil { - return nil, fmt.Errorf("invalid code ID: %s", err) - } - - accessConfig, err := parseAccessConfig(parts[1]) - if err != nil { - return nil, err - } - updates[i] = types.AccessConfigUpdate{ - CodeID: codeID, - InstantiatePermission: accessConfig, - } - } - return updates, nil -} - -func ProposalUpdateInstantiateConfigCmd() *cobra.Command { - bech32Prefix := sdk.GetConfig().GetBech32AccountAddrPrefix() - cmd := &cobra.Command{ - Use: "update-instantiate-config [code-id:permission]...", - Short: "Submit an update instantiate config proposal.", - Args: cobra.MinimumNArgs(1), - Long: strings.TrimSpace( - fmt.Sprintf(`Submit an update instantiate config proposal for multiple code ids. - -Example: -$ %s tx gov submit-proposal update-instantiate-config 1:nobody 2:everybody 3:%s1l2rsakp388kuv9k8qzq6lrm9taddae7fpx59wm,%s1vx8knpllrj7n963p9ttd80w47kpacrhuts497x -`, version.AppName, bech32Prefix, bech32Prefix)), - RunE: func(cmd *cobra.Command, args []string) error { - clientCtx, proposalTitle, proposalDescr, deposit, err := getProposalInfo(cmd) - if err != nil { - return err - } - updates, err := parseAccessConfigUpdates(args) - if err != nil { - return err - } - - content := types.UpdateInstantiateConfigProposal{ - Title: proposalTitle, - Description: proposalDescr, - AccessConfigUpdates: updates, - } - msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) - if err != nil { - return err - } - if err = msg.ValidateBasic(); err != nil { - return err - } - - return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) - }, - SilenceUsage: true, - } - // proposal flags - cmd.Flags().String(cli.FlagTitle, "", "Title of proposal") - cmd.Flags().String(cli.FlagDescription, "", "Description of proposal") - cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") - return cmd -} - -func getProposalInfo(cmd *cobra.Command) (client.Context, string, string, sdk.Coins, error) { - clientCtx, err := client.GetClientTxContext(cmd) - if err != nil { - return client.Context{}, "", "", nil, err - } - - proposalTitle, err := cmd.Flags().GetString(cli.FlagTitle) - if err != nil { - return clientCtx, proposalTitle, "", nil, err - } - - proposalDescr, err := cmd.Flags().GetString(cli.FlagDescription) - if err != nil { - return client.Context{}, proposalTitle, proposalDescr, nil, err - } - - depositArg, err := cmd.Flags().GetString(cli.FlagDeposit) - if err != nil { - return client.Context{}, proposalTitle, proposalDescr, nil, err - } - - deposit, err := sdk.ParseCoinsNormalized(depositArg) - if err != nil { - return client.Context{}, proposalTitle, proposalDescr, deposit, err - } - - return clientCtx, proposalTitle, proposalDescr, deposit, nil -} diff --git a/x/wasm/client/cli/gov_tx_test.go b/x/wasm/client/cli/gov_tx_test.go deleted file mode 100644 index e02d5ac..0000000 --- a/x/wasm/client/cli/gov_tx_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package cli - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestParseAccessConfigUpdates(t *testing.T) { - specs := map[string]struct { - src []string - exp []types.AccessConfigUpdate - expErr bool - }{ - "nobody": { - src: []string{"1:nobody"}, - exp: []types.AccessConfigUpdate{{ - CodeID: 1, - InstantiatePermission: types.AccessConfig{Permission: types.AccessTypeNobody}, - }}, - }, - "everybody": { - src: []string{"1:everybody"}, - exp: []types.AccessConfigUpdate{{ - CodeID: 1, - InstantiatePermission: types.AccessConfig{Permission: types.AccessTypeEverybody}, - }}, - }, - "any of addresses - single": { - src: []string{"1:cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x"}, - exp: []types.AccessConfigUpdate{ - { - CodeID: 1, - InstantiatePermission: types.AccessConfig{ - Permission: types.AccessTypeAnyOfAddresses, - Addresses: []string{"cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x"}, - }, - }, - }, - }, - "any of addresses - multiple": { - src: []string{"1:cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x,cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"}, - exp: []types.AccessConfigUpdate{ - { - CodeID: 1, - InstantiatePermission: types.AccessConfig{ - Permission: types.AccessTypeAnyOfAddresses, - Addresses: []string{"cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x", "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"}, - }, - }, - }, - }, - "multiple code ids with different permissions": { - src: []string{"1:cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x,cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", "2:nobody"}, - exp: []types.AccessConfigUpdate{ - { - CodeID: 1, - InstantiatePermission: types.AccessConfig{ - Permission: types.AccessTypeAnyOfAddresses, - Addresses: []string{"cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x", "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"}, - }, - }, { - CodeID: 2, - InstantiatePermission: types.AccessConfig{ - Permission: types.AccessTypeNobody, - }, - }, - }, - }, - "any of addresses - empty list": { - src: []string{"1:"}, - expErr: true, - }, - "any of addresses - invalid address": { - src: []string{"1:foo"}, - expErr: true, - }, - "any of addresses - duplicate address": { - src: []string{"1:cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x,cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x"}, - expErr: true, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - got, gotErr := parseAccessConfigUpdates(spec.src) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - assert.Equal(t, spec.exp, got) - }) - } -} - -func TestParseCodeInfoFlags(t *testing.T) { - correctSource := "https://github.com/CosmWasm/wasmd/blob/main/x/wasm/keeper/testdata/hackatom.wasm" - correctBuilderRef := "cosmwasm/workspace-optimizer:0.12.9" - - wasmBin, err := os.ReadFile("../../keeper/testdata/hackatom.wasm") - require.NoError(t, err) - - checksumStr := "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5" - - specs := map[string]struct { - args []string - expErr bool - }{ - "source missing": { - args: []string{"--builder=" + correctBuilderRef, "--code-hash=" + checksumStr}, - expErr: true, - }, - "builder missing": { - args: []string{"--code-source-url=" + correctSource, "--code-hash=" + checksumStr}, - expErr: true, - }, - "code hash missing": { - args: []string{"--code-source-url=" + correctSource, "--builder=" + correctBuilderRef}, - expErr: true, - }, - "source format wrong": { - args: []string{"--code-source-url=" + "format_wrong", "--builder=" + correctBuilderRef, "--code-hash=" + checksumStr}, - expErr: true, - }, - "builder format wrong": { - args: []string{"--code-source-url=" + correctSource, "--builder=" + "format//", "--code-hash=" + checksumStr}, - expErr: true, - }, - "code hash wrong": { - args: []string{"--code-source-url=" + correctSource, "--builder=" + correctBuilderRef, "--code-hash=" + "AA"}, - expErr: true, - }, - "happy path, none set": { - args: []string{}, - expErr: false, - }, - "happy path all set": { - args: []string{"--code-source-url=" + correctSource, "--builder=" + correctBuilderRef, "--code-hash=" + checksumStr}, - expErr: false, - }, - } - for name, spec := range specs { - t.Run(name, func(t *testing.T) { - flags := ProposalStoreCodeCmd().Flags() - require.NoError(t, flags.Parse(spec.args)) - _, _, _, gotErr := parseVerificationFlags(wasmBin, flags) - if spec.expErr { - require.Error(t, gotErr) - return - } - require.NoError(t, gotErr) - }) - } -} diff --git a/x/wasm/client/cli/new_tx.go b/x/wasm/client/cli/new_tx.go index 1a7f5ce..8ce605a 100644 --- a/x/wasm/client/cli/new_tx.go +++ b/x/wasm/client/cli/new_tx.go @@ -3,10 +3,10 @@ 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" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/spf13/cobra" "github.com/terpnetwork/terp-core/x/wasm/types" @@ -25,7 +25,7 @@ func MigrateContractCmd() *cobra.Command { return err } - msg, err := parseMigrateContractArgs(args, clientCtx) + msg, err := parseMigrateContractArgs(args, clientCtx.GetFromAddress().String()) if err != nil { return err } @@ -40,17 +40,17 @@ func MigrateContractCmd() *cobra.Command { return cmd } -func parseMigrateContractArgs(args []string, cliCtx client.Context) (types.MsgMigrateContract, error) { +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{}, sdkerrors.Wrap(err, "code id") + return types.MsgMigrateContract{}, errorsmod.Wrap(err, "code id") } migrateMsg := args[2] msg := types.MsgMigrateContract{ - Sender: cliCtx.GetFromAddress().String(), + Sender: sender, Contract: args[0], CodeID: codeID, Msg: []byte(migrateMsg), @@ -71,10 +71,7 @@ func UpdateContractAdminCmd() *cobra.Command { return err } - msg, err := parseUpdateContractAdminArgs(args, clientCtx) - if err != nil { - return err - } + msg := parseUpdateContractAdminArgs(args, clientCtx.GetFromAddress().String()) if err := msg.ValidateBasic(); err != nil { return err } @@ -86,13 +83,13 @@ func UpdateContractAdminCmd() *cobra.Command { return cmd } -func parseUpdateContractAdminArgs(args []string, cliCtx client.Context) (types.MsgUpdateAdmin, error) { +func parseUpdateContractAdminArgs(args []string, sender string) types.MsgUpdateAdmin { msg := types.MsgUpdateAdmin{ - Sender: cliCtx.GetFromAddress().String(), + Sender: sender, Contract: args[0], NewAdmin: args[1], } - return msg, nil + return msg } // ClearContractAdminCmd clears an admin for a contract @@ -122,3 +119,42 @@ func ClearContractAdminCmd() *cobra.Command { 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 index f641079..2971e1e 100644 --- a/x/wasm/client/cli/query.go +++ b/x/wasm/client/cli/query.go @@ -63,6 +63,7 @@ func GetCmdLibVersion() *cobra.Command { fmt.Println(version) return nil }, + SilenceUsage: true, } return cmd } @@ -103,6 +104,7 @@ func GetCmdBuildAddress() *cobra.Command { cmd.Println(keeper.BuildContractAddressPredictable(codeHash, creator, salt, msg).String()) return nil }, + SilenceUsage: true, } decoder.RegisterFlags(cmd.PersistentFlags(), "salt") return cmd @@ -578,6 +580,7 @@ func GetCmdListContractsByCreator() *cobra.Command { SilenceUsage: true, } flags.AddQueryFlagsToCmd(cmd) + flags.AddPaginationFlagsToCmd(cmd, "list contracts by creator") return cmd } diff --git a/x/wasm/client/cli/tx.go b/x/wasm/client/cli/tx.go index b89904c..6131620 100644 --- a/x/wasm/client/cli/tx.go +++ b/x/wasm/client/cli/tx.go @@ -13,7 +13,6 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/crypto/keyring" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/authz" "github.com/spf13/cobra" @@ -66,6 +65,7 @@ func GetTxCmd() *cobra.Command { UpdateContractAdminCmd(), ClearContractAdminCmd(), GrantAuthorizationCmd(), + UpdateInstantiateConfigCmd(), ) return txCmd } @@ -82,7 +82,7 @@ func StoreCodeCmd() *cobra.Command { if err != nil { return err } - msg, err := parseStoreCodeArgs(args[0], clientCtx.GetFromAddress(), cmd.Flags()) + msg, err := parseStoreCodeArgs(args[0], clientCtx.GetFromAddress().String(), cmd.Flags()) if err != nil { return err } @@ -94,15 +94,13 @@ func StoreCodeCmd() *cobra.Command { SilenceUsage: true, } - 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, "", "Deprecated: Only this address can instantiate a contract from the code, optional") - cmd.Flags().StringSlice(flagInstantiateByAnyOfAddress, []string{}, "Any of the addresses can instantiate a contract from the code, optional") + addInstantiatePermissionFlags(cmd) flags.AddTxFlagsToCmd(cmd) return cmd } -func parseStoreCodeArgs(file string, sender sdk.AccAddress, flags *flag.FlagSet) (types.MsgStoreCode, error) { +// 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 @@ -125,7 +123,7 @@ func parseStoreCodeArgs(file string, sender sdk.AccAddress, flags *flag.FlagSet) } msg := types.MsgStoreCode{ - Sender: sender.String(), + Sender: sender, WASMByteCode: wasm, InstantiatePermission: perm, } @@ -154,12 +152,7 @@ func parseAccessConfigFlags(flags *flag.FlagSet) (*types.AccessConfig, error) { return nil, fmt.Errorf("instantiate by address: %s", err) } if onlyAddrStr != "" { - allowedAddr, err := sdk.AccAddressFromBech32(onlyAddrStr) - if err != nil { - return nil, sdkerrors.Wrap(err, flagInstantiateByAddress) - } - x := types.AccessTypeOnlyAddress.With(allowedAddr) - return &x, nil + return nil, fmt.Errorf("not supported anymore. Use: %s", flagInstantiateByAnyOfAddress) } everybodyStr, err := flags.GetString(flagInstantiateByEverybody) if err != nil { @@ -191,6 +184,13 @@ func parseAccessConfigFlags(flags *flag.FlagSet) (*types.AccessConfig, error) { 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{ @@ -209,7 +209,7 @@ $ %s tx wasm instantiate 1 '{"foo":"bar"}' --admin="$(%s keys show mykey -a)" \ if err != nil { return err } - msg, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.GetFromAddress(), cmd.Flags()) + msg, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.GetFromAddress().String(), cmd.Flags()) if err != nil { return err } @@ -260,7 +260,7 @@ $ %s tx wasm instantiate2 1 '{"foo":"bar"}' $(echo -n "testing" | xxd -ps) --adm if err != nil { return fmt.Errorf("fix msg: %w", err) } - data, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.GetFromAddress(), cmd.Flags()) + data, err := parseInstantiateArgs(args[0], args[1], clientCtx.Keyring, clientCtx.GetFromAddress().String(), cmd.Flags()) if err != nil { return err } @@ -292,7 +292,7 @@ $ %s tx wasm instantiate2 1 '{"foo":"bar"}' $(echo -n "testing" | xxd -ps) --adm return cmd } -func parseInstantiateArgs(rawCodeID, initMsg string, kr keyring.Keyring, sender sdk.AccAddress, flags *flag.FlagSet) (*types.MsgInstantiateContract, error) { +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 { @@ -326,7 +326,7 @@ func parseInstantiateArgs(rawCodeID, initMsg string, kr keyring.Keyring, sender // 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 (terpd issue #719)") + 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") @@ -339,7 +339,11 @@ func parseInstantiateArgs(rawCodeID, initMsg string, kr keyring.Keyring, sender if err != nil { return nil, fmt.Errorf("admin %s", err) } - adminStr = info.GetAddress().String() + admin, err := info.GetAddress() + if err != nil { + return nil, err + } + adminStr = admin.String() } else { adminStr = addr.String() } @@ -347,7 +351,7 @@ func parseInstantiateArgs(rawCodeID, initMsg string, kr keyring.Keyring, sender // build and sign the transaction, then broadcast to Tendermint msg := types.MsgInstantiateContract{ - Sender: sender.String(), + Sender: sender, CodeID: codeID, Label: label, Funds: amount, @@ -526,7 +530,12 @@ $ %s tx grant execution --allow-all-messages --ma return fmt.Errorf("%s authorization type not supported", args[1]) } - grantMsg, err := authz.NewMsgGrant(clientCtx.GetFromAddress(), grantee, authorization, time.Unix(0, exp)) + expire, err := getExpireTime(cmd) + if err != nil { + return err + } + + grantMsg, err := authz.NewMsgGrant(clientCtx.GetFromAddress(), grantee, authorization, expire) if err != nil { return err } @@ -543,3 +552,15 @@ $ %s tx grant execution --allow-all-messages --ma 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 index 0585fe7..0521f5e 100644 --- a/x/wasm/client/cli/tx_test.go +++ b/x/wasm/client/cli/tx_test.go @@ -25,7 +25,7 @@ func TestParseAccessConfigFlags(t *testing.T) { }, "only address": { args: []string{"--instantiate-only-address=cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x"}, - expCfg: &types.AccessConfig{Permission: types.AccessTypeOnlyAddress, Address: "cosmos1vx8knpllrj7n963p9ttd80w47kpacrhuts497x"}, + expErr: true, }, "only address - invalid": { args: []string{"--instantiate-only-address=foo"}, diff --git a/x/wasm/client/proposal_handler.go b/x/wasm/client/proposal_handler.go deleted file mode 100644 index 105e416..0000000 --- a/x/wasm/client/proposal_handler.go +++ /dev/null @@ -1,25 +0,0 @@ -package client - -import ( - govclient "github.com/cosmos/cosmos-sdk/x/gov/client" - - "github.com/terpnetwork/terp-core/x/wasm/client/cli" - "github.com/terpnetwork/terp-core/x/wasm/client/rest" //nolint:staticcheck -) - -// ProposalHandlers define the wasm cli proposal types and rest handler. -// Deprecated: the rest package will be removed. You can use the GRPC gateway instead -var ProposalHandlers = []govclient.ProposalHandler{ - govclient.NewProposalHandler(cli.ProposalStoreCodeCmd, rest.StoreCodeProposalHandler), - govclient.NewProposalHandler(cli.ProposalInstantiateContractCmd, rest.InstantiateProposalHandler), - govclient.NewProposalHandler(cli.ProposalMigrateContractCmd, rest.MigrateProposalHandler), - govclient.NewProposalHandler(cli.ProposalExecuteContractCmd, rest.ExecuteProposalHandler), - govclient.NewProposalHandler(cli.ProposalSudoContractCmd, rest.SudoProposalHandler), - govclient.NewProposalHandler(cli.ProposalUpdateContractAdminCmd, rest.UpdateContractAdminProposalHandler), - govclient.NewProposalHandler(cli.ProposalClearContractAdminCmd, rest.ClearContractAdminProposalHandler), - govclient.NewProposalHandler(cli.ProposalPinCodesCmd, rest.PinCodeProposalHandler), - govclient.NewProposalHandler(cli.ProposalUnpinCodesCmd, rest.UnpinCodeProposalHandler), - govclient.NewProposalHandler(cli.ProposalUpdateInstantiateConfigCmd, rest.UpdateInstantiateConfigProposalHandler), - govclient.NewProposalHandler(cli.ProposalStoreAndInstantiateContractCmd, rest.EmptyRestHandler), - govclient.NewProposalHandler(cli.ProposalInstantiateContract2Cmd, rest.EmptyRestHandler), -} diff --git a/x/wasm/client/proposal_handler_test.go b/x/wasm/client/proposal_handler_test.go deleted file mode 100644 index 90d273a..0000000 --- a/x/wasm/client/proposal_handler_test.go +++ /dev/null @@ -1,381 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" - "os" - "testing" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/gorilla/mux" - "github.com/stretchr/testify/require" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" -) - -func TestGovRestHandlers(t *testing.T) { - type dict map[string]interface{} - var ( - anyAddress = "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz" - aBaseReq = dict{ - "from": anyAddress, - "memo": "rest test", - "chain_id": "testing", - "account_number": "1", - "sequence": "1", - "fees": []dict{{"denom": "ustake", "amount": "1000000"}}, - } - ) - encodingConfig := keeper.MakeEncodingConfig(t) - clientCtx := client.Context{}. - WithCodec(encodingConfig.Marshaler). - WithTxConfig(encodingConfig.TxConfig). - WithLegacyAmino(encodingConfig.Amino). - WithInput(os.Stdin). - WithAccountRetriever(authtypes.AccountRetriever{}). - WithBroadcastMode(flags.BroadcastBlock). - WithChainID("testing") - - // router setup as in gov/client/rest/tx.go - propSubRtr := mux.NewRouter().PathPrefix("/gov/proposals").Subrouter() - for _, ph := range ProposalHandlers { - r := ph.RESTHandler(clientCtx) - propSubRtr.HandleFunc(fmt.Sprintf("/%s", r.SubRoute), r.Handler).Methods("POST") - } - - specs := map[string]struct { - srcBody dict - srcPath string - expCode int - }{ - "store-code": { - srcPath: "/gov/proposals/wasm_store_code", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "store-code", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "wasm_byte_code": []byte("valid wasm byte code"), - "source": "https://example.com/", - "builder": "cosmwasm/workspace-optimizer:v0.12.9", - "code_hash": "79F174F09BFE3F83398BF7C147929D5F735161BD46D645E85216BB13BF91D42D", - "instantiate_permission": dict{ - "permission": "OnlyAddress", - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - }, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusOK, - }, - "store-code without verification info": { - srcPath: "/gov/proposals/wasm_store_code", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "store-code", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "wasm_byte_code": []byte("valid wasm byte code"), - "instantiate_permission": dict{ - "permission": "OnlyAddress", - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - }, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusOK, - }, - "store-code without permission": { - srcPath: "/gov/proposals/wasm_store_code", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "store-code", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "wasm_byte_code": []byte("valid wasm byte code"), - "source": "https://example.com/", - "builder": "cosmwasm/workspace-optimizer:v0.12.9", - "code_hash": "79F174F09BFE3F83398BF7C147929D5F735161BD46D645E85216BB13BF91D42D", - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusOK, - }, - "store-code invalid permission": { - srcPath: "/gov/proposals/wasm_store_code", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "store-code", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "wasm_byte_code": []byte("valid wasm byte code"), - "source": "https://example.com/", - "builder": "cosmwasm/workspace-optimizer:v0.12.9", - "code_hash": "79F174F09BFE3F83398BF7C147929D5F735161BD46D645E85216BB13BF91D42D", - "instantiate_permission": dict{ - "permission": "Nobody", - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - }, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusBadRequest, - }, - "store-code with incomplete proposal data: blank title": { - srcPath: "/gov/proposals/wasm_store_code", - srcBody: dict{ - "title": "", - "description": "My proposal", - "type": "store-code", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "wasm_byte_code": []byte("valid wasm byte code"), - "source": "https://example.com/", - "code_hash": "79F174F09BFE3F83398BF7C147929D5F735161BD46D645E85216BB13BF91D42D", - "builder": "cosmwasm/workspace-optimizer:v0.12.9", - "instantiate_permission": dict{ - "permission": "OnlyAddress", - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - }, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusBadRequest, - }, - "store-code with incomplete content data: no wasm_byte_code": { - srcPath: "/gov/proposals/wasm_store_code", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "store-code", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "wasm_byte_code": "", - "builder": "cosmwasm/workspace-optimizer:v0.12.9", - "source": "https://example.com/", - "code_hash": "79F174F09BFE3F83398BF7C147929D5F735161BD46D645E85216BB13BF91D42D", - "instantiate_permission": dict{ - "permission": "OnlyAddress", - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - }, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusBadRequest, - }, - "store-code with incomplete content data: no builder": { - srcPath: "/gov/proposals/wasm_store_code", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "store-code", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "wasm_byte_code": "", - "source": "https://example.com/", - "code_hash": "79F174F09BFE3F83398BF7C147929D5F735161BD46D645E85216BB13BF91D42D", - "instantiate_permission": dict{ - "permission": "OnlyAddress", - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - }, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusBadRequest, - }, - "store-code with incomplete content data: no code hash": { - srcPath: "/gov/proposals/wasm_store_code", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "store-code", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "wasm_byte_code": "", - "builder": "cosmwasm/workspace-optimizer:v0.12.9", - "source": "https://example.com/", - "instantiate_permission": dict{ - "permission": "OnlyAddress", - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - }, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusBadRequest, - }, - "store-code with incomplete content data: no source": { - srcPath: "/gov/proposals/wasm_store_code", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "store-code", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "wasm_byte_code": "", - "builder": "cosmwasm/workspace-optimizer:v0.12.9", - "code_hash": "79F174F09BFE3F83398BF7C147929D5F735161BD46D645E85216BB13BF91D42D", - "instantiate_permission": dict{ - "permission": "OnlyAddress", - "address": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - }, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusBadRequest, - }, - "instantiate contract": { - srcPath: "/gov/proposals/wasm_instantiate", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "instantiate", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "admin": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "code_id": "1", - "label": "https://example.com/", - "msg": dict{"recipient": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz"}, - "funds": []dict{{"denom": "ustake", "amount": "100"}}, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusOK, - }, - "migrate contract": { - srcPath: "/gov/proposals/wasm_migrate", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "migrate", - "contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "code_id": "1", - "msg": dict{"foo": "bar"}, - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusOK, - }, - "execute contract": { - srcPath: "/gov/proposals/wasm_execute", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "migrate", - "contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "msg": dict{"foo": "bar"}, - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusOK, - }, - "execute contract fails with no run_as": { - srcPath: "/gov/proposals/wasm_execute", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "migrate", - "contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "msg": dict{"foo": "bar"}, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusBadRequest, - }, - "execute contract fails with no message": { - srcPath: "/gov/proposals/wasm_execute", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "migrate", - "contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusBadRequest, - }, - "sudo contract": { - srcPath: "/gov/proposals/wasm_sudo", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "migrate", - "contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "msg": dict{"foo": "bar"}, - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusOK, - }, - "sudo contract fails with no message": { - srcPath: "/gov/proposals/wasm_sudo", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "migrate", - "contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusBadRequest, - }, - "update contract admin": { - srcPath: "/gov/proposals/wasm_update_admin", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "migrate", - "contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "new_admin": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz", - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusOK, - }, - "clear contract admin": { - srcPath: "/gov/proposals/wasm_clear_admin", - srcBody: dict{ - "title": "Test Proposal", - "description": "My proposal", - "type": "migrate", - "contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", - "deposit": []dict{{"denom": "ustake", "amount": "10"}}, - "proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np", - "base_req": aBaseReq, - }, - expCode: http.StatusOK, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - src, err := json.Marshal(spec.srcBody) - require.NoError(t, err) - - // when - r := httptest.NewRequest("POST", spec.srcPath, bytes.NewReader(src)) - w := httptest.NewRecorder() - propSubRtr.ServeHTTP(w, r) - - // then - require.Equal(t, spec.expCode, w.Code, w.Body.String()) - }) - } -} diff --git a/x/wasm/client/rest/gov.go b/x/wasm/client/rest/gov.go deleted file mode 100644 index 3d0adc5..0000000 --- a/x/wasm/client/rest/gov.go +++ /dev/null @@ -1,547 +0,0 @@ -package rest - -import ( - "encoding/json" - "net/http" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -type StoreCodeProposalJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - - RunAs string `json:"run_as" yaml:"run_as"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `json:"wasm_byte_code" yaml:"wasm_byte_code"` - // InstantiatePermission to apply on contract creation, optional - InstantiatePermission *types.AccessConfig `json:"instantiate_permission" yaml:"instantiate_permission"` - - // UnpinCode indicates if the code should not be pinned as part of the proposal. - UnpinCode bool `json:"unpin_code" yaml:"unpin_code"` - - // Source is the URL where the code is hosted - Source string `json:"source" yaml:"source"` - // Builder is the docker image used to build the code deterministically, used for smart - // contract verification - Builder string `json:"builder" yaml:"builder"` - // CodeHash is the SHA256 sum of the code outputted by optimizer, used for smart contract verification - CodeHash []byte `json:"code_hash" yaml:"code_hash"` -} - -func (s StoreCodeProposalJSONReq) Content() govtypes.Content { - return &types.StoreCodeProposal{ - Title: s.Title, - Description: s.Description, - RunAs: s.RunAs, - WASMByteCode: s.WASMByteCode, - InstantiatePermission: s.InstantiatePermission, - UnpinCode: s.UnpinCode, - Source: s.Source, - Builder: s.Builder, - CodeHash: s.CodeHash, - } -} - -func (s StoreCodeProposalJSONReq) GetProposer() string { - return s.Proposer -} - -func (s StoreCodeProposalJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s StoreCodeProposalJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func StoreCodeProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "wasm_store_code", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req StoreCodeProposalJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type InstantiateProposalJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - - RunAs string `json:"run_as" yaml:"run_as"` - // Admin is an optional address that can execute migrations - Admin string `json:"admin,omitempty" yaml:"admin"` - Code uint64 `json:"code_id" yaml:"code_id"` - Label string `json:"label" yaml:"label"` - Msg json.RawMessage `json:"msg" yaml:"msg"` - Funds sdk.Coins `json:"funds" yaml:"funds"` -} - -func (s InstantiateProposalJSONReq) Content() govtypes.Content { - return &types.InstantiateContractProposal{ - Title: s.Title, - Description: s.Description, - RunAs: s.RunAs, - Admin: s.Admin, - CodeID: s.Code, - Label: s.Label, - Msg: types.RawContractMessage(s.Msg), - Funds: s.Funds, - } -} - -func (s InstantiateProposalJSONReq) GetProposer() string { - return s.Proposer -} - -func (s InstantiateProposalJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s InstantiateProposalJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func InstantiateProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "wasm_instantiate", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req InstantiateProposalJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type MigrateProposalJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - - Contract string `json:"contract" yaml:"contract"` - Code uint64 `json:"code_id" yaml:"code_id"` - Msg json.RawMessage `json:"msg" yaml:"msg"` -} - -func (s MigrateProposalJSONReq) Content() govtypes.Content { - return &types.MigrateContractProposal{ - Title: s.Title, - Description: s.Description, - Contract: s.Contract, - CodeID: s.Code, - Msg: types.RawContractMessage(s.Msg), - } -} - -func (s MigrateProposalJSONReq) GetProposer() string { - return s.Proposer -} - -func (s MigrateProposalJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s MigrateProposalJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func MigrateProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "wasm_migrate", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req MigrateProposalJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type ExecuteProposalJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - - Contract string `json:"contract" yaml:"contract"` - Msg json.RawMessage `json:"msg" yaml:"msg"` - // RunAs is the role that is passed to the contract's environment - RunAs string `json:"run_as" yaml:"run_as"` - Funds sdk.Coins `json:"funds" yaml:"funds"` -} - -func (s ExecuteProposalJSONReq) Content() govtypes.Content { - return &types.ExecuteContractProposal{ - Title: s.Title, - Description: s.Description, - Contract: s.Contract, - Msg: types.RawContractMessage(s.Msg), - RunAs: s.RunAs, - Funds: s.Funds, - } -} - -func (s ExecuteProposalJSONReq) GetProposer() string { - return s.Proposer -} - -func (s ExecuteProposalJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s ExecuteProposalJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func ExecuteProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "wasm_execute", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req ExecuteProposalJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type SudoProposalJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - - Contract string `json:"contract" yaml:"contract"` - Msg json.RawMessage `json:"msg" yaml:"msg"` -} - -func (s SudoProposalJSONReq) Content() govtypes.Content { - return &types.SudoContractProposal{ - Title: s.Title, - Description: s.Description, - Contract: s.Contract, - Msg: types.RawContractMessage(s.Msg), - } -} - -func (s SudoProposalJSONReq) GetProposer() string { - return s.Proposer -} - -func (s SudoProposalJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s SudoProposalJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func SudoProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "wasm_sudo", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req SudoProposalJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type UpdateAdminJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - - NewAdmin string `json:"new_admin" yaml:"new_admin"` - Contract string `json:"contract" yaml:"contract"` -} - -func (s UpdateAdminJSONReq) Content() govtypes.Content { - return &types.UpdateAdminProposal{ - Title: s.Title, - Description: s.Description, - Contract: s.Contract, - NewAdmin: s.NewAdmin, - } -} - -func (s UpdateAdminJSONReq) GetProposer() string { - return s.Proposer -} - -func (s UpdateAdminJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s UpdateAdminJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func UpdateContractAdminProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "wasm_update_admin", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req UpdateAdminJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type ClearAdminJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - - Contract string `json:"contract" yaml:"contract"` -} - -func (s ClearAdminJSONReq) Content() govtypes.Content { - return &types.ClearAdminProposal{ - Title: s.Title, - Description: s.Description, - Contract: s.Contract, - } -} - -func (s ClearAdminJSONReq) GetProposer() string { - return s.Proposer -} - -func (s ClearAdminJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s ClearAdminJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func ClearContractAdminProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "wasm_clear_admin", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req ClearAdminJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type PinCodeJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - - CodeIDs []uint64 `json:"code_ids" yaml:"code_ids"` -} - -func (s PinCodeJSONReq) Content() govtypes.Content { - return &types.PinCodesProposal{ - Title: s.Title, - Description: s.Description, - CodeIDs: s.CodeIDs, - } -} - -func (s PinCodeJSONReq) GetProposer() string { - return s.Proposer -} - -func (s PinCodeJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s PinCodeJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func PinCodeProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "pin_code", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req PinCodeJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type UnpinCodeJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - - CodeIDs []uint64 `json:"code_ids" yaml:"code_ids"` -} - -func (s UnpinCodeJSONReq) Content() govtypes.Content { - return &types.UnpinCodesProposal{ - Title: s.Title, - Description: s.Description, - CodeIDs: s.CodeIDs, - } -} - -func (s UnpinCodeJSONReq) GetProposer() string { - return s.Proposer -} - -func (s UnpinCodeJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s UnpinCodeJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func UnpinCodeProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "unpin_code", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req UnpinCodeJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type UpdateInstantiateConfigProposalJSONReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` - Proposer string `json:"proposer" yaml:"proposer"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - AccessConfigUpdates []types.AccessConfigUpdate `json:"access_config_updates" yaml:"access_config_updates"` -} - -func (s UpdateInstantiateConfigProposalJSONReq) Content() govtypes.Content { - return &types.UpdateInstantiateConfigProposal{ - Title: s.Title, - Description: s.Description, - AccessConfigUpdates: s.AccessConfigUpdates, - } -} - -func (s UpdateInstantiateConfigProposalJSONReq) GetProposer() string { - return s.Proposer -} - -func (s UpdateInstantiateConfigProposalJSONReq) GetDeposit() sdk.Coins { - return s.Deposit -} - -func (s UpdateInstantiateConfigProposalJSONReq) GetBaseReq() rest.BaseReq { - return s.BaseReq -} - -func UpdateInstantiateConfigProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "update_instantiate_config", - Handler: func(w http.ResponseWriter, r *http.Request) { - var req UpdateInstantiateConfigProposalJSONReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - toStdTxResponse(cliCtx, w, req) - }, - } -} - -type wasmProposalData interface { - Content() govtypes.Content - GetProposer() string - GetDeposit() sdk.Coins - GetBaseReq() rest.BaseReq -} - -func toStdTxResponse(cliCtx client.Context, w http.ResponseWriter, data wasmProposalData) { - proposerAddr, err := sdk.AccAddressFromBech32(data.GetProposer()) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - msg, err := govtypes.NewMsgSubmitProposal(data.Content(), data.GetDeposit(), proposerAddr) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - baseReq := data.GetBaseReq().Sanitize() - if !baseReq.ValidateBasic(w) { - return - } - tx.WriteGeneratedTxResponse(cliCtx, w, baseReq, msg) -} - -func EmptyRestHandler(cliCtx client.Context) govrest.ProposalRESTHandler { - return govrest.ProposalRESTHandler{ - SubRoute: "unsupported", - Handler: func(w http.ResponseWriter, r *http.Request) { - rest.WriteErrorResponse(w, http.StatusBadRequest, "Legacy REST Routes are not supported for gov proposals") - }, - } -} diff --git a/x/wasm/client/rest/new_tx.go b/x/wasm/client/rest/new_tx.go deleted file mode 100644 index 52fcb00..0000000 --- a/x/wasm/client/rest/new_tx.go +++ /dev/null @@ -1,86 +0,0 @@ -package rest - -import ( - "net/http" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/gorilla/mux" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func registerNewTxRoutes(cliCtx client.Context, r *mux.Router) { - r.HandleFunc("/wasm/contract/{contractAddr}/admin", setContractAdminHandlerFn(cliCtx)).Methods("PUT") - r.HandleFunc("/wasm/contract/{contractAddr}/code", migrateContractHandlerFn(cliCtx)).Methods("PUT") -} - -type migrateContractReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - Admin string `json:"admin,omitempty" yaml:"admin"` - CodeID uint64 `json:"code_id" yaml:"code_id"` - Msg []byte `json:"msg,omitempty" yaml:"msg"` -} - -type updateContractAdministrateReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - Admin string `json:"admin,omitempty" yaml:"admin"` -} - -func setContractAdminHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req updateContractAdministrateReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - vars := mux.Vars(r) - contractAddr := vars["contractAddr"] - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - msg := &types.MsgUpdateAdmin{ - Sender: req.BaseReq.From, - NewAdmin: req.Admin, - Contract: contractAddr, - } - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) - } -} - -func migrateContractHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req migrateContractReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - vars := mux.Vars(r) - contractAddr := vars["contractAddr"] - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - msg := &types.MsgMigrateContract{ - Sender: req.BaseReq.From, - Contract: contractAddr, - CodeID: req.CodeID, - Msg: req.Msg, - } - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) - } -} diff --git a/x/wasm/client/rest/query.go b/x/wasm/client/rest/query.go deleted file mode 100644 index 7ae5705..0000000 --- a/x/wasm/client/rest/query.go +++ /dev/null @@ -1,270 +0,0 @@ -package rest - -import ( - "encoding/base64" - "encoding/hex" - "encoding/json" - "fmt" - "net/http" - "strconv" - - "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/gorilla/mux" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func registerQueryRoutes(cliCtx client.Context, r *mux.Router) { - r.HandleFunc("/wasm/code", listCodesHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/wasm/code/{codeID}", queryCodeHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/wasm/code/{codeID}/contracts", listContractsByCodeHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/wasm/contract/{contractAddr}", queryContractHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/wasm/contract/{contractAddr}/state", queryContractStateAllHandlerFn(cliCtx)).Methods("GET") - r.HandleFunc("/wasm/contract/{contractAddr}/history", queryContractHistoryFn(cliCtx)).Methods("GET") - r.HandleFunc("/wasm/contract/{contractAddr}/smart/{query}", queryContractStateSmartHandlerFn(cliCtx)).Queries("encoding", "{encoding}").Methods("GET") - r.HandleFunc("/wasm/contract/{contractAddr}/raw/{key}", queryContractStateRawHandlerFn(cliCtx)).Queries("encoding", "{encoding}").Methods("GET") -} - -func listCodesHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, keeper.QueryListCode) - res, height, err := cliCtx.Query(route) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, json.RawMessage(res)) - } -} - -func queryCodeHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - codeID, err := strconv.ParseUint(mux.Vars(r)["codeID"], 10, 64) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - route := fmt.Sprintf("custom/%s/%s/%d", types.QuerierRoute, keeper.QueryGetCode, codeID) - res, height, err := cliCtx.Query(route) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - if len(res) == 0 { - rest.WriteErrorResponse(w, http.StatusNotFound, "contract not found") - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, json.RawMessage(res)) - } -} - -func listContractsByCodeHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - codeID, err := strconv.ParseUint(mux.Vars(r)["codeID"], 10, 64) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - route := fmt.Sprintf("custom/%s/%s/%d", types.QuerierRoute, keeper.QueryListContractByCode, codeID) - res, height, err := cliCtx.Query(route) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, json.RawMessage(res)) - } -} - -func queryContractHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContract, addr.String()) - res, height, err := cliCtx.Query(route) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, json.RawMessage(res)) - } -} - -func queryContractStateAllHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateAll) - res, height, err := cliCtx.Query(route) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - // parse res - var resultData []types.Model - err = json.Unmarshal(res, &resultData) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, resultData) - } -} - -func queryContractStateRawHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - decoder := newArgDecoder(hex.DecodeString) - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - decoder.encoding = mux.Vars(r)["encoding"] - queryData, err := decoder.DecodeString(mux.Vars(r)["key"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateRaw) - res, height, err := cliCtx.QueryWithData(route, queryData) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - cliCtx = cliCtx.WithHeight(height) - // ensure this is base64 encoded - encoded := base64.StdEncoding.EncodeToString(res) - rest.PostProcessResponse(w, cliCtx, encoded) - } -} - -type smartResponse struct { - Smart []byte `json:"smart"` -} - -func queryContractStateSmartHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - decoder := newArgDecoder(hex.DecodeString) - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - decoder.encoding = mux.Vars(r)["encoding"] - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateSmart) - - queryData, err := decoder.DecodeString(mux.Vars(r)["query"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - res, height, err := cliCtx.QueryWithData(route, queryData) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - // return as raw bytes (to be base64-encoded) - responseData := smartResponse{Smart: res} - - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, responseData) - } -} - -func queryContractHistoryFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) - if !ok { - return - } - - route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryContractHistory, addr.String()) - res, height, err := cliCtx.Query(route) - if err != nil { - rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error()) - return - } - cliCtx = cliCtx.WithHeight(height) - rest.PostProcessResponse(w, cliCtx, json.RawMessage(res)) - } -} - -type argumentDecoder struct { - // dec is the default decoder - dec func(string) ([]byte, error) - encoding string -} - -func newArgDecoder(def func(string) ([]byte, error)) *argumentDecoder { - return &argumentDecoder{dec: def} -} - -func (a *argumentDecoder) DecodeString(s string) ([]byte, error) { - switch a.encoding { - case "hex": - return hex.DecodeString(s) - case "base64": - return base64.StdEncoding.DecodeString(s) - default: - return a.dec(s) - } -} diff --git a/x/wasm/client/rest/rest.go b/x/wasm/client/rest/rest.go deleted file mode 100644 index 95339d3..0000000 --- a/x/wasm/client/rest/rest.go +++ /dev/null @@ -1,15 +0,0 @@ -// Deprecated: the rest package will be removed. You can use the GRPC gateway instead -package rest - -import ( - "github.com/cosmos/cosmos-sdk/client" - "github.com/gorilla/mux" -) - -// RegisterRoutes registers staking-related REST handlers to a router -// Deprecated: the rest package will be removed. You can use the GRPC gateway instead -func RegisterRoutes(cliCtx client.Context, r *mux.Router) { - registerQueryRoutes(cliCtx, r) - registerTxRoutes(cliCtx, r) - registerNewTxRoutes(cliCtx, r) -} diff --git a/x/wasm/client/rest/tx.go b/x/wasm/client/rest/tx.go deleted file mode 100644 index cda2653..0000000 --- a/x/wasm/client/rest/tx.go +++ /dev/null @@ -1,149 +0,0 @@ -package rest - -import ( - "net/http" - "strconv" - - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/gorilla/mux" - - "github.com/terpnetwork/terp-core/x/wasm/ioutils" - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func registerTxRoutes(cliCtx client.Context, r *mux.Router) { - r.HandleFunc("/wasm/code", storeCodeHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc("/wasm/code/{codeId}", instantiateContractHandlerFn(cliCtx)).Methods("POST") - r.HandleFunc("/wasm/contract/{contractAddr}", executeContractHandlerFn(cliCtx)).Methods("POST") -} - -type storeCodeReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - WasmBytes []byte `json:"wasm_bytes"` -} - -type instantiateContractReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - Label string `json:"label" yaml:"label"` - Deposit sdk.Coins `json:"deposit" yaml:"deposit"` - Admin string `json:"admin,omitempty" yaml:"admin"` - Msg []byte `json:"msg" yaml:"msg"` -} - -type executeContractReq struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - ExecMsg []byte `json:"exec_msg" yaml:"exec_msg"` - Amount sdk.Coins `json:"coins" yaml:"coins"` -} - -func storeCodeHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req storeCodeReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - var err error - wasm := req.WasmBytes - - // gzip the wasm file - if ioutils.IsWasm(wasm) { - wasm, err = ioutils.GzipIt(wasm) - if err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - } else if !ioutils.IsGzip(wasm) { - rest.WriteErrorResponse(w, http.StatusBadRequest, "Invalid input file, use wasm binary or zip") - return - } - - // build and sign the transaction, then broadcast to Tendermint - msg := types.MsgStoreCode{ - Sender: req.BaseReq.From, - WASMByteCode: wasm, - } - - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, &msg) - } -} - -func instantiateContractHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req instantiateContractReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - vars := mux.Vars(r) - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - // get the id of the code to instantiate - codeID, err := strconv.ParseUint(vars["codeId"], 10, 64) - if err != nil { - return - } - - msg := types.MsgInstantiateContract{ - Sender: req.BaseReq.From, - CodeID: codeID, - Label: req.Label, - Funds: req.Deposit, - Msg: req.Msg, - Admin: req.Admin, - } - - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, &msg) - } -} - -func executeContractHandlerFn(cliCtx client.Context) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var req executeContractReq - if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { - return - } - vars := mux.Vars(r) - contractAddr := vars["contractAddr"] - - req.BaseReq = req.BaseReq.Sanitize() - if !req.BaseReq.ValidateBasic(w) { - return - } - - msg := types.MsgExecuteContract{ - Sender: req.BaseReq.From, - Contract: contractAddr, - Msg: req.ExecMsg, - Funds: req.Amount, - } - - if err := msg.ValidateBasic(); err != nil { - rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) - return - } - - tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, &msg) - } -} diff --git a/x/wasm/common_test.go b/x/wasm/common_test.go index ce232a5..c2e1100 100644 --- a/x/wasm/common_test.go +++ b/x/wasm/common_test.go @@ -9,6 +9,7 @@ import ( // ensure store code returns the expected response func assertStoreCodeResponse(t *testing.T, data []byte, expected uint64) { + t.Helper() var pStoreResp MsgStoreCodeResponse require.NoError(t, pStoreResp.Unmarshal(data)) require.Equal(t, pStoreResp.CodeID, expected) @@ -16,6 +17,7 @@ func assertStoreCodeResponse(t *testing.T, data []byte, expected uint64) { // ensure execution returns the expected data func assertExecuteResponse(t *testing.T, data []byte, expected []byte) { + t.Helper() var pExecResp MsgExecuteContractResponse require.NoError(t, pExecResp.Unmarshal(data)) require.Equal(t, pExecResp.Data, expected) @@ -23,6 +25,7 @@ func assertExecuteResponse(t *testing.T, data []byte, expected []byte) { // 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) diff --git a/x/wasm/exported/exported.go b/x/wasm/exported/exported.go new file mode 100644 index 0000000..000114e --- /dev/null +++ b/x/wasm/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/wasm/genesis_test.go b/x/wasm/genesis_test.go index 9d968f8..d6050ba 100644 --- a/x/wasm/genesis_test.go +++ b/x/wasm/genesis_test.go @@ -9,6 +9,7 @@ import ( ) func TestInitGenesis(t *testing.T) { + t.Helper() data := setupTest(t) deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) @@ -16,13 +17,13 @@ func TestInitGenesis(t *testing.T) { creator := data.faucet.NewFundedRandomAccount(data.ctx, deposit.Add(deposit...)...) fred := data.faucet.NewFundedRandomAccount(data.ctx, topUp...) - h := data.module.Route().Handler() - q := data.module.LegacyQuerierHandler(nil) - msg := MsgStoreCode{ Sender: creator.String(), WASMByteCode: testContract, } + h := data.msgServiceRouter.Handler(&msg) + q := data.grpcQueryRouter + err := msg.ValidateBasic() require.NoError(t, err) @@ -30,7 +31,7 @@ func TestInitGenesis(t *testing.T) { require.NoError(t, err) assertStoreCodeResponse(t, res.Data, 1) - _, _, bob := keyPubAddr() + bob := keyPubAddr() initMsg := initMsg{ Verifier: fred, Beneficiary: bob, @@ -38,59 +39,62 @@ func TestInitGenesis(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - initCmd := MsgInstantiateContract{ + instMsg := MsgInstantiateContract{ Sender: creator.String(), CodeID: firstCodeID, Msg: initMsgBz, Funds: deposit, Label: "testing", } - res, err = h(data.ctx, &initCmd) + h = data.msgServiceRouter.Handler(&instMsg) + res, err = h(data.ctx, &instMsg) require.NoError(t, err) contractBech32Addr := parseInitResponse(t, res.Data) - execCmd := MsgExecuteContract{ + execMsg := MsgExecuteContract{ Sender: fred.String(), Contract: contractBech32Addr, Msg: []byte(`{"release":{}}`), Funds: topUp, } - res, err = h(data.ctx, &execCmd) + 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) - assertCodeBytes(t, q, data.ctx, 1, testContract) + 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}) - assertContractInfo(t, q, data.ctx, contractBech32Addr, 1, creator) + 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.module.LegacyQuerierHandler(nil) + q2 := newData.grpcQueryRouter // initialize new app with genstate - InitGenesis(newData.ctx, &newData.keeper, *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) - assertCodeBytes(t, q2, newData.ctx, 1, testContract) + 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}) - assertContractInfo(t, q2, newData.ctx, contractBech32Addr, 1, creator) + 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/handler.go b/x/wasm/handler.go deleted file mode 100644 index 8f7a862..0000000 --- a/x/wasm/handler.go +++ /dev/null @@ -1,75 +0,0 @@ -package wasm - -import ( - "fmt" - - "github.com/gogo/protobuf/proto" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" - "github.com/terpnetwork/terp-core/x/wasm/types" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" -) - -// NewHandler returns a handler for "wasm" type messages. -func NewHandler(k types.ContractOpsKeeper) sdk.Handler { - msgServer := keeper.NewMsgServerImpl(k) - - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - ctx = ctx.WithEventManager(sdk.NewEventManager()) - - var ( - res proto.Message - err error - ) - switch msg := msg.(type) { - case *MsgStoreCode: //nolint:typecheck - res, err = msgServer.StoreCode(sdk.WrapSDKContext(ctx), msg) - case *MsgInstantiateContract: - res, err = msgServer.InstantiateContract(sdk.WrapSDKContext(ctx), msg) - case *MsgInstantiateContract2: - res, err = msgServer.InstantiateContract2(sdk.WrapSDKContext(ctx), msg) - case *MsgExecuteContract: - res, err = msgServer.ExecuteContract(sdk.WrapSDKContext(ctx), msg) - case *MsgMigrateContract: - res, err = msgServer.MigrateContract(sdk.WrapSDKContext(ctx), msg) - case *MsgUpdateAdmin: - res, err = msgServer.UpdateAdmin(sdk.WrapSDKContext(ctx), msg) - case *MsgClearAdmin: - res, err = msgServer.ClearAdmin(sdk.WrapSDKContext(ctx), msg) - default: - errMsg := fmt.Sprintf("unrecognized wasm message type: %T", msg) - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) - } - - ctx = ctx.WithEventManager(filterMessageEvents(ctx)) - return sdk.WrapServiceResult(ctx, res, err) - } -} - -// filterMessageEvents returns the same events with all of type == EventTypeMessage removed except -// for wasm message types. -// this is so only our top-level message event comes through -func filterMessageEvents(ctx sdk.Context) *sdk.EventManager { - m := sdk.NewEventManager() - for _, e := range ctx.EventManager().Events() { - if e.Type == sdk.EventTypeMessage && - !hasWasmModuleAttribute(e.Attributes) { - continue - } - m.EmitEvent(e) - } - return m -} - -func hasWasmModuleAttribute(attrs []abci.EventAttribute) bool { - for _, a := range attrs { - if sdk.AttributeKeyModule == string(a.Key) && - types.ModuleName == string(a.Value) { - return true - } - } - return false -} diff --git a/x/wasm/ibc.go b/x/wasm/ibc.go index 017abc6..cf06e64 100644 --- a/x/wasm/ibc.go +++ b/x/wasm/ibc.go @@ -3,14 +3,14 @@ package wasm import ( "math" + errorsmod "cosmossdk.io/errors" wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - porttypes "github.com/cosmos/ibc-go/v4/modules/core/05-port/types" - host "github.com/cosmos/ibc-go/v4/modules/core/24-host" - ibcexported "github.com/cosmos/ibc-go/v4/modules/core/exported" + 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" ) @@ -50,7 +50,7 @@ func (i IBCHandler) OnChanOpenInit( } contractAddr, err := ContractFromPortID(portID) if err != nil { - return "", sdkerrors.Wrapf(err, "contract port id") + return "", errorsmod.Wrapf(err, "contract port id") } msg := wasmvmtypes.IBCChannelOpenMsg{ @@ -71,13 +71,13 @@ func (i IBCHandler) OnChanOpenInit( if err != nil { return "", err } - if acceptedVersion == "" { + 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 "", sdkerrors.Wrap(err, "claim capability") + return "", errorsmod.Wrap(err, "claim capability") } return acceptedVersion, nil } @@ -99,7 +99,7 @@ func (i IBCHandler) OnChanOpenTry( contractAddr, err := ContractFromPortID(portID) if err != nil { - return "", sdkerrors.Wrapf(err, "contract port id") + return "", errorsmod.Wrapf(err, "contract port id") } msg := wasmvmtypes.IBCChannelOpenMsg{ @@ -131,7 +131,7 @@ func (i IBCHandler) OnChanOpenTry( 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 "", sdkerrors.Wrap(err, "claim capability") + return "", errorsmod.Wrap(err, "claim capability") } } @@ -147,23 +147,17 @@ func (i IBCHandler) OnChanOpenAck( ) error { contractAddr, err := ContractFromPortID(portID) if err != nil { - return sdkerrors.Wrapf(err, "contract port id") + return errorsmod.Wrapf(err, "contract port id") } channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) if !ok { - return sdkerrors.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) + return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) } channelInfo.Counterparty.ChannelId = counterpartyChannelID - // This is a bit ugly, but it is set AFTER the callback is done, yet we want to provide the contract - // access to the channel in queries. We can revisit how to better integrate with ibc-go in the future, - // but this is the best/safest we can do now. (If you remove this, you error when sending a packet during the - // OnChanOpenAck entry point) - // https://github.com/cosmos/ibc-go/pull/647/files#diff-54b5be375a2333c56f2ae1b5b4dc13ac9c734561e30286505f39837ee75762c7R25 - i.channelKeeper.SetChannel(ctx, portID, channelID, channelInfo) appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) if !ok { - return sdkerrors.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) + return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) } msg := wasmvmtypes.IBCChannelConnectMsg{ @@ -179,15 +173,15 @@ func (i IBCHandler) OnChanOpenAck( func (i IBCHandler) OnChanOpenConfirm(ctx sdk.Context, portID, channelID string) error { contractAddr, err := ContractFromPortID(portID) if err != nil { - return sdkerrors.Wrapf(err, "contract port id") + return errorsmod.Wrapf(err, "contract port id") } channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) if !ok { - return sdkerrors.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) + return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) } appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) if !ok { - return sdkerrors.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) + return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) } msg := wasmvmtypes.IBCChannelConnectMsg{ OpenConfirm: &wasmvmtypes.IBCOpenConfirm{ @@ -201,15 +195,15 @@ func (i IBCHandler) OnChanOpenConfirm(ctx sdk.Context, portID, channelID string) func (i IBCHandler) OnChanCloseInit(ctx sdk.Context, portID, channelID string) error { contractAddr, err := ContractFromPortID(portID) if err != nil { - return sdkerrors.Wrapf(err, "contract port id") + return errorsmod.Wrapf(err, "contract port id") } channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) if !ok { - return sdkerrors.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) + return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) } appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) if !ok { - return sdkerrors.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) + return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) } msg := wasmvmtypes.IBCChannelCloseMsg{ @@ -229,15 +223,15 @@ func (i IBCHandler) OnChanCloseConfirm(ctx sdk.Context, portID, channelID string // counterparty has closed the channel contractAddr, err := ContractFromPortID(portID) if err != nil { - return sdkerrors.Wrapf(err, "contract port id") + return errorsmod.Wrapf(err, "contract port id") } channelInfo, ok := i.channelKeeper.GetChannel(ctx, portID, channelID) if !ok { - return sdkerrors.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) + return errorsmod.Wrapf(channeltypes.ErrChannelNotFound, "port ID (%s) channel ID (%s)", portID, channelID) } appVersion, ok := i.appVersionGetter.GetAppVersion(ctx, portID, channelID) if !ok { - return sdkerrors.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) + return errorsmod.Wrapf(channeltypes.ErrInvalidChannelVersion, "port ID (%s) channel ID (%s)", portID, channelID) } msg := wasmvmtypes.IBCChannelCloseMsg{ @@ -270,7 +264,7 @@ func (i IBCHandler) OnRecvPacket( ) ibcexported.Acknowledgement { contractAddr, err := ContractFromPortID(packet.DestinationPort) if err != nil { - return channeltypes.NewErrorAcknowledgement(sdkerrors.Wrapf(err, "contract port id")) + 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) @@ -301,7 +295,7 @@ func (i IBCHandler) OnAcknowledgementPacket( ) error { contractAddr, err := ContractFromPortID(packet.SourcePort) if err != nil { - return sdkerrors.Wrapf(err, "contract port id") + return errorsmod.Wrapf(err, "contract port id") } err = i.keeper.OnAckPacket(ctx, contractAddr, wasmvmtypes.IBCPacketAckMsg{ @@ -310,7 +304,7 @@ func (i IBCHandler) OnAcknowledgementPacket( Relayer: relayer.String(), }) if err != nil { - return sdkerrors.Wrap(err, "on ack") + return errorsmod.Wrap(err, "on ack") } return nil } @@ -319,12 +313,12 @@ func (i IBCHandler) OnAcknowledgementPacket( func (i IBCHandler) OnTimeoutPacket(ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) error { contractAddr, err := ContractFromPortID(packet.SourcePort) if err != nil { - return sdkerrors.Wrapf(err, "contract port id") + 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 sdkerrors.Wrap(err, "on timeout") + return errorsmod.Wrap(err, "on timeout") } return nil } @@ -357,7 +351,7 @@ func ValidateChannelParams(channelID string) error { return err } if channelSequence > math.MaxUint32 { - return sdkerrors.Wrapf(types.ErrMaxIBCChannels, "channel sequence %d is greater than max allowed transfer channels %d", 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 index f118edc..286d7bc 100644 --- a/x/wasm/ibc_integration_test.go +++ b/x/wasm/ibc_integration_test.go @@ -5,9 +5,9 @@ import ( wasmvm "github.com/CosmWasm/wasmvm" wasmvmtypes "github.com/CosmWasm/wasmvm/types" - ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v4/testing" + 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" @@ -47,10 +47,10 @@ func TestOnChanOpenInitVersion(t *testing.T) { wasmtesting.NewIBCContractMockWasmer(myContract)), } coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) myContractAddr = chainA.SeedNewContractInstance() - contractInfo = chainA.App.WasmKeeper.GetContractInfo(chainA.GetContext(), myContractAddr) + contractInfo = chainA.App.WasmKeeper.GetContractInfo(chainA.App.NewUncachedContext(false, chainA.CurrentHeader), myContractAddr) ) path := wasmibctesting.NewPath(chainA, chainB) @@ -98,8 +98,8 @@ func TestOnChanOpenTryVersion(t *testing.T) { wasmtesting.NewIBCContractMockWasmer(myContract)), } coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) myContractAddr = chainA.SeedNewContractInstance() contractInfo = chainA.ContractInfo(myContractAddr) ) diff --git a/x/wasm/ibc_reflect_test.go b/x/wasm/ibc_reflect_test.go index dda50a9..7d4e41d 100644 --- a/x/wasm/ibc_reflect_test.go +++ b/x/wasm/ibc_reflect_test.go @@ -5,8 +5,8 @@ import ( "github.com/stretchr/testify/assert" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v4/testing" + 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" @@ -25,8 +25,8 @@ func TestIBCReflectContract(t *testing.T) { var ( coordinator = wasmibctesting.NewCoordinator(t, 2) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) ) coordinator.CommitBlock(chainA, chainB) diff --git a/x/wasm/ibc_test.go b/x/wasm/ibc_test.go index ee63c7f..a92d451 100644 --- a/x/wasm/ibc_test.go +++ b/x/wasm/ibc_test.go @@ -4,8 +4,8 @@ import ( "testing" wasmvmtypes "github.com/CosmWasm/wasmvm/types" - clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/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" ) diff --git a/x/wasm/ibctesting/chain.go b/x/wasm/ibctesting/chain.go index abeb352..7297e2c 100644 --- a/x/wasm/ibctesting/chain.go +++ b/x/wasm/ibctesting/chain.go @@ -5,38 +5,40 @@ import ( "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" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" 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/teststaking" + "github.com/cosmos/cosmos-sdk/x/staking/testutil" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - commitmenttypes "github.com/cosmos/ibc-go/v4/modules/core/23-commitment/types" - host "github.com/cosmos/ibc-go/v4/modules/core/24-host" - "github.com/cosmos/ibc-go/v4/modules/core/exported" - "github.com/cosmos/ibc-go/v4/modules/core/types" - ibctmtypes "github.com/cosmos/ibc-go/v4/modules/light-clients/07-tendermint/types" - ibctesting "github.com/cosmos/ibc-go/v4/testing" - "github.com/cosmos/ibc-go/v4/testing/mock" + 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" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto/tmhash" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - tmprotoversion "github.com/tendermint/tendermint/proto/tendermint/version" - tmtypes "github.com/tendermint/tendermint/types" - tmversion "github.com/tendermint/tendermint/version" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/app/params" - "github.com/terpnetwork/terp-core/x/wasm" ) var MaxAccounts = 10 @@ -57,8 +59,8 @@ type TestChain struct { Coordinator *Coordinator App *app.TerpApp ChainID string - LastHeader *ibctmtypes.Header // header for last block height committed - CurrentHeader tmproto.Header // header for current block height + 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 @@ -89,6 +91,7 @@ type PacketAck struct { // 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 { + t.Helper() // generate validators private/public key var ( validatorsPerChain = 4 @@ -128,6 +131,7 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string, opts ...wasm // 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 { + t.Helper() genAccs := []authtypes.GenesisAccount{} genBals := []banktypes.Balance{} senderAccs := []SenderAccount{} @@ -165,7 +169,7 @@ func NewTestChainWithValSet(t *testing.T, coord *Coordinator, chainID string, va Time: coord.CurrentTime.UTC(), } - txConfig := params.MakeEncodingConfig().TxConfig + txConfig := wasmApp.TxConfig() // create an account to send transactions from chain := &TestChain{ @@ -202,10 +206,17 @@ func (chain *TestChain) QueryProof(key []byte) ([]byte, clienttypes.Height) { } // 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. +// 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", host.StoreKey), + Path: fmt.Sprintf("store/%s/key", storeKey), Height: height - 1, Data: key, Prove: true, @@ -291,6 +302,7 @@ func (chain *TestChain) NextBlock() { Time: chain.CurrentHeader.Time, ValidatorsHash: chain.Vals.Hash(), NextValidatorsHash: chain.NextVals.Hash(), + ProposerAddress: chain.CurrentHeader.ProposerAddress, } chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader}) @@ -309,7 +321,7 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { // ensure the chain has the latest time chain.Coordinator.UpdateTimeForChain(chain) - _, r, err := app.SignAndDeliver( + _, r, err := app.SignAndDeliverWithoutCommit( chain.t, chain.TxConfig, chain.App.BaseApp, @@ -320,12 +332,12 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { []uint64{chain.SenderAccount.GetSequence()}, chain.SenderPrivKey, ) + if err != nil { + return nil, err + } // NextBlock calls app.Commit() chain.NextBlock() - if err != nil { - return r, err - } // increment sequence for successful transaction execution err = chain.SenderAccount.SetSequence(chain.SenderAccount.GetSequence() + 1) @@ -335,12 +347,12 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { chain.Coordinator.IncrementTime() - chain.captureIBCEvents(r) + chain.CaptureIBCEvents(r) return r, nil } -func (chain *TestChain) captureIBCEvents(r *sdk.Result) { +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 @@ -373,7 +385,7 @@ func (chain *TestChain) GetValsAtHeight(height int64) (*tmtypes.ValidatorSet, bo valSet := stakingtypes.Validators(histInfo.Valset) - tmValidators, err := teststaking.ToTmValidators(valSet, sdk.DefaultPowerReduction) + tmValidators, err := testutil.ToTmValidators(valSet, sdk.DefaultPowerReduction) if err != nil { panic(err) } @@ -396,13 +408,13 @@ func (chain *TestChain) GetPrefix() commitmenttypes.MerklePrefix { // 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) (*ibctmtypes.Header, error) { +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) (*ibctmtypes.Header, error) { +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() { @@ -424,7 +436,7 @@ func (chain *TestChain) ConstructUpdateTMClientHeaderWithTrustedHeight(counterpa // NextValidatorsHash tmTrustedVals, ok = counterparty.GetValsAtHeight(int64(trustedHeight.RevisionHeight + 1)) if !ok { - return nil, sdkerrors.Wrapf(ibctmtypes.ErrInvalidHeaderHeight, "could not retrieve trusted validators at trustedHeight: %d", trustedHeight) + return nil, errorsmod.Wrapf(ibctm.ErrInvalidHeaderHeight, "could not retrieve trusted validators at trustedHeight: %d", trustedHeight) } } // inject trusted fields into last header @@ -448,13 +460,13 @@ func (chain *TestChain) ExpireClient(amount time.Duration) { // 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() *ibctmtypes.Header { +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) *ibctmtypes.Header { +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 @@ -478,18 +490,17 @@ func (chain *TestChain) CreateTMClientHeader(chainID string, blockHeight int64, AppHash: chain.CurrentHeader.AppHash, LastResultsHash: tmhash.Sum([]byte("last_results_hash")), EvidenceHash: tmhash.Sum([]byte("evidence_hash")), - ProposerAddress: tmValSet.Proposer.Address, //nolint:staticcheck + 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)) - for i, v := range tmValSet.Validators { + signerArr := make([]tmtypes.PrivValidator, len(tmValSet.Validators)) //nolint:staticcheck + for i, v := range tmValSet.Validators { //nolint:staticcheck signerArr[i] = signers[v.Address.String()] } @@ -501,8 +512,10 @@ func (chain *TestChain) CreateTMClientHeader(chainID string, blockHeight int64, Commit: commit.ToProto(), } - valSet, err = tmValSet.ToProto() - require.NoError(chain.t, err) + if tmValSet != nil { //nolint:staticcheck + valSet, err = tmValSet.ToProto() + require.NoError(chain.t, err) + } if tmTrustedVals != nil { trustedVals, err = tmTrustedVals.ToProto() @@ -511,7 +524,7 @@ func (chain *TestChain) CreateTMClientHeader(chainID string, blockHeight int64, // 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 &ibctmtypes.Header{ + return &ibctm.Header{ SignedHeader: signedHeader, ValidatorSet: valSet, TrustedHeight: trustedHeight, @@ -539,11 +552,11 @@ func (chain *TestChain) CreatePortCapability(scopedKeeper capabilitykeeper.Scope _, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.PortPath(portID)) if !ok { // create capability using the IBC capability keeper - cap, err := chain.App.ScopedIBCKeeper.NewCapability(chain.GetContext(), host.PortPath(portID)) + 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(), cap, host.PortPath(portID)) + err = scopedKeeper.ClaimCapability(chain.GetContext(), portCap, host.PortPath(portID)) require.NoError(chain.t, err) } @@ -553,10 +566,10 @@ func (chain *TestChain) CreatePortCapability(scopedKeeper capabilitykeeper.Scope // 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 { - cap, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.PortPath(portID)) + portCap, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.PortPath(portID)) require.True(chain.t, ok) - return cap + return portCap } // CreateChannelCapability binds and claims a capability for the given portID and channelID @@ -567,9 +580,9 @@ func (chain *TestChain) CreateChannelCapability(scopedKeeper capabilitykeeper.Sc // check if the portId is already binded, if not bind it _, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), capName) if !ok { - cap, err := chain.App.ScopedIBCKeeper.NewCapability(chain.GetContext(), capName) + portCap, err := chain.App.ScopedIBCKeeper.NewCapability(chain.GetContext(), capName) require.NoError(chain.t, err) - err = scopedKeeper.ClaimCapability(chain.GetContext(), cap, capName) + err = scopedKeeper.ClaimCapability(chain.GetContext(), portCap, capName) require.NoError(chain.t, err) } @@ -579,10 +592,16 @@ func (chain *TestChain) CreateChannelCapability(scopedKeeper capabilitykeeper.Sc // 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 { - cap, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.ChannelCapabilityPath(portID, channelID)) + chanCap, ok := chain.App.ScopedIBCKeeper.GetCapability(chain.GetContext(), host.ChannelCapabilityPath(portID, channelID)) require.True(chain.t, ok) - return cap + 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 { diff --git a/x/wasm/ibctesting/coordinator.go b/x/wasm/ibctesting/coordinator.go index 0428951..4f691ff 100644 --- a/x/wasm/ibctesting/coordinator.go +++ b/x/wasm/ibctesting/coordinator.go @@ -2,24 +2,21 @@ package ibctesting import ( "fmt" - "strconv" "testing" "time" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - host "github.com/cosmos/ibc-go/v4/modules/core/24-host" - ibctesting "github.com/cosmos/ibc-go/v4/testing" + 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" - abci "github.com/tendermint/tendermint/abci/types" wasmkeeper "github.com/terpnetwork/terp-core/x/wasm/keeper" ) -const ChainIDPrefix = "testchain" - var ( - globalStartTime = time.Date(2020, 12, 4, 10, 30, 0, 0, time.UTC) 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 @@ -33,17 +30,18 @@ type Coordinator struct { // 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 := 0; i < n; i++ { + for i := 1; i <= n; i++ { chainID := GetChainID(i) var x []wasmkeeper.Option - if len(opts) > i { - x = opts[i] + if len(opts) > (i - 1) { + x = opts[i-1] } chains[chainID] = NewTestChain(t, coord, chainID, x...) } @@ -183,7 +181,7 @@ func (coord *Coordinator) GetChain(chainID string) *TestChain { // GetChainID returns the chainID used for the provided index. func GetChainID(index int) string { - return ChainIDPrefix + strconv.Itoa(index) + return ibctesting.GetChainID(index) } // CommitBlock commits a block on the provided indexes and then increments the global time. @@ -220,11 +218,9 @@ func (coord *Coordinator) ConnOpenInitOnBothChains(path *Path) error { return err } - if err := path.EndpointB.UpdateClient(); err != nil { - return err - } + err := path.EndpointB.UpdateClient() - return nil + return err } // ChanOpenInitOnBothChains initializes a channel on the source chain and counterparty chain @@ -245,11 +241,9 @@ func (coord *Coordinator) ChanOpenInitOnBothChains(path *Path) error { return err } - if err := path.EndpointB.UpdateClient(); err != nil { - return err - } + err := path.EndpointB.UpdateClient() - return nil + return err } // RelayAndAckPendingPackets sends pending packages from path.EndpointA to the counterparty chain and acks diff --git a/x/wasm/ibctesting/endpoint.go b/x/wasm/ibctesting/endpoint.go index e56c5d0..4eb47ba 100644 --- a/x/wasm/ibctesting/endpoint.go +++ b/x/wasm/ibctesting/endpoint.go @@ -2,16 +2,18 @@ package ibctesting import ( "fmt" + "strings" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - connectiontypes "github.com/cosmos/ibc-go/v4/modules/core/03-connection/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - commitmenttypes "github.com/cosmos/ibc-go/v4/modules/core/23-commitment/types" - host "github.com/cosmos/ibc-go/v4/modules/core/24-host" - "github.com/cosmos/ibc-go/v4/modules/core/exported" - ibctmtypes "github.com/cosmos/ibc-go/v4/modules/light-clients/07-tendermint/types" - ibctesting "github.com/cosmos/ibc-go/v4/testing" + 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" ) @@ -91,10 +93,9 @@ func (endpoint *Endpoint) CreateClient() (err error) { require.True(endpoint.Chain.t, ok) height := endpoint.Counterparty.Chain.LastHeader.GetHeight().(clienttypes.Height) - clientState = ibctmtypes.NewClientState( + clientState = ibctm.NewClientState( endpoint.Counterparty.Chain.ChainID, tmConfig.TrustLevel, tmConfig.TrustingPeriod, tmConfig.UnbondingPeriod, tmConfig.MaxClockDrift, - height, commitmenttypes.GetSDKSpecs(), ibctesting.UpgradePath, tmConfig.AllowUpdateAfterExpiry, tmConfig.AllowUpdateAfterMisbehaviour, - ) + height, commitmenttypes.GetSDKSpecs(), ibctesting.UpgradePath) consensusState = endpoint.Counterparty.Chain.LastHeader.ConsensusState() case exported.Solomachine: // TODO @@ -131,7 +132,7 @@ func (endpoint *Endpoint) UpdateClient() (err error) { // ensure counterparty has committed state endpoint.Chain.Coordinator.CommitBlock(endpoint.Counterparty.Chain) - var header exported.Header + var header exported.ClientMessage switch endpoint.ClientConfig.GetClientType() { case exported.Tendermint: @@ -154,6 +155,60 @@ func (endpoint *Endpoint) UpdateClient() (err error) { 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( @@ -175,9 +230,8 @@ func (endpoint *Endpoint) ConnOpenInit() error { // ConnOpenTry will construct and execute a MsgConnectionOpenTry on the associated endpoint. func (endpoint *Endpoint) ConnOpenTry() error { - if err := endpoint.UpdateClient(); err != nil { - return err - } + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) counterpartyClient, proofClient, proofConsensus, consensusHeight, proofInit, proofHeight := endpoint.QueryConnectionHandshakeProof() @@ -203,9 +257,8 @@ func (endpoint *Endpoint) ConnOpenTry() error { // ConnOpenAck will construct and execute a MsgConnectionOpenAck on the associated endpoint. func (endpoint *Endpoint) ConnOpenAck() error { - if err := endpoint.UpdateClient(); err != nil { - return err - } + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) counterpartyClient, proofClient, proofConsensus, consensusHeight, proofTry, proofHeight := endpoint.QueryConnectionHandshakeProof() @@ -221,9 +274,8 @@ func (endpoint *Endpoint) ConnOpenAck() error { // ConnOpenConfirm will construct and execute a MsgConnectionOpenConfirm on the associated endpoint. func (endpoint *Endpoint) ConnOpenConfirm() error { - if err := endpoint.UpdateClient(); err != nil { - return err - } + err := endpoint.UpdateClient() + require.NoError(endpoint.Chain.t, err) connectionKey := host.ConnectionKey(endpoint.Counterparty.ConnectionID) proof, height := endpoint.Counterparty.Chain.QueryProof(connectionKey) @@ -290,9 +342,8 @@ func (endpoint *Endpoint) ChanOpenInit() error { // ChanOpenTry will construct and execute a MsgChannelOpenTry on the associated endpoint. func (endpoint *Endpoint) ChanOpenTry() error { - if err := endpoint.UpdateClient(); err != nil { - return err - } + 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) @@ -323,9 +374,8 @@ func (endpoint *Endpoint) ChanOpenTry() error { // ChanOpenAck will construct and execute a MsgChannelOpenAck on the associated endpoint. func (endpoint *Endpoint) ChanOpenAck() error { - if err := endpoint.UpdateClient(); err != nil { - return err - } + 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) @@ -346,9 +396,8 @@ func (endpoint *Endpoint) ChanOpenAck() error { // ChanOpenConfirm will construct and execute a MsgChannelOpenConfirm on the associated endpoint. func (endpoint *Endpoint) ChanOpenConfirm() error { - if err := endpoint.UpdateClient(); err != nil { - return err - } + 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) @@ -387,19 +436,30 @@ func (endpoint *Endpoint) ChanCloseConfirm() error { // 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. -func (endpoint *Endpoint) SendPacket(packet exported.PacketI) error { - channelCap := endpoint.Chain.GetChannelCapability(packet.GetSourcePort(), packet.GetSourceChannel()) +// 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 - err := endpoint.Chain.App.IBCKeeper.ChannelKeeper.SendPacket(endpoint.Chain.GetContext(), channelCap, packet) + sequence, err := endpoint.Chain.App.IBCKeeper.ChannelKeeper.SendPacket(endpoint.Chain.GetContext(), channelCap, endpoint.ChannelConfig.PortID, endpoint.ChannelID, timeoutHeight, timeoutTimestamp, data) if err != nil { - return err + return 0, err } // commit changes since no message was sent endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain) - return endpoint.Counterparty.UpdateClient() + err = endpoint.Counterparty.UpdateClient() + if err != nil { + return 0, err + } + + return sequence, nil } // RecvPacket receives a packet on the associated endpoint. diff --git a/x/wasm/ibctesting/event_utils.go b/x/wasm/ibctesting/event_utils.go index 0933dad..a376901 100644 --- a/x/wasm/ibctesting/event_utils.go +++ b/x/wasm/ibctesting/event_utils.go @@ -8,9 +8,9 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - abci "github.com/tendermint/tendermint/abci/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 { @@ -60,8 +60,8 @@ func getHexField(evt abci.Event, key string) []byte { // return the value for the attribute with the given name func getField(evt abci.Event, key string) string { for _, attr := range evt.Attributes { - if string(attr.Key) == key { - return string(attr.Value) + if attr.Key == key { + return attr.Value } } return "" @@ -95,8 +95,8 @@ 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 string(attr.Key) == channeltypes.AttributeKeyPortID { - return string(attr.Value), nil + if attr.Key == channeltypes.AttributeKeyPortID { + return attr.Value, nil } } } @@ -108,8 +108,8 @@ 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 string(attr.Key) == channeltypes.AttributeVersion { - return string(attr.Value), nil + if attr.Key == channeltypes.AttributeVersion { + return attr.Value, nil } } } diff --git a/x/wasm/ibctesting/faucet.go b/x/wasm/ibctesting/faucet.go index 283cf19..46da6c3 100644 --- a/x/wasm/ibctesting/faucet.go +++ b/x/wasm/ibctesting/faucet.go @@ -1,6 +1,7 @@ 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" @@ -10,7 +11,7 @@ import ( ) // Fund an address with the given amount in default denom -func (chain *TestChain) Fund(addr sdk.AccAddress, amount sdk.Int) { +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(), @@ -29,7 +30,7 @@ func (chain *TestChain) SendNonDefaultSenderMsgs(senderPrivKey cryptotypes.PrivK addr := sdk.AccAddress(senderPrivKey.PubKey().Address().Bytes()) account := chain.App.AccountKeeper.GetAccount(chain.GetContext(), addr) require.NotNil(chain.t, account) - _, r, err := app.SignAndDeliver( + _, r, err := app.SignAndDeliverWithoutCommit( chain.t, chain.TxConfig, chain.App.BaseApp, @@ -41,12 +42,12 @@ func (chain *TestChain) SendNonDefaultSenderMsgs(senderPrivKey cryptotypes.PrivK senderPrivKey, ) - // SignAndDeliver calls app.Commit() + // SignAndDeliverWithoutCommit calls app.Commit() chain.NextBlock() chain.Coordinator.IncrementTime() if err != nil { return r, err } - chain.captureIBCEvents(r) + chain.CaptureIBCEvents(r) return r, nil } diff --git a/x/wasm/ibctesting/path.go b/x/wasm/ibctesting/path.go index 5e86132..c7f1af8 100644 --- a/x/wasm/ibctesting/path.go +++ b/x/wasm/ibctesting/path.go @@ -5,8 +5,8 @@ import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v4/testing" + 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 @@ -40,7 +40,7 @@ func (path *Path) SetChannelOrdered() { // 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, ack []byte) error { +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)) { @@ -59,11 +59,9 @@ func (path *Path) RelayPacket(packet channeltypes.Packet, ack []byte) error { return err } - if err := path.EndpointA.AcknowledgePacket(packet, ack); err != nil { - return err - } + err = path.EndpointA.AcknowledgePacket(packet, ack) - return nil + return err } pc = path.EndpointB.Chain.App.IBCKeeper.ChannelKeeper.GetPacketCommitment(path.EndpointB.Chain.GetContext(), packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence()) @@ -84,10 +82,8 @@ func (path *Path) RelayPacket(packet channeltypes.Packet, ack []byte) error { return err } - if err := path.EndpointB.AcknowledgePacket(packet, ack); err != nil { - return err - } - return nil + err = path.EndpointB.AcknowledgePacket(packet, ack) + return err } return fmt.Errorf("packet commitment does not exist on either endpoint for provided packet") diff --git a/x/wasm/ibctesting/wasm.go b/x/wasm/ibctesting/wasm.go index eda889b..d8e5b50 100644 --- a/x/wasm/ibctesting/wasm.go +++ b/x/wasm/ibctesting/wasm.go @@ -8,13 +8,13 @@ import ( "os" "strings" - ibctesting "github.com/cosmos/ibc-go/v4/testing" + 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/golang/protobuf/proto" //nolint + "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/rand" "github.com/terpnetwork/terp-core/x/wasm/types" ) @@ -56,14 +56,13 @@ func (chain *TestChain) StoreCode(byteCode []byte) types.MsgStoreCodeResponse { } r, err := chain.SendMsgs(storeMsg) require.NoError(chain.t, err) - protoResult := chain.parseSDKResultData(r) - require.Len(chain.t, protoResult.Data, 1) // unmarshal protobuf response from data - var pInstResp types.MsgStoreCodeResponse - require.NoError(chain.t, pInstResp.Unmarshal(protoResult.Data[0].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 + return *pInstResp } func (chain *TestChain) InstantiateContract(codeID uint64, initMsg []byte) sdk.AccAddress { @@ -78,11 +77,9 @@ func (chain *TestChain) InstantiateContract(codeID uint64, initMsg []byte) sdk.A r, err := chain.SendMsgs(instantiateMsg) require.NoError(chain.t, err) - protoResult := chain.parseSDKResultData(r) - require.Len(chain.t, protoResult.Data, 1) - - var pExecResp types.MsgInstantiateContractResponse - require.NoError(chain.t, pExecResp.Unmarshal(protoResult.Data[0].Data)) + 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 @@ -126,12 +123,6 @@ func (chain *TestChain) SmartQuery(contractAddr string, queryMsg interface{}, re return json.Unmarshal(resp.Data, response) } -func (chain *TestChain) parseSDKResultData(r *sdk.Result) sdk.TxMsgData { - var protoResult sdk.TxMsgData - require.NoError(chain.t, proto.Unmarshal(r.Data, &protoResult)) - return protoResult -} - // 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/utils.go b/x/wasm/ioutils/utils.go index 197c44c..9c9cd38 100644 --- a/x/wasm/ioutils/utils.go +++ b/x/wasm/ioutils/utils.go @@ -12,6 +12,8 @@ var ( // 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") ) diff --git a/x/wasm/keeper/addresses_test.go b/x/wasm/keeper/addresses_test.go index fbcc607..399c3e7 100644 --- a/x/wasm/keeper/addresses_test.go +++ b/x/wasm/keeper/addresses_test.go @@ -5,9 +5,9 @@ import ( "fmt" "testing" + tmbytes "github.com/cometbft/cometbft/libs/bytes" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - tmbytes "github.com/tendermint/tendermint/libs/bytes" ) func TestBuildContractAddress(t *testing.T) { diff --git a/x/wasm/keeper/ante.go b/x/wasm/keeper/ante.go index 3d1faee..27dd580 100644 --- a/x/wasm/keeper/ante.go +++ b/x/wasm/keeper/ante.go @@ -3,6 +3,7 @@ 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" @@ -10,11 +11,11 @@ import ( // CountTXDecorator ante handler to count the tx position in a block. type CountTXDecorator struct { - storeKey sdk.StoreKey + storeKey storetypes.StoreKey } // NewCountTXDecorator constructor -func NewCountTXDecorator(storeKey sdk.StoreKey) *CountTXDecorator { +func NewCountTXDecorator(storeKey storetypes.StoreKey) *CountTXDecorator { return &CountTXDecorator{storeKey: storeKey} } diff --git a/x/wasm/keeper/ante_test.go b/x/wasm/keeper/ante_test.go index bc5da14..5903335 100644 --- a/x/wasm/keeper/ante_test.go +++ b/x/wasm/keeper/ante_test.go @@ -4,18 +4,16 @@ import ( "testing" "time" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/terpnetwork/terp-core/x/wasm/keeper" - + 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/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" + "github.com/terpnetwork/terp-core/x/wasm/keeper" "github.com/terpnetwork/terp-core/x/wasm/types" ) @@ -23,7 +21,7 @@ func TestCountTxDecorator(t *testing.T) { keyWasm := sdk.NewKVStoreKey(types.StoreKey) db := dbm.NewMemDB() ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyWasm, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(keyWasm, storetypes.StoreTypeIAVL, db) require.NoError(t, ms.LoadLatestVersion()) const myCurrentBlockHeight = 100 @@ -34,7 +32,9 @@ func TestCountTxDecorator(t *testing.T) { expErr bool }{ "no initial counter set": { - setupDB: func(t *testing.T, ctx sdk.Context) {}, + setupDB: func(t *testing.T, ctx sdk.Context) { + t.Helper() + }, nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { gotCounter, ok := types.TXCounter(ctx) require.True(t, ok) @@ -47,6 +47,7 @@ func TestCountTxDecorator(t *testing.T) { }, "persistent counter incremented - big endian": { setupDB: func(t *testing.T, ctx sdk.Context) { + t.Helper() bz := []byte{0, 0, 0, 0, 0, 0, 0, myCurrentBlockHeight, 1, 0, 0, 2} ctx.MultiStore().GetKVStore(keyWasm).Set(types.TXCounterPrefix, bz) }, @@ -62,6 +63,7 @@ func TestCountTxDecorator(t *testing.T) { }, "old height counter replaced": { setupDB: func(t *testing.T, ctx sdk.Context) { + t.Helper() 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) @@ -78,6 +80,7 @@ func TestCountTxDecorator(t *testing.T) { }, "simulation not persisted": { setupDB: func(t *testing.T, ctx sdk.Context) { + t.Helper() }, simulate: true, nextAssertAnte: func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { @@ -164,19 +167,21 @@ func TestLimitSimulationGasDecorator(t *testing.T) { nextAnte := consumeGasAnteHandler(spec.consumeGas) ctx := sdk.Context{}. WithGasMeter(sdk.NewInfiniteGasMeter()). - WithConsensusParams(&abci.ConsensusParams{ - Block: &abci.BlockParams{MaxGas: spec.maxBlockGas}, + 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) - ante.AnteHandle(ctx, nil, spec.simulation, nextAnte) + _, err := ante.AnteHandle(ctx, nil, spec.simulation, nextAnte) + require.NoError(t, err) }) return } ante := keeper.NewLimitSimulationGasDecorator(spec.customLimit) - ante.AnteHandle(ctx, nil, spec.simulation, nextAnte) + _, err := ante.AnteHandle(ctx, nil, spec.simulation, nextAnte) + require.NoError(t, err) }) } } diff --git a/x/wasm/keeper/api.go b/x/wasm/keeper/api.go index 3b39b34..88f3b82 100644 --- a/x/wasm/keeper/api.go +++ b/x/wasm/keeper/api.go @@ -7,12 +7,12 @@ import ( ) const ( - // DefaultGasCostHumanAddress is how moch SDK gas we charge to convert to a human address format + // DefaultGasCostHumanAddress is how much SDK gas we charge to convert to a human address format DefaultGasCostHumanAddress = 5 - // DefaultGasCostCanonicalAddress is how moch SDK gas we charge to convert to a canonical address format + // DefaultGasCostCanonicalAddress is how much SDK gas we charge to convert to a canonical address format DefaultGasCostCanonicalAddress = 4 - // DefaultDeserializationCostPerByte The formular should be `len(data) * deserializationCostPerByte` + // DefaultDeserializationCostPerByte The formula should be `len(data) * deserializationCostPerByte` DefaultDeserializationCostPerByte = 1 ) diff --git a/x/wasm/keeper/bench_test.go b/x/wasm/keeper/bench_test.go index a47cacd..2780665 100644 --- a/x/wasm/keeper/bench_test.go +++ b/x/wasm/keeper/bench_test.go @@ -4,9 +4,9 @@ import ( "os" "testing" + dbm "github.com/cometbft/cometbft-db" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/stretchr/testify/require" - dbm "github.com/tendermint/tm-db" "github.com/terpnetwork/terp-core/x/wasm/types" ) diff --git a/x/wasm/keeper/contract_keeper_test.go b/x/wasm/keeper/contract_keeper_test.go index 40197bd..c722ff0 100644 --- a/x/wasm/keeper/contract_keeper_test.go +++ b/x/wasm/keeper/contract_keeper_test.go @@ -18,6 +18,8 @@ import ( 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{} @@ -27,7 +29,6 @@ func TestInstantiate2(t *testing.T) { 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 ( @@ -36,6 +37,7 @@ func TestInstantiate2(t *testing.T) { ) // create instances for duplicate checks exampleContract := func(t *testing.T, ctx sdk.Context, fixMsg bool) { + t.Helper() _, _, err := keepers.ContractKeeper.Instantiate2( ctx, example.CodeID, @@ -50,9 +52,11 @@ func TestInstantiate2(t *testing.T) { require.NoError(t, err) } exampleWithFixMsg := func(t *testing.T, ctx sdk.Context) { + t.Helper() exampleContract(t, ctx, true) } exampleWithoutFixMsg := func(t *testing.T, ctx sdk.Context) { + t.Helper() exampleContract(t, ctx, false) } specs := map[string]struct { diff --git a/x/wasm/keeper/events.go b/x/wasm/keeper/events.go index 441d591..47068aa 100644 --- a/x/wasm/keeper/events.go +++ b/x/wasm/keeper/events.go @@ -4,9 +4,10 @@ import ( "fmt" "strings" + errorsmod "cosmossdk.io/errors" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/terpnetwork/terp-core/x/wasm/types" ) @@ -31,7 +32,7 @@ func newCustomEvents(evts wasmvmtypes.Events, contractAddr sdk.AccAddress) (sdk. for _, e := range evts { typ := strings.TrimSpace(e.Type) if len(typ) <= eventTypeMinLength { - return nil, sdkerrors.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Event type too short: '%s'", typ)) + return nil, errorsmod.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Event type too short: '%s'", typ)) } attributes, err := contractSDKEventAttributes(e.Attributes, contractAddr) if err != nil { @@ -50,16 +51,16 @@ func contractSDKEventAttributes(customAttributes []wasmvmtypes.EventAttribute, c // ensure key and value are non-empty (and trim what is there) key := strings.TrimSpace(l.Key) if len(key) == 0 { - return nil, sdkerrors.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Empty attribute key. Value: %s", l.Value)) + 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, sdkerrors.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Empty attribute value. Key: %s", key)) + 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, sdkerrors.Wrap(types.ErrInvalidEvent, fmt.Sprintf("Attribute key starts with reserved prefix %s: '%s'", types.AttributeReservedPrefix, key)) + 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)) } diff --git a/x/wasm/keeper/events_test.go b/x/wasm/keeper/events_test.go index 5ed07f4..5320b28 100644 --- a/x/wasm/keeper/events_test.go +++ b/x/wasm/keeper/events_test.go @@ -280,7 +280,7 @@ 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 string(a.Key) == types.AttributeKeyContractAddr && string(a.Value) == contractAddr.String() { + if a.Key == types.AttributeKeyContractAddr && a.Value == contractAddr.String() { return true } } diff --git a/x/wasm/keeper/gas_register.go b/x/wasm/keeper/gas_register.go index b78ba06..e26a19a 100644 --- a/x/wasm/keeper/gas_register.go +++ b/x/wasm/keeper/gas_register.go @@ -1,6 +1,7 @@ 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" @@ -22,20 +23,20 @@ const ( // 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/CosmWasm/wasmd/issues/566 and https://github.com/CosmWasm/wasmd/issues/631. + // 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/CosmWasm/wasmd/pull/634#issuecomment-938055852 + // 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/CosmWasm/wasmd/pull/634#issuecomment-938056803 + // 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/CosmWasm/wasmd/pull/634#issuecomment-938056803 + // 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) @@ -55,7 +56,7 @@ const ( ) // default: 0.15 gas. -// see https://github.com/CosmWasm/wasmd/pull/898#discussion_r937727200 +// see https://github.com/terpnetwork/terp-core/pull/898#discussion_r937727200 var defaultPerByteUncompressCost = wasmvmtypes.UFraction{ Numerator: 15, Denominator: 100, @@ -68,7 +69,7 @@ func DefaultPerByteUncompressCost() wasmvmtypes.UFraction { // GasRegister abstract source for gas costs type GasRegister interface { - // NewContractInstanceCosts costs to crate a new contract instance from code + // 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 @@ -140,14 +141,14 @@ func NewDefaultWasmGasRegister() WasmGasRegister { // NewWasmGasRegister constructor func NewWasmGasRegister(c WasmGasRegisterConfig) WasmGasRegister { if c.GasMultiplier == 0 { - panic(sdkerrors.Wrap(sdkerrors.ErrLogic, "GasMultiplier can not be 0")) + panic(errorsmod.Wrap(sdkerrors.ErrLogic, "GasMultiplier can not be 0")) } return WasmGasRegister{ c: c, } } -// NewContractInstanceCosts costs to crate a new contract instance from code +// 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) } @@ -155,7 +156,7 @@ func (g WasmGasRegister) NewContractInstanceCosts(pinned bool, msgLen int) store // CompileCosts costs to persist and "compile" a new wasm contract func (g WasmGasRegister) CompileCosts(byteLength int) storetypes.Gas { if byteLength < 0 { - panic(sdkerrors.Wrap(types.ErrInvalid, "negative length")) + panic(errorsmod.Wrap(types.ErrInvalid, "negative length")) } return g.c.CompileCost * uint64(byteLength) } @@ -163,7 +164,7 @@ func (g WasmGasRegister) CompileCosts(byteLength int) storetypes.Gas { // UncompressCosts costs to unpack a new wasm contract func (g WasmGasRegister) UncompressCosts(byteLength int) sdk.Gas { if byteLength < 0 { - panic(sdkerrors.Wrap(types.ErrInvalid, "negative length")) + panic(errorsmod.Wrap(types.ErrInvalid, "negative length")) } return g.c.UncompressCost.Mul(uint64(byteLength)).Floor() } @@ -171,7 +172,7 @@ func (g WasmGasRegister) UncompressCosts(byteLength int) sdk.Gas { // InstantiateContractCosts costs when interacting with a wasm contract func (g WasmGasRegister) InstantiateContractCosts(pinned bool, msgLen int) sdk.Gas { if msgLen < 0 { - panic(sdkerrors.Wrap(types.ErrInvalid, "negative length")) + panic(errorsmod.Wrap(types.ErrInvalid, "negative length")) } dataCosts := sdk.Gas(msgLen) * g.c.ContractMessageDataCost if pinned { diff --git a/x/wasm/keeper/gas_register_test.go b/x/wasm/keeper/gas_register_test.go index 44b836c..3a29e07 100644 --- a/x/wasm/keeper/gas_register_test.go +++ b/x/wasm/keeper/gas_register_test.go @@ -84,12 +84,12 @@ func TestNewContractInstanceCosts(t *testing.T) { "big msg - unpinned": { srcLen: math.MaxUint32, srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(DefaultContractMessageDataCost*math.MaxUint32 + DefaultInstanceCost), + exp: DefaultContractMessageDataCost*math.MaxUint32 + DefaultInstanceCost, }, "empty msg - unpinned": { srcLen: 0, srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(DefaultInstanceCost), + exp: DefaultInstanceCost, }, "negative len": { @@ -131,7 +131,7 @@ func TestContractInstanceCosts(t *testing.T) { srcLen: math.MaxUint32, srcConfig: DefaultGasRegisterConfig(), pinned: true, - exp: sdk.Gas(DefaultContractMessageDataCost * math.MaxUint32), + exp: DefaultContractMessageDataCost * math.MaxUint32, }, "empty msg - pinned": { srcLen: 0, @@ -147,12 +147,12 @@ func TestContractInstanceCosts(t *testing.T) { "big msg - unpinned": { srcLen: math.MaxUint32, srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(DefaultContractMessageDataCost*math.MaxUint32 + DefaultInstanceCost), + exp: DefaultContractMessageDataCost*math.MaxUint32 + DefaultInstanceCost, }, "empty msg - unpinned": { srcLen: 0, srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(DefaultInstanceCost), + exp: DefaultInstanceCost, }, "negative len": { @@ -196,7 +196,7 @@ func TestReplyCost(t *testing.T) { }, srcConfig: DefaultGasRegisterConfig(), pinned: true, - exp: sdk.Gas(3*DefaultEventAttributeDataCost + DefaultPerAttributeCost + DefaultContractMessageDataCost), // 3 == len("foo") + exp: 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost + DefaultContractMessageDataCost, // 3 == len("foo") }, "subcall response with events - pinned": { src: wasmvmtypes.Reply{ @@ -210,7 +210,7 @@ func TestReplyCost(t *testing.T) { }, srcConfig: DefaultGasRegisterConfig(), pinned: true, - exp: sdk.Gas(3*DefaultEventAttributeDataCost + DefaultPerAttributeCost), // 3 == len("foo") + exp: 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost, // 3 == len("foo") }, "subcall response with events exceeds free tier- pinned": { src: wasmvmtypes.Reply{ @@ -224,7 +224,7 @@ func TestReplyCost(t *testing.T) { }, srcConfig: DefaultGasRegisterConfig(), pinned: true, - exp: sdk.Gas((3+6)*DefaultEventAttributeDataCost + DefaultPerAttributeCost), // 3 == len("foo"), 6 == len("myData") + exp: (3+6)*DefaultEventAttributeDataCost + DefaultPerAttributeCost, // 3 == len("foo"), 6 == len("myData") }, "subcall response error - pinned": { src: wasmvmtypes.Reply{ @@ -248,7 +248,7 @@ func TestReplyCost(t *testing.T) { }, }, srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(DefaultInstanceCost + 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost + DefaultContractMessageDataCost), + exp: DefaultInstanceCost + 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost + DefaultContractMessageDataCost, }, "subcall response with events - unpinned": { src: wasmvmtypes.Reply{ @@ -261,7 +261,7 @@ func TestReplyCost(t *testing.T) { }, }, srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(DefaultInstanceCost + 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost), + exp: DefaultInstanceCost + 3*DefaultEventAttributeDataCost + DefaultPerAttributeCost, }, "subcall response with events exceeds free tier- unpinned": { src: wasmvmtypes.Reply{ @@ -274,7 +274,7 @@ func TestReplyCost(t *testing.T) { }, }, srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(DefaultInstanceCost + (3+6)*DefaultEventAttributeDataCost + DefaultPerAttributeCost), // 3 == len("foo"), 6 == len("myData") + exp: DefaultInstanceCost + (3+6)*DefaultEventAttributeDataCost + DefaultPerAttributeCost, // 3 == len("foo"), 6 == len("myData") }, "subcall response error - unpinned": { src: wasmvmtypes.Reply{ @@ -283,7 +283,7 @@ func TestReplyCost(t *testing.T) { }, }, srcConfig: DefaultGasRegisterConfig(), - exp: sdk.Gas(DefaultInstanceCost + 3*DefaultContractMessageDataCost), + exp: DefaultInstanceCost + 3*DefaultContractMessageDataCost, }, "subcall response with empty events": { src: wasmvmtypes.Reply{ diff --git a/x/wasm/keeper/genesis.go b/x/wasm/keeper/genesis.go index 39fc234..0e467ea 100644 --- a/x/wasm/keeper/genesis.go +++ b/x/wasm/keeper/genesis.go @@ -1,9 +1,9 @@ package keeper import ( + errorsmod "cosmossdk.io/errors" + abci "github.com/cometbft/cometbft/abci/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - abci "github.com/tendermint/tendermint/abci/types" "github.com/terpnetwork/terp-core/x/wasm/types" ) @@ -18,19 +18,23 @@ type ValidatorSetSource interface { // 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) - keeper.SetParams(ctx, data.Params) + 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, sdkerrors.Wrapf(err, "code %d with id: %d", i, code.CodeID) + 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, sdkerrors.Wrapf(err, "contract number %d", i) + return nil, errorsmod.Wrapf(err, "contract number %d", i) } } } @@ -39,11 +43,11 @@ func InitGenesis(ctx sdk.Context, keeper *Keeper, data types.GenesisState) ([]ab for i, contract := range data.Contracts { contractAddr, err := sdk.AccAddressFromBech32(contract.ContractAddress) if err != nil { - return nil, sdkerrors.Wrapf(err, "address in contract number %d", i) + 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, sdkerrors.Wrapf(err, "contract number %d", i) + return nil, errorsmod.Wrapf(err, "contract number %d", i) } maxContractID = i + 1 // not ideal but max(contractID) is not persisted otherwise } @@ -51,18 +55,18 @@ func InitGenesis(ctx sdk.Context, keeper *Keeper, data types.GenesisState) ([]ab for i, seq := range data.Sequences { err := keeper.importAutoIncrementID(ctx, seq.IDKey, seq.Value) if err != nil { - return nil, sdkerrors.Wrapf(err, "sequence number %d", i) + return nil, errorsmod.Wrapf(err, "sequence number %d", i) } } // sanity check seq values seqVal := keeper.PeekAutoIncrementID(ctx, types.KeyLastCodeID) if seqVal <= maxCodeID { - return nil, sdkerrors.Wrapf(types.ErrInvalid, "seq %s with value: %d must be greater than: %d ", string(types.KeyLastCodeID), 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, sdkerrors.Wrapf(types.ErrInvalid, "seq %s with value: %d must be greater than: %d ", string(types.KeyLastInstanceID), seqVal, 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 } diff --git a/x/wasm/keeper/genesis_test.go b/x/wasm/keeper/genesis_test.go index 27ec75f..6be1689 100644 --- a/x/wasm/keeper/genesis_test.go +++ b/x/wasm/keeper/genesis_test.go @@ -9,30 +9,33 @@ import ( "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" - distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" 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/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/terpnetwork/terp-core/x/wasm/types" - wasmTypes "github.com/terpnetwork/terp-core/x/wasm/types" ) const firstCodeID = 1 func TestGenesisExportImport(t *testing.T) { - wasmKeeper, srcCtx, srcStoreKeys := setupKeeper(t) + wasmKeeper, srcCtx := setupKeeper(t) contractKeeper := NewGovPermissionKeeper(wasmKeeper) wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") @@ -41,7 +44,8 @@ func TestGenesisExportImport(t *testing.T) { // store some test data f := fuzz.New().Funcs(ModelFuzzers...) - wasmKeeper.SetParams(srcCtx, types.DefaultParams()) + err = wasmKeeper.SetParams(srcCtx, types.DefaultParams()) + require.NoError(t, err) for i := 0; i < 25; i++ { var ( @@ -64,26 +68,30 @@ func TestGenesisExportImport(t *testing.T) { codeID, _, err := contractKeeper.Create(srcCtx, creatorAddr, wasmCode, &codeInfo.InstantiateConfig) require.NoError(t, err) if pinned { - contractKeeper.PinCode(srcCtx, codeID) + err = contractKeeper.PinCode(srcCtx, codeID) + require.NoError(t, err) } if contractExtension { anyTime := time.Now().UTC() - var nestedType govtypes.TextProposal + var nestedType v1beta1.TextProposal f.NilChance(0).Fuzz(&nestedType) - myExtension, err := govtypes.NewProposal(&nestedType, 1, anyTime, anyTime) + myExtension, err := v1beta1.NewProposal(&nestedType, 1, anyTime, anyTime) + require.NoError(t, err) + err = contract.SetExtension(&myExtension) require.NoError(t, err) - contract.SetExtension(&myExtension) } contract.CodeID = codeID contractAddr := wasmKeeper.ClassicAddressGenerator()(srcCtx, codeID, nil) wasmKeeper.storeContractInfo(srcCtx, contractAddr, &contract) wasmKeeper.appendToContractHistory(srcCtx, contractAddr, history...) - wasmKeeper.importContractState(srcCtx, contractAddr, stateModels) + err = wasmKeeper.importContractState(srcCtx, contractAddr, stateModels) + require.NoError(t, err) } var wasmParams types.Params f.NilChance(0).Fuzz(&wasmParams) - wasmKeeper.SetParams(srcCtx, wasmParams) + err = wasmKeeper.SetParams(srcCtx, wasmParams) + require.NoError(t, err) // export exportedState := ExportGenesis(srcCtx, wasmKeeper) @@ -101,10 +109,10 @@ func TestGenesisExportImport(t *testing.T) { require.NoError(t, err) // setup new instances - dstKeeper, dstCtx, dstStoreKeys := setupKeeper(t) + dstKeeper, dstCtx := setupKeeper(t) // reset contract code index in source DB for comparison with dest DB - wasmKeeper.IterateContractInfo(srcCtx, func(address sdk.AccAddress, info wasmTypes.ContractInfo) bool { + wasmKeeper.IterateContractInfo(srcCtx, func(address sdk.AccAddress, info types.ContractInfo) bool { creatorAddress := sdk.MustAccAddressFromBech32(info.Creator) history := wasmKeeper.GetContractHistory(srcCtx, address) @@ -114,36 +122,36 @@ func TestGenesisExportImport(t *testing.T) { }) // re-import - var importState wasmTypes.GenesisState + var importState types.GenesisState err = dstKeeper.cdc.UnmarshalJSON(exportedGenesis, &importState) require.NoError(t, err) - InitGenesis(dstCtx, dstKeeper, importState) + _, err = InitGenesis(dstCtx, dstKeeper, importState) + require.NoError(t, err) // compare whole DB - for j := range srcStoreKeys { - srcIT := srcCtx.KVStore(srcStoreKeys[j]).Iterator(nil, nil) - dstIT := dstCtx.KVStore(dstStoreKeys[j]).Iterator(nil, nil) - - for i := 0; srcIT.Valid(); i++ { - require.True(t, dstIT.Valid(), "[%s] destination DB has less elements than source. Missing: %x", srcStoreKeys[j].Name(), srcIT.Key()) - require.Equal(t, srcIT.Key(), dstIT.Key(), i) - require.Equal(t, srcIT.Value(), dstIT.Value(), "[%s] element (%d): %X", srcStoreKeys[j].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() + + 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 := wasmTypes.CodeInfoFixture(wasmTypes.WithSHA256CodeHash(wasmCode)) + myCodeInfo := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) specs := map[string]struct { src types.GenesisState expSuccess bool @@ -205,7 +213,7 @@ func TestGenesisInit(t *testing.T) { "prevent code hash mismatch": {src: types.GenesisState{ Codes: []types.Code{{ CodeID: firstCodeID, - CodeInfo: wasmTypes.CodeInfoFixture(func(i *wasmTypes.CodeInfo) { i.CodeHash = make([]byte, sha256.Size) }), + CodeInfo: types.CodeInfoFixture(func(i *types.CodeInfo) { i.CodeHash = make([]byte, sha256.Size) }), CodeBytes: wasmCode, }}, Params: types.DefaultParams(), @@ -254,7 +262,7 @@ func TestGenesisInit(t *testing.T) { Contracts: []types.Contract{ { ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *wasmTypes.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), + ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), ContractCodeHistory: []types.ContractCodeHistoryEntry{ { Operation: types.ContractCodeHistoryOperationTypeMigrate, @@ -283,7 +291,7 @@ func TestGenesisInit(t *testing.T) { Contracts: []types.Contract{ { ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *wasmTypes.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), + ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), ContractCodeHistory: []types.ContractCodeHistoryEntry{ { Operation: types.ContractCodeHistoryOperationTypeMigrate, @@ -294,7 +302,7 @@ func TestGenesisInit(t *testing.T) { }, }, { ContractAddress: BuildContractAddressClassic(1, 2).String(), - ContractInfo: types.ContractInfoFixture(func(c *wasmTypes.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), + ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), ContractCodeHistory: []types.ContractCodeHistoryEntry{ { Operation: types.ContractCodeHistoryOperationTypeMigrate, @@ -318,7 +326,7 @@ func TestGenesisInit(t *testing.T) { Contracts: []types.Contract{ { ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *wasmTypes.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), + ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), ContractCodeHistory: []types.ContractCodeHistoryEntry{ { Operation: types.ContractCodeHistoryOperationTypeMigrate, @@ -342,7 +350,7 @@ func TestGenesisInit(t *testing.T) { Contracts: []types.Contract{ { ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *wasmTypes.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), + ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), ContractCodeHistory: []types.ContractCodeHistoryEntry{ { Operation: types.ContractCodeHistoryOperationTypeMigrate, @@ -353,7 +361,7 @@ func TestGenesisInit(t *testing.T) { }, }, { ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *wasmTypes.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), + ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), ContractCodeHistory: []types.ContractCodeHistoryEntry{ { Operation: types.ContractCodeHistoryOperationTypeMigrate, @@ -377,7 +385,7 @@ func TestGenesisInit(t *testing.T) { Contracts: []types.Contract{ { ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *wasmTypes.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), + ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), ContractState: []types.Model{ { Key: []byte{0x1}, @@ -433,7 +441,7 @@ func TestGenesisInit(t *testing.T) { Contracts: []types.Contract{ { ContractAddress: BuildContractAddressClassic(1, 1).String(), - ContractInfo: types.ContractInfoFixture(func(c *wasmTypes.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), + ContractInfo: types.ContractInfoFixture(func(c *types.ContractInfo) { c.CodeID = 1 }, types.RandCreatedFields), ContractCodeHistory: []types.ContractCodeHistoryEntry{ { Operation: types.ContractCodeHistoryOperationTypeMigrate, @@ -454,7 +462,7 @@ func TestGenesisInit(t *testing.T) { } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - keeper, ctx, _ := setupKeeper(t) + keeper, ctx := setupKeeper(t) require.NoError(t, types.ValidateGenesis(spec.src)) _, gotErr := InitGenesis(ctx, keeper, spec.src) @@ -534,7 +542,7 @@ func TestImportContractWithCodeHistoryPreserved(t *testing.T) { {"id_key": "BGxhc3RDb250cmFjdElk", "value": "3"} ] }` - keeper, ctx, _ := setupKeeper(t) + keeper, ctx := setupKeeper(t) wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -543,7 +551,7 @@ func TestImportContractWithCodeHistoryPreserved(t *testing.T) { enc64 := base64.StdEncoding.EncodeToString genesisStr := fmt.Sprintf(genesisTemplate, enc64(wasmCodeHash[:]), enc64(wasmCode)) - var importState wasmTypes.GenesisState + var importState types.GenesisState err = keeper.cdc.UnmarshalJSON([]byte(genesisStr), &importState) require.NoError(t, err) require.NoError(t, importState.ValidateBasic(), genesisStr) @@ -566,7 +574,7 @@ func TestImportContractWithCodeHistoryPreserved(t *testing.T) { expCodeInfo := types.CodeInfo{ CodeHash: wasmCodeHash[:], Creator: codeCreatorAddr, - InstantiateConfig: wasmTypes.AccessConfig{ + InstantiateConfig: types.AccessConfig{ Permission: types.AccessTypeOnlyAddress, Address: codeCreatorAddr, }, @@ -614,22 +622,17 @@ func TestImportContractWithCodeHistoryPreserved(t *testing.T) { assert.Equal(t, uint64(3), keeper.PeekAutoIncrementID(ctx, types.KeyLastInstanceID)) } -func setupKeeper(t *testing.T) (*Keeper, sdk.Context, []sdk.StoreKey) { +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) }) - var ( - keyParams = sdk.NewKVStoreKey(paramtypes.StoreKey) - tkeyParams = sdk.NewTransientStoreKey(paramtypes.TStoreKey) - keyWasm = sdk.NewKVStoreKey(wasmTypes.StoreKey) - ) + + keyWasm := sdk.NewKVStoreKey(types.StoreKey) db := dbm.NewMemDB() ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyWasm, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) + ms.MountStoreWithDB(keyWasm, storetypes.StoreTypeIAVL, db) require.NoError(t, ms.LoadLatestVersion()) ctx := sdk.NewContext(ms, tmproto.Header{ @@ -641,22 +644,20 @@ func setupKeeper(t *testing.T) (*Keeper, sdk.Context, []sdk.StoreKey) { // register an example extension. must be protobuf encodingConfig.InterfaceRegistry.RegisterImplementations( (*types.ContractInfoExtension)(nil), - &govtypes.Proposal{}, + &v1beta1.Proposal{}, ) // also registering gov interfaces for nested Any type - govtypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) + v1beta1.RegisterInterfaces(encodingConfig.InterfaceRegistry) - wasmConfig := wasmTypes.DefaultWasmConfig() - pk := paramskeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, keyParams, tkeyParams) + wasmConfig := types.DefaultWasmConfig() srcKeeper := NewKeeper( encodingConfig.Marshaler, keyWasm, - pk.Subspace(wasmTypes.ModuleName), authkeeper.AccountKeeper{}, &bankkeeper.BaseKeeper{}, stakingkeeper.Keeper{}, - distributionkeeper.Keeper{}, + nil, nil, nil, nil, @@ -666,6 +667,39 @@ func setupKeeper(t *testing.T) (*Keeper, sdk.Context, []sdk.StoreKey) { tempDir, wasmConfig, AvailableCapabilities, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) - return &srcKeeper, ctx, []sdk.StoreKey{keyWasm, keyParams} + 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 index 42337b0..beba71a 100644 --- a/x/wasm/keeper/handler_plugin.go +++ b/x/wasm/keeper/handler_plugin.go @@ -4,13 +4,15 @@ 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/v4/modules/core/04-channel/types" - host "github.com/cosmos/ibc-go/v4/modules/core/24-host" + 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" ) @@ -88,7 +90,7 @@ func (h SDKMessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Ad // make sure this account can send it for _, acct := range msg.GetSigners() { if !acct.Equals(contractAddr) { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "contract doesn't have permission") + return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "contract doesn't have permission") } } @@ -103,7 +105,7 @@ func (h SDKMessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Ad // 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, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "can't route message %+v", msg) + 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. @@ -137,7 +139,7 @@ func (m MessageHandlerChain) DispatchMsg(ctx sdk.Context, contractAddr sdk.AccAd return events, data, err } } - return nil, nil, sdkerrors.Wrap(types.ErrUnknownMsg, "no handler found") + return nil, nil, errorsmod.Wrap(types.ErrUnknownMsg, "no handler found") } // IBCRawPacketHandler handels IBC.SendPacket messages which are published to an IBC channel. @@ -151,44 +153,35 @@ func NewIBCRawPacketHandler(chk types.ChannelKeeper, cak types.CapabilityKeeper) } // DispatchMsg publishes a raw IBC packet onto the channel. -func (h IBCRawPacketHandler) DispatchMsg(ctx sdk.Context, _ sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) (events []sdk.Event, data [][]byte, err error) { +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, sdkerrors.Wrapf(types.ErrUnsupportedForContract, "ibc not supported") + return nil, nil, errorsmod.Wrapf(types.ErrUnsupportedForContract, "ibc not supported") } contractIBCChannelID := msg.IBC.SendPacket.ChannelID if contractIBCChannelID == "" { - return nil, nil, sdkerrors.Wrapf(types.ErrEmpty, "ibc channel") + return nil, nil, errorsmod.Wrapf(types.ErrEmpty, "ibc channel") } - sequence, found := h.channelKeeper.GetNextSequenceSend(ctx, contractIBCPortID, contractIBCChannelID) - if !found { - return nil, nil, sdkerrors.Wrapf(channeltypes.ErrSequenceSendNotFound, - "source port: %s, source channel: %s", contractIBCPortID, contractIBCChannelID, - ) + 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) - channelInfo, ok := h.channelKeeper.GetChannel(ctx, contractIBCPortID, contractIBCChannelID) - if !ok { - return nil, nil, sdkerrors.Wrap(channeltypes.ErrInvalidChannel, "not found") + resp := &types.MsgIBCSendResponse{Sequence: seq} + val, err := resp.Marshal() + if err != nil { + return nil, nil, errorsmod.Wrap(err, "failed to marshal IBC send response") } - channelCap, ok := h.capabilityKeeper.GetCapability(ctx, host.ChannelCapabilityPath(contractIBCPortID, contractIBCChannelID)) - if !ok { - return nil, nil, sdkerrors.Wrap(channeltypes.ErrChannelCapabilityNotFound, "module does not own channel capability") - } - packet := channeltypes.NewPacket( - msg.IBC.SendPacket.Data, - sequence, - contractIBCPortID, - contractIBCChannelID, - channelInfo.Counterparty.PortId, - channelInfo.Counterparty.ChannelId, - ConvertWasmIBCTimeoutHeightToCosmosHeight(msg.IBC.SendPacket.Timeout.Block), - msg.IBC.SendPacket.Timeout.Timestamp, - ) - return nil, nil, h.channelKeeper.SendPacket(ctx, channelCap, packet) + + return nil, [][]byte{val}, nil } var _ Messenger = MessageHandlerFunc(nil) @@ -209,11 +202,14 @@ func NewBurnCoinMessageHandler(burner types.Burner) MessageHandlerFunc { 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, sdkerrors.Wrap(err, "transfer to module") + return nil, nil, errorsmod.Wrap(err, "transfer to module") } if err := burner.BurnCoins(ctx, types.ModuleName, coins); err != nil { - return nil, nil, sdkerrors.Wrap(err, "burn coins") + return nil, nil, errorsmod.Wrap(err, "burn coins") } moduleLogger(ctx).Info("Burned", "amount", coins) return nil, nil, nil diff --git a/x/wasm/keeper/handler_plugin_encoders.go b/x/wasm/keeper/handler_plugin_encoders.go index e002423..e6883e1 100644 --- a/x/wasm/keeper/handler_plugin_encoders.go +++ b/x/wasm/keeper/handler_plugin_encoders.go @@ -4,17 +4,19 @@ 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" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - ibcclienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/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" ) @@ -103,12 +105,12 @@ func (e MessageEncoders) Encode(ctx sdk.Context, contractAddr sdk.AccAddress, co case msg.Gov != nil: return EncodeGovMsg(contractAddr, msg.Gov) } - return nil, sdkerrors.Wrap(types.ErrUnknownMsg, "unknown variant of Wasm") + 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, sdkerrors.Wrap(types.ErrUnknownMsg, "unknown variant of Bank") + return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Bank") } if len(msg.Send.Amount) == 0 { return nil, nil @@ -125,8 +127,8 @@ func EncodeBankMsg(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, return []sdk.Msg{&sdkMsg}, nil } -func NoCustomMsg(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { - return nil, sdkerrors.Wrap(types.ErrUnknownMsg, "custom variant not supported") +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) { @@ -144,7 +146,7 @@ func EncodeDistributionMsg(sender sdk.AccAddress, msg *wasmvmtypes.DistributionM } return []sdk.Msg{&withdrawMsg}, nil default: - return nil, sdkerrors.Wrap(types.ErrUnknownMsg, "unknown variant of Distribution") + return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Distribution") } } @@ -186,22 +188,22 @@ func EncodeStakingMsg(sender sdk.AccAddress, msg *wasmvmtypes.StakingMsg) ([]sdk } return []sdk.Msg{&sdkMsg}, nil default: - return nil, sdkerrors.Wrap(types.ErrUnknownMsg, "unknown variant of Staking") + 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) { - any := codectypes.Any{ + codecAny := codectypes.Any{ TypeUrl: msg.TypeURL, Value: msg.Value, } var sdkMsg sdk.Msg - if err := unpacker.UnpackAny(&any, &sdkMsg); err != nil { - return nil, sdkerrors.Wrap(types.ErrInvalidMsg, fmt.Sprintf("Cannot unpack proto message with type URL: %s", msg.TypeURL)) + 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, sdkerrors.Wrap(types.ErrInvalidMsg, fmt.Sprintf("UnpackInterfaces inside msg: %s", err)) + return nil, errorsmod.Wrap(types.ErrInvalidMsg, fmt.Sprintf("UnpackInterfaces inside msg: %s", err)) } return []sdk.Msg{sdkMsg}, nil } @@ -237,6 +239,24 @@ func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, 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(), @@ -259,7 +279,7 @@ func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, } return []sdk.Msg{&sdkMsg}, nil default: - return nil, sdkerrors.Wrap(types.ErrUnknownMsg, "unknown variant of Wasm") + return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Wasm") } } @@ -275,7 +295,7 @@ func EncodeIBCMsg(portSource types.ICS20TransferPortSource) func(ctx sdk.Context case msg.Transfer != nil: amount, err := ConvertWasmCoinToSdkCoin(msg.Transfer.Amount) if err != nil { - return nil, sdkerrors.Wrap(err, "amount") + return nil, errorsmod.Wrap(err, "amount") } msg := &ibctransfertypes.MsgTransfer{ SourcePort: portSource.GetPort(ctx), @@ -288,29 +308,56 @@ func EncodeIBCMsg(portSource types.ICS20TransferPortSource) func(ctx sdk.Context } return []sdk.Msg{msg}, nil default: - return nil, sdkerrors.Wrap(types.ErrUnknownMsg, "Unknown variant of IBC") + return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of IBC") } } } func EncodeGovMsg(sender sdk.AccAddress, msg *wasmvmtypes.GovMsg) ([]sdk.Msg, error) { - var option govtypes.VoteOption - switch msg.Vote.Vote { + 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 = govtypes.OptionYes + option = v1.OptionYes case wasmvmtypes.No: - option = govtypes.OptionNo + option = v1.OptionNo case wasmvmtypes.NoWithVeto: - option = govtypes.OptionNoWithVeto + option = v1.OptionNoWithVeto case wasmvmtypes.Abstain: - option = govtypes.OptionAbstain - } - vote := &govtypes.MsgVote{ - ProposalId: msg.Vote.ProposalId, - Voter: sender.String(), - Option: option, + option = v1.OptionAbstain + default: + return v1.OptionEmpty, types.ErrInvalid } - return []sdk.Msg{vote}, nil + return option, nil } // ConvertWasmIBCTimeoutHeightToCosmosHeight converts a wasmvm type ibc timeout height to ibc module type height @@ -329,17 +376,16 @@ func ConvertWasmCoinsToSdkCoins(coins []wasmvmtypes.Coin) (sdk.Coins, error) { if err != nil { return nil, err } - toSend = append(toSend, c) + toSend = toSend.Add(c) } - toSend.Sort() - return toSend, nil + 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{}, sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, coin.Amount+coin.Denom) + return sdk.Coin{}, errorsmod.Wrap(sdkerrors.ErrInvalidCoins, coin.Amount+coin.Denom) } r := sdk.Coin{ Denom: coin.Denom, diff --git a/x/wasm/keeper/handler_plugin_encoders_test.go b/x/wasm/keeper/handler_plugin_encoders_test.go index ececbde..9d19721 100644 --- a/x/wasm/keeper/handler_plugin_encoders_test.go +++ b/x/wasm/keeper/handler_plugin_encoders_test.go @@ -3,19 +3,19 @@ package keeper import ( "testing" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - "github.com/golang/protobuf/proto" - "github.com/stretchr/testify/assert" - 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" @@ -50,7 +50,7 @@ func TestEncoding(t *testing.T) { content, err := codectypes.NewAnyWithValue(types.StoreCodeProposalFixture()) require.NoError(t, err) - proposalMsg := &govtypes.MsgSubmitProposal{ + proposalMsg := &v1beta1.MsgSubmitProposal{ Proposer: addr1.String(), InitialDeposit: sdk.NewCoins(sdk.NewInt64Coin("uatom", 12345)), Content: content, @@ -65,8 +65,10 @@ func TestEncoding(t *testing.T) { transferPortSource types.ICS20TransferPortSource // set if valid output []sdk.Msg - // set if invalid - isError bool + // set if expect mapping fails + expError bool + // set if sdk validate basic should fail + expInvalid bool }{ "simple send": { sender: addr1, @@ -113,7 +115,7 @@ func TestEncoding(t *testing.T) { }, }, }, - isError: true, + expError: true, }, "invalid address": { sender: addr1, @@ -130,7 +132,8 @@ func TestEncoding(t *testing.T) { }, }, }, - isError: false, // addresses are checked in the handler + expError: false, // addresses are checked in the handler + expInvalid: true, output: []sdk.Msg{ &banktypes.MsgSend{ FromAddress: addr1.String(), @@ -189,6 +192,35 @@ func TestEncoding(t *testing.T) { }, }, }, + "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{ @@ -271,7 +303,8 @@ func TestEncoding(t *testing.T) { }, }, }, - isError: false, // fails in the handler + expError: false, // fails in the handler + expInvalid: true, output: []sdk.Msg{ &stakingtypes.MsgDelegate{ DelegatorAddress: addr1.String(), @@ -378,7 +411,7 @@ func TestEncoding(t *testing.T) { Value: bankMsgBin, }, }, - isError: true, + expError: true, }, "IBC transfer with block timeout": { sender: addr1, @@ -500,69 +533,240 @@ func TestEncoding(t *testing.T) { }, }, }, + } + 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: addr1, - srcContractIBCPort: "myIBCPort", + sender: myAddr, srcMsg: wasmvmtypes.CosmosMsg{ Gov: &wasmvmtypes.GovMsg{ Vote: &wasmvmtypes.VoteMsg{ProposalId: 1, Vote: wasmvmtypes.Yes}, }, }, output: []sdk.Msg{ - &govtypes.MsgVote{ + &v1.MsgVote{ ProposalId: 1, - Voter: addr1.String(), - Option: govtypes.OptionYes, + Voter: myAddr.String(), + Option: v1.OptionYes, }, }, }, "Gov vote: No": { - sender: addr1, - srcContractIBCPort: "myIBCPort", + sender: myAddr, srcMsg: wasmvmtypes.CosmosMsg{ Gov: &wasmvmtypes.GovMsg{ Vote: &wasmvmtypes.VoteMsg{ProposalId: 1, Vote: wasmvmtypes.No}, }, }, output: []sdk.Msg{ - &govtypes.MsgVote{ + &v1.MsgVote{ ProposalId: 1, - Voter: addr1.String(), - Option: govtypes.OptionNo, + Voter: myAddr.String(), + Option: v1.OptionNo, }, }, }, "Gov vote: Abstain": { - sender: addr1, - srcContractIBCPort: "myIBCPort", + sender: myAddr, srcMsg: wasmvmtypes.CosmosMsg{ Gov: &wasmvmtypes.GovMsg{ Vote: &wasmvmtypes.VoteMsg{ProposalId: 10, Vote: wasmvmtypes.Abstain}, }, }, output: []sdk.Msg{ - &govtypes.MsgVote{ + &v1.MsgVote{ ProposalId: 10, - Voter: addr1.String(), - Option: govtypes.OptionAbstain, + Voter: myAddr.String(), + Option: v1.OptionAbstain, }, }, }, "Gov vote: No with veto": { - sender: addr1, - srcContractIBCPort: "myIBCPort", + sender: myAddr, srcMsg: wasmvmtypes.CosmosMsg{ Gov: &wasmvmtypes.GovMsg{ Vote: &wasmvmtypes.VoteMsg{ProposalId: 1, Vote: wasmvmtypes.NoWithVeto}, }, }, output: []sdk.Msg{ - &govtypes.MsgVote{ + &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: addr1.String(), - Option: govtypes.OptionNoWithVeto, + 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) @@ -570,12 +774,22 @@ func TestEncoding(t *testing.T) { 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.isError { - require.Error(t, err) - } else { - require.NoError(t, err) - assert.Equal(t, tc.output, res) + 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) + } } }) } @@ -635,3 +849,85 @@ func TestConvertWasmCoinToSdkCoin(t *testing.T) { }) } } + +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 index 1f1a839..42cc810 100644 --- a/x/wasm/keeper/handler_plugin_test.go +++ b/x/wasm/keeper/handler_plugin_test.go @@ -4,6 +4,9 @@ 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" @@ -11,9 +14,8 @@ import ( 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/v4/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - ibcexported "github.com/cosmos/ibc-go/v4/modules/core/exported" + 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" @@ -40,7 +42,7 @@ func TestMessageHandlerChainDispatch(t *testing.T) { myMsg := wasmvmtypes.CosmosMsg{Custom: []byte(`{}`)} specs := map[string]struct { handlers []Messenger - expErr *sdkerrors.Error + expErr *errorsmod.Error expEvents []sdk.Event }{ "single handler": { @@ -120,7 +122,7 @@ func TestSDKMessageHandlerDispatch(t *testing.T) { specs := map[string]struct { srcRoute MessageRouter srcEncoder CustomEncoder - expErr *sdkerrors.Error + expErr *errorsmod.Error expMsgDispatched int }{ "all good": { @@ -223,14 +225,18 @@ func TestSDKMessageHandlerDispatch(t *testing.T) { func TestIBCRawPacketHandler(t *testing.T) { ibcPort := "contractsIBCPort" - var ctx sdk.Context + ctx := sdk.Context{}.WithLogger(log.TestingLogger()) - var capturedPacket ibcexported.PacketI + type CapturedPacket struct { + sourcePort string + sourceChannel string + timeoutHeight clienttypes.Height + timeoutTimestamp uint64 + data []byte + } + var capturedPacket *CapturedPacket chanKeeper := &wasmtesting.MockChannelKeeper{ - GetNextSequenceSendFn: func(ctx sdk.Context, portID, channelID string) (uint64, bool) { - return 1, true - }, GetChannelFn: func(ctx sdk.Context, srcPort, srcChan string) (channeltypes.Channel, bool) { return channeltypes.Channel{ Counterparty: channeltypes.NewCounterparty( @@ -239,9 +245,15 @@ func TestIBCRawPacketHandler(t *testing.T) { ), }, true }, - SendPacketFn: func(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error { - capturedPacket = packet - return nil + 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{ @@ -254,8 +266,8 @@ func TestIBCRawPacketHandler(t *testing.T) { srcMsg wasmvmtypes.SendPacketMsg chanKeeper types.ChannelKeeper capKeeper types.CapabilityKeeper - expPacketSent channeltypes.Packet - expErr *sdkerrors.Error + expPacketSent *CapturedPacket + expErr *errorsmod.Error }{ "all good": { srcMsg: wasmvmtypes.SendPacketMsg{ @@ -265,29 +277,13 @@ func TestIBCRawPacketHandler(t *testing.T) { }, chanKeeper: chanKeeper, capKeeper: capKeeper, - expPacketSent: channeltypes.Packet{ - Sequence: 1, - SourcePort: ibcPort, - SourceChannel: "channel-1", - DestinationPort: "other-port", - DestinationChannel: "other-channel-1", - Data: []byte("myData"), - TimeoutHeight: clienttypes.Height{RevisionNumber: 1, RevisionHeight: 2}, + expPacketSent: &CapturedPacket{ + sourcePort: ibcPort, + sourceChannel: "channel-1", + timeoutHeight: clienttypes.Height{RevisionNumber: 1, RevisionHeight: 2}, + data: []byte("myData"), }, }, - "sequence not found returns error": { - srcMsg: wasmvmtypes.SendPacketMsg{ - ChannelID: "channel-1", - Data: []byte("myData"), - Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{Revision: 1, Height: 2}}, - }, - chanKeeper: &wasmtesting.MockChannelKeeper{ - GetNextSequenceSendFn: func(ctx sdk.Context, portID, channelID string) (uint64, bool) { - return 0, false - }, - }, - expErr: channeltypes.ErrSequenceSendNotFound, - }, "capability not found returns error": { srcMsg: wasmvmtypes.SendPacketMsg{ ChannelID: "channel-1", @@ -308,14 +304,23 @@ func TestIBCRawPacketHandler(t *testing.T) { capturedPacket = nil // when h := NewIBCRawPacketHandler(spec.chanKeeper, spec.capKeeper) - data, evts, gotErr := h.DispatchMsg(ctx, RandomAccountAddress(t), ibcPort, wasmvmtypes.CosmosMsg{IBC: &wasmvmtypes.IBCMsg{SendPacket: &spec.srcMsg}}) + 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, data) + 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) }) } @@ -400,7 +405,7 @@ func TestBurnCoinMessageHandlerIntegration(t *testing.T) { // 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) + diff := before.Supply.Sub(after.Supply...) assert.Equal(t, sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(100))), diff) }) } diff --git a/x/wasm/keeper/ibc.go b/x/wasm/keeper/ibc.go index 83a31ba..ff94048 100644 --- a/x/wasm/keeper/ibc.go +++ b/x/wasm/keeper/ibc.go @@ -3,10 +3,10 @@ package keeper import ( "strings" + errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - host "github.com/cosmos/ibc-go/v4/modules/core/24-host" + host "github.com/cosmos/ibc-go/v7/modules/core/24-host" "github.com/terpnetwork/terp-core/x/wasm/types" ) @@ -15,8 +15,8 @@ import ( // 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 { - cap := k.portKeeper.BindPort(ctx, portID) - return k.ClaimCapability(ctx, cap, host.PortPath(portID)) + 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 @@ -39,7 +39,7 @@ func PortIDForContract(addr sdk.AccAddress) string { func ContractFromPortID(portID string) (sdk.AccAddress, error) { if !strings.HasPrefix(portID, portIDPrefix) { - return nil, sdkerrors.Wrapf(types.ErrInvalid, "without prefix") + return nil, errorsmod.Wrapf(types.ErrInvalid, "without prefix") } return sdk.AccAddressFromBech32(portID[len(portIDPrefix):]) } diff --git a/x/wasm/keeper/keeper.go b/x/wasm/keeper/keeper.go index 0fea265..f5d5c4d 100644 --- a/x/wasm/keeper/keeper.go +++ b/x/wasm/keeper/keeper.go @@ -7,14 +7,17 @@ import ( "encoding/hex" "fmt" "math" - "path/filepath" "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" @@ -22,8 +25,6 @@ import ( 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" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/tendermint/tendermint/libs/log" "github.com/terpnetwork/terp-core/x/wasm/ioutils" "github.com/terpnetwork/terp-core/x/wasm/types" @@ -77,7 +78,7 @@ type WasmVMResponseHandler interface { ) ([]byte, error) } -// list of account types that are accepted for wasm contracts. Chains importing terpd +// 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{}): {}, @@ -85,7 +86,7 @@ var defaultAcceptedAccountTypes = map[reflect.Type]struct{}{ // Keeper will have a reference to Wasmer with it's own data directory. type Keeper struct { - storeKey sdk.StoreKey + storeKey storetypes.StoreKey cdc codec.Codec accountKeeper types.AccountKeeper bank CoinTransferrer @@ -97,94 +98,60 @@ type Keeper struct { messenger Messenger // queryGasLimit is the max wasmvm gas that can be spent on executing a query with a contract queryGasLimit uint64 - paramSpace paramtypes.Subspace gasRegister GasRegister maxQueryStackSize uint32 acceptedAccountTypes map[reflect.Type]struct{} accountPruner AccountPruner -} - -// 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 sdk.StoreKey, - paramSpace paramtypes.Subspace, - accountKeeper types.AccountKeeper, - bankKeeper types.BankKeeper, - stakingKeeper types.StakingKeeper, - distKeeper types.DistributionKeeper, - channelKeeper types.ChannelKeeper, - portKeeper types.PortKeeper, - capabilityKeeper types.CapabilityKeeper, - portSource types.ICS20TransferPortSource, - router MessageRouter, - _ GRPCQueryRouter, - homeDir string, - wasmConfig types.WasmConfig, - availableCapabilities string, - opts ...Option, -) Keeper { - wasmer, err := wasmvm.NewVM(filepath.Join(homeDir, "wasm"), availableCapabilities, contractMemoryLimit, wasmConfig.ContractDebugMode, wasmConfig.MemoryCacheSize) - if err != nil { - panic(err) - } - // set KeyTable if it has not already been set - if !paramSpace.HasKeyTable() { - paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) - } - - 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, - paramSpace: paramSpace, - gasRegister: NewDefaultWasmGasRegister(), - maxQueryStackSize: types.DefaultMaxQueryStackSize, - acceptedAccountTypes: defaultAcceptedAccountTypes, - } - keeper.wasmVMQueryHandler = DefaultQueryPlugins(bankKeeper, stakingKeeper, distKeeper, channelKeeper, keeper) - for _, o := range opts { - o.apply(keeper) - } - // not updateable, yet - keeper.wasmVMResponseHandler = NewDefaultWasmVMContractResponseHandler(NewMessageDispatcher(keeper.messenger, keeper)) - return *keeper + // 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 { - var a types.AccessConfig - k.paramSpace.Get(ctx, types.ParamStoreKeyUploadAccess, &a) - return a + return k.GetParams(ctx).CodeUploadAccess } func (k Keeper) getInstantiateAccessConfig(ctx sdk.Context) types.AccessType { - var a types.AccessType - k.paramSpace.Get(ctx, types.ParamStoreKeyInstantiateAccess, &a) - return a + 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 - k.paramSpace.GetParamSet(ctx, ¶ms) + store := ctx.KVStore(k.storeKey) + bz := store.Get(types.ParamsKey) + if bz == nil { + return params + } + + k.cdc.MustUnmarshal(bz, ¶ms) return params } -func (k Keeper) SetParams(ctx sdk.Context, ps types.Params) { - k.paramSpace.SetParamSet(ctx, &ps) +// 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, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "cannot be nil") + return 0, checksum, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "cannot be nil") } // figure out proper instantiate access @@ -198,25 +165,25 @@ func (k Keeper) create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, } if !authZ.CanCreateCode(chainConfigs, creator, *instantiateAccess) { - return 0, checksum, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not create code") + 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, sdkerrors.Wrap(types.ErrCreateFailed, err.Error()) + 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, sdkerrors.Wrap(types.ErrCreateFailed, err.Error()) + return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error()) } report, err := k.wasmVM.AnalyzeCode(checksum) if err != nil { - return 0, checksum, sdkerrors.Wrap(types.ErrCreateFailed, err.Error()) + 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) @@ -247,21 +214,21 @@ func (k Keeper) importCode(ctx sdk.Context, codeID uint64, codeInfo types.CodeIn var err error wasmCode, err = ioutils.Uncompress(wasmCode, uint64(types.MaxWasmSize)) if err != nil { - return sdkerrors.Wrap(types.ErrCreateFailed, err.Error()) + return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) } } newCodeHash, err := k.wasmVM.Create(wasmCode) if err != nil { - return sdkerrors.Wrap(types.ErrCreateFailed, err.Error()) + return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) } if !bytes.Equal(codeInfo.CodeHash, newCodeHash) { - return sdkerrors.Wrap(types.ErrInvalid, "code hashes not same") + return errorsmod.Wrap(types.ErrInvalid, "code hashes not same") } store := ctx.KVStore(k.storeKey) key := types.GetCodeKey(codeID) if store.Has(key) { - return sdkerrors.Wrapf(types.ErrDuplicate, "duplicate code: %d", codeID) + return errorsmod.Wrapf(types.ErrDuplicate, "duplicate code: %d", codeID) } // 0x01 | codeID (uint64) -> ContractInfo store.Set(key, k.cdc.MustMarshal(&codeInfo)) @@ -286,13 +253,12 @@ func (k Keeper) instantiate( instanceCosts := k.gasRegister.NewContractInstanceCosts(k.IsPinnedCode(ctx, codeID), len(initMsg)) ctx.GasMeter().ConsumeGas(instanceCosts, "Loading CosmWasm module: instantiate") - // get contact info codeInfo := k.GetCodeInfo(ctx, codeID) if codeInfo == nil { - return nil, nil, sdkerrors.Wrap(types.ErrNotFound, "code") + return nil, nil, errorsmod.Wrap(types.ErrNotFound, "code") } if !authPolicy.CanInstantiateContract(codeInfo.InstantiateConfig, creator) { - return nil, nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate") + return nil, nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not instantiate") } contractAddress := addressGenerator(ctx, codeID, codeInfo.CodeHash) @@ -315,14 +281,14 @@ func (k Keeper) instantiate( // 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 terpd namespace spam and overwrite it. + // 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, sdkerrors.Wrap(err, "prune balance") + return nil, nil, errorsmod.Wrap(err, "prune balance") case !handled: return nil, nil, types.ErrAccountExists.Wrap("address is claimed by external account") } @@ -346,17 +312,17 @@ func (k Keeper) instantiate( // create prefixed data store // 0x03 | BuildContractAddressClassic (sdk.AccAddress) prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) + 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, prefixStore, cosmwasmAPI, querier, k.gasMeter(ctx), gas, costJSONDeserialization) + 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, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error()) + return nil, nil, errorsmod.Wrap(types.ErrInstantiateFailed, err.Error()) } // persist instance first @@ -366,7 +332,7 @@ func (k Keeper) instantiate( // check for IBC flag report, err := k.wasmVM.AnalyzeCode(codeInfo.CodeHash) if err != nil { - return nil, nil, sdkerrors.Wrap(types.ErrInstantiateFailed, err.Error()) + return nil, nil, errorsmod.Wrap(types.ErrInstantiateFailed, err.Error()) } if report.HasIBCEntryPoints { // register IBC port @@ -392,7 +358,7 @@ func (k Keeper) instantiate( data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) if err != nil { - return nil, nil, sdkerrors.Wrap(err, "dispatch") + return nil, nil, errorsmod.Wrap(err, "dispatch") } return contractAddress, data, nil @@ -425,7 +391,7 @@ func (k Keeper) execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller 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, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) + return nil, errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) } ctx.EventManager().EmitEvent(sdk.NewEvent( @@ -435,7 +401,7 @@ func (k Keeper) execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) if err != nil { - return nil, sdkerrors.Wrap(err, "dispatch") + return nil, errorsmod.Wrap(err, "dispatch") } return data, nil @@ -448,28 +414,28 @@ func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller contractInfo := k.GetContractInfo(ctx, contractAddress) if contractInfo == nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract") + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract") } if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not migrate") + return nil, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not migrate") } newCodeInfo := k.GetCodeInfo(ctx, newCodeID) if newCodeInfo == nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "unknown code") + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown code") } if !authZ.CanInstantiateContract(newCodeInfo.InstantiateConfig, caller) { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "to use new code") + 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, sdkerrors.Wrap(types.ErrMigrationFailed, err.Error()) + return nil, errorsmod.Wrap(types.ErrMigrationFailed, err.Error()) case !report.HasIBCEntryPoints && contractInfo.IBCPortID != "": // prevent update to non ibc contract - return nil, sdkerrors.Wrap(types.ErrMigrationFailed, "requires ibc callbacks") + return nil, errorsmod.Wrap(types.ErrMigrationFailed, "requires ibc callbacks") case report.HasIBCEntryPoints && contractInfo.IBCPortID == "": // add ibc port ibcPort, err := k.ensureIbcPort(ctx, contractAddress) @@ -485,12 +451,12 @@ func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller querier := k.newQueryHandler(ctx, contractAddress) prefixStoreKey := types.GetContractStorePrefix(contractAddress) - prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey) + vmStore := types.NewStoreAdapter(prefix.NewStore(ctx.KVStore(k.storeKey), prefixStoreKey)) gas := k.runtimeGasForContract(ctx) - res, gasUsed, err := k.wasmVM.Migrate(newCodeInfo.CodeHash, env, msg, &prefixStore, cosmwasmAPI, &querier, k.gasMeter(ctx), gas, costJSONDeserialization) + 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, sdkerrors.Wrap(types.ErrMigrationFailed, err.Error()) + return nil, errorsmod.Wrap(types.ErrMigrationFailed, err.Error()) } // delete old secondary index entry k.removeFromContractCodeSecondaryIndex(ctx, contractAddress, k.getLastContractHistoryEntry(ctx, contractAddress)) @@ -508,7 +474,7 @@ func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) if err != nil { - return nil, sdkerrors.Wrap(err, "dispatch") + return nil, errorsmod.Wrap(err, "dispatch") } return data, nil @@ -535,7 +501,7 @@ func (k Keeper) Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte 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, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) + return nil, errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) } ctx.EventManager().EmitEvent(sdk.NewEvent( @@ -545,7 +511,7 @@ func (k Keeper) Sudo(ctx sdk.Context, contractAddress sdk.AccAddress, msg []byte data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) if err != nil { - return nil, sdkerrors.Wrap(err, "dispatch") + return nil, errorsmod.Wrap(err, "dispatch") } return data, nil @@ -571,7 +537,7 @@ func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply was 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, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) + return nil, errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) } ctx.EventManager().EmitEvent(sdk.NewEvent( @@ -581,7 +547,7 @@ func (k Keeper) reply(ctx sdk.Context, contractAddress sdk.AccAddress, reply was data, err := k.handleContractResponse(ctx, contractAddress, contractInfo.IBCPortID, res.Messages, res.Attributes, res.Data, res.Events) if err != nil { - return nil, sdkerrors.Wrap(err, "dispatch") + return nil, errorsmod.Wrap(err, "dispatch") } return data, nil @@ -632,13 +598,20 @@ func (k Keeper) IterateContractsByCode(ctx sdk.Context, codeID uint64, cb func(a func (k Keeper) setContractAdmin(ctx sdk.Context, contractAddress, caller, newAdmin sdk.AccAddress, authZ AuthorizationPolicy) error { contractInfo := k.GetContractInfo(ctx, contractAddress) if contractInfo == nil { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "unknown contract") } if !authZ.CanModifyContract(contractInfo.AdminAddr(), caller) { - return sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not modify contract") + return errorsmod.Wrap(sdkerrors.ErrUnauthorized, "can not modify contract") } - contractInfo.Admin = newAdmin.String() + 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 } @@ -715,7 +688,7 @@ func (k Keeper) QuerySmart(ctx sdk.Context, contractAddr sdk.AccAddress, req []b 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, sdkerrors.Wrap(types.ErrQueryFailed, qErr.Error()) + return nil, errorsmod.Wrap(types.ErrQueryFailed, qErr.Error()) } return queryResult, nil } @@ -755,25 +728,26 @@ func (k Keeper) QueryRaw(ctx sdk.Context, contractAddress sdk.AccAddress, key [] return prefixStore.Get(key) } -func (k Keeper) contractInstance(ctx sdk.Context, contractAddress sdk.AccAddress) (types.ContractInfo, types.CodeInfo, prefix.Store, error) { +// 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{}, prefix.Store{}, sdkerrors.Wrap(types.ErrNotFound, "contract") + 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{}, prefix.Store{}, sdkerrors.Wrap(types.ErrNotFound, "code info") + 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, prefixStore, nil + return contractInfo, codeInfo, types.NewStoreAdapter(prefixStore), nil } func (k Keeper) GetContractInfo(ctx sdk.Context, contractAddress sdk.AccAddress) *types.ContractInfo { @@ -836,7 +810,7 @@ func (k Keeper) importContractState(ctx sdk.Context, contractAddress sdk.AccAddr model.Value = []byte{} } if prefixStore.Has(model.Key) { - return sdkerrors.Wrapf(types.ErrDuplicate, "duplicate key: %x", model.Key) + return errorsmod.Wrapf(types.ErrDuplicate, "duplicate key: %x", model.Key) } prefixStore.Set(model.Key, model.Value) } @@ -889,11 +863,11 @@ func (k Keeper) GetByteCode(ctx sdk.Context, codeID uint64) ([]byte, error) { func (k Keeper) pinCode(ctx sdk.Context, codeID uint64) error { codeInfo := k.GetCodeInfo(ctx, codeID) if codeInfo == nil { - return sdkerrors.Wrap(types.ErrNotFound, "code info") + return errorsmod.Wrap(types.ErrNotFound, "code info") } if err := k.wasmVM.Pin(codeInfo.CodeHash); err != nil { - return sdkerrors.Wrap(types.ErrPinContractFailed, err.Error()) + return errorsmod.Wrap(types.ErrPinContractFailed, err.Error()) } store := ctx.KVStore(k.storeKey) // store 1 byte to not run into `nil` debugging issues @@ -910,10 +884,10 @@ func (k Keeper) pinCode(ctx sdk.Context, codeID uint64) error { func (k Keeper) unpinCode(ctx sdk.Context, codeID uint64) error { codeInfo := k.GetCodeInfo(ctx, codeID) if codeInfo == nil { - return sdkerrors.Wrap(types.ErrNotFound, "code info") + return errorsmod.Wrap(types.ErrNotFound, "code info") } if err := k.wasmVM.Unpin(codeInfo.CodeHash); err != nil { - return sdkerrors.Wrap(types.ErrUnpinContractFailed, err.Error()) + return errorsmod.Wrap(types.ErrUnpinContractFailed, err.Error()) } store := ctx.KVStore(k.storeKey) @@ -941,10 +915,10 @@ func (k Keeper) InitializePinnedCodes(ctx sdk.Context) error { for ; iter.Valid(); iter.Next() { codeInfo := k.GetCodeInfo(ctx, types.ParsePinnedCodeIndex(iter.Key())) if codeInfo == nil { - return sdkerrors.Wrap(types.ErrNotFound, "code info") + return errorsmod.Wrap(types.ErrNotFound, "code info") } if err := k.wasmVM.Pin(codeInfo.CodeHash); err != nil { - return sdkerrors.Wrap(types.ErrPinContractFailed, err.Error()) + return errorsmod.Wrap(types.ErrPinContractFailed, err.Error()) } } return nil @@ -954,7 +928,7 @@ func (k Keeper) InitializePinnedCodes(ctx sdk.Context) error { func (k Keeper) setContractInfoExtension(ctx sdk.Context, contractAddr sdk.AccAddress, ext types.ContractInfoExtension) error { info := k.GetContractInfo(ctx, contractAddr) if info == nil { - return sdkerrors.Wrap(types.ErrNotFound, "contract info") + return errorsmod.Wrap(types.ErrNotFound, "contract info") } if err := info.SetExtension(ext); err != nil { return err @@ -967,15 +941,25 @@ func (k Keeper) setContractInfoExtension(ctx sdk.Context, contractAddr sdk.AccAd 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 sdkerrors.Wrap(types.ErrNotFound, "code info") + return errorsmod.Wrap(types.ErrNotFound, "code info") } isSubset := newConfig.Permission.IsSubset(k.getInstantiateAccessConfig(ctx)) if !authz.CanModifyCodeAccessConfig(sdk.MustAccAddressFromBech32(info.Creator), caller, isSubset) { - return sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "can not modify code access config") + 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 } @@ -1014,7 +998,7 @@ func (k Keeper) runtimeGasForContract(ctx sdk.Context) uint64 { if meter.IsOutOfGas() { return 0 } - if meter.Limit() == 0 { // infinite gas meter with limit=0 and not out of gas + if meter.Limit() == math.MaxUint64 { // infinite gas meter and not out of gas return math.MaxUint64 } return k.gasRegister.ToWasmVMGas(meter.Limit() - meter.GasConsumedToLimit()) @@ -1055,7 +1039,7 @@ func (k Keeper) PeekAutoIncrementID(ctx sdk.Context, lastIDKey []byte) uint64 { func (k Keeper) importAutoIncrementID(ctx sdk.Context, lastIDKey []byte, val uint64) error { store := ctx.KVStore(k.storeKey) if store.Has(lastIDKey) { - return sdkerrors.Wrapf(types.ErrDuplicate, "autoincrement id: %s", string(lastIDKey)) + return errorsmod.Wrapf(types.ErrDuplicate, "autoincrement id: %s", string(lastIDKey)) } bz := sdk.Uint64ToBigEndian(val) store.Set(lastIDKey, bz) @@ -1064,10 +1048,10 @@ func (k Keeper) importAutoIncrementID(ctx sdk.Context, lastIDKey []byte, val uin 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 sdkerrors.Wrapf(types.ErrNotFound, "code id: %d", c.CodeID) + return errorsmod.Wrapf(types.ErrNotFound, "code id: %d", c.CodeID) } if k.HasContractInfo(ctx, contractAddr) { - return sdkerrors.Wrapf(types.ErrDuplicate, "contract: %s", contractAddr) + return errorsmod.Wrapf(types.ErrDuplicate, "contract: %s", contractAddr) } creatorAddress, err := sdk.AccAddressFromBech32(c.Creator) @@ -1116,7 +1100,7 @@ func moduleLogger(ctx sdk.Context) log.Logger { } // Querier creates a new grpc querier instance -func Querier(k *Keeper) *grpcQuerier { //nolint:revive +func Querier(k *Keeper) *GrpcQuerier { return NewGrpcQuerier(k.cdc, k.storeKey, k, k.queryGasLimit) } @@ -1146,7 +1130,7 @@ func (c BankCoinTransferrer) TransferCoins(parentCtx sdk.Context, fromAddr sdk.A return err } if c.keeper.BlockedAddr(toAddr) { - return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", toAddr.String()) + return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is not allowed to receive funds", toAddr.String()) } sdkerr := c.keeper.SendCoins(ctx, fromAddr, toAddr, amount) @@ -1191,10 +1175,10 @@ func (b VestingCoinBurner) CleanupExistingAccount(ctx sdk.Context, existingAcc a 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, sdkerrors.Wrap(err, "prune account balance") + return false, errorsmod.Wrap(err, "prune account balance") } if err := b.bank.BurnCoins(ctx, types.ModuleName, coinsToBurn); err != nil { - return false, sdkerrors.Wrap(err, "burn account balance") + return false, errorsmod.Wrap(err, "burn account balance") } return true, nil } @@ -1219,7 +1203,7 @@ func (h DefaultWasmVMContractResponseHandler) Handle(ctx sdk.Context, contractAd result := origRspData switch rsp, err := h.md.DispatchSubmessages(ctx, contractAddr, ibcPort, messages); { case err != nil: - return nil, sdkerrors.Wrap(err, "submessages") + return nil, errorsmod.Wrap(err, "submessages") case rsp != nil: result = rsp } diff --git a/x/wasm/keeper/keeper_cgo.go b/x/wasm/keeper/keeper_cgo.go new file mode 100644 index 0000000..64c94f3 --- /dev/null +++ b/x/wasm/keeper/keeper_cgo.go @@ -0,0 +1,65 @@ +//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 new file mode 100644 index 0000000..2c45dbc --- /dev/null +++ b/x/wasm/keeper/keeper_no_cgo.go @@ -0,0 +1,34 @@ +//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 index d194135..61a317d 100644 --- a/x/wasm/keeper/keeper_test.go +++ b/x/wasm/keeper/keeper_test.go @@ -7,11 +7,17 @@ import ( "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" @@ -26,8 +32,6 @@ import ( fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/rand" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" "github.com/terpnetwork/terp-core/x/wasm/types" @@ -59,7 +63,7 @@ func TestCreateSuccess(t *testing.T) { require.NoError(t, err) require.Equal(t, hackatomWasm, storedCode) // and events emitted - codeHash := "13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5" + 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()) } @@ -120,10 +124,11 @@ func TestCreateStoresInstantiatePermission(t *testing.T) { t.Run(msg, func(t *testing.T) { ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.ContractKeeper, keepers.BankKeeper - keepers.WasmKeeper.SetParams(ctx, types.Params{ + 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) @@ -145,7 +150,7 @@ func TestCreateWithParamPermissions(t *testing.T) { specs := map[string]struct { policy AuthorizationPolicy chainUpload types.AccessConfig - expError *sdkerrors.Error + expError *errorsmod.Error }{ "default": { policy: DefaultAuthorizationPolicy{}, @@ -178,9 +183,10 @@ func TestCreateWithParamPermissions(t *testing.T) { t.Run(msg, func(t *testing.T) { params := types.DefaultParams() params.CodeUploadAccess = spec.chainUpload - keepers.WasmKeeper.SetParams(ctx, params) + err := keepers.WasmKeeper.SetParams(ctx, params) + require.NoError(t, err) keeper := NewPermissionedKeeper(keepers.WasmKeeper, spec.policy) - _, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) + _, _, err = keeper.Create(ctx, creator, hackatomWasm, nil) require.True(t, spec.expError.Is(err), err) if spec.expError != nil { return @@ -209,7 +215,7 @@ func TestEnforceValidPermissionsOnCreate(t *testing.T) { // grantedPermission is set iff no error grantedPermission types.AccessConfig // expError is nil iff the request is allowed - expError *sdkerrors.Error + expError *errorsmod.Error }{ "override everybody": { defaultPermssion: types.AccessTypeEverybody, @@ -256,7 +262,8 @@ func TestEnforceValidPermissionsOnCreate(t *testing.T) { t.Run(msg, func(t *testing.T) { params := types.DefaultParams() params.InstantiateDefaultPermission = spec.defaultPermssion - keeper.SetParams(ctx, params) + 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 { @@ -409,7 +416,7 @@ func TestInstantiate(t *testing.T) { gasAfter := ctx.GasMeter().GasConsumed() if types.EnableGasVerification { - require.Equal(t, uint64(0x1a7bb), gasAfter-gasBefore) + require.Equal(t, uint64(0x1b5bc), gasAfter-gasBefore) } // ensure it is stored properly @@ -508,7 +515,7 @@ func TestInstantiateWithPermissions(t *testing.T) { specs := map[string]struct { srcPermission types.AccessConfig srcActor sdk.AccAddress - expError *sdkerrors.Error + expError *errorsmod.Error }{ "default": { srcPermission: types.DefaultUploadAccess, @@ -556,7 +563,6 @@ func TestInstantiateWithAccounts(t *testing.T) { senderAddr := DeterministicAccountAddress(t, 1) keepers.Faucet.Fund(parentCtx, senderAddr, sdk.NewInt64Coin("denom", 100000000)) - const myLabel = "testing" mySalt := []byte(`my salt`) contractAddr := BuildContractAddressPredictable(example.Checksum, senderAddr, mySalt, []byte{}) @@ -667,7 +673,7 @@ func TestInstantiateWithAccounts(t *testing.T) { } }() // when - gotAddr, _, gotErr := keepers.ContractKeeper.Instantiate2(ctx, 1, senderAddr, nil, initMsg, myLabel, spec.deposit, mySalt, false) + 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 @@ -724,7 +730,7 @@ func TestInstantiateWithContractFactoryChildQueriesParent(t *testing.T) { // 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/CosmWasm/wasmd/issues/896 + // see also: https://github.com/terpnetwork/terp-core/issues/896 ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) keeper := keepers.WasmKeeper @@ -745,7 +751,7 @@ func TestInstantiateWithContractFactoryChildQueriesParent(t *testing.T) { // overwrite wasmvm in router router := baseapp.NewMsgServiceRouter() router.SetInterfaceRegistry(keepers.EncodingConfig.InterfaceRegistry) - types.RegisterMsgServer(router, NewMsgServerImpl(NewDefaultPermissionKeeper(keeper))) + 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)) @@ -835,7 +841,7 @@ func TestExecute(t *testing.T) { // unauthorized - trialCtx so we don't change state trialCtx := ctx.WithMultiStore(ctx.MultiStore().CacheWrap().(sdk.MultiStore)) - res, err := keepers.ContractKeeper.Execute(trialCtx, addr, creator, []byte(`{"release":{}}`), nil) + _, 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()) @@ -845,15 +851,15 @@ func TestExecute(t *testing.T) { gasBefore := ctx.GasMeter().GasConsumed() em := sdk.NewEventManager() // when - res, err = keepers.ContractKeeper.Execute(ctx.WithEventManager(em), addr, fred, []byte(`{"release":{}}`), topUp) - diff := time.Now().Sub(start) + 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(0x17d87), gasAfter-gasBefore) + require.Equal(t, uint64(0x1a154), gasAfter-gasBefore) } // ensure bob now exists and got both payments released bobAcct = accKeeper.GetAccount(ctx, bob) @@ -935,7 +941,8 @@ func TestExecuteWithDeposit(t *testing.T) { ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.ContractKeeper if spec.newBankParams != nil { - bankKeeper.SetParams(ctx, *spec.newBankParams) + 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))) @@ -992,7 +999,7 @@ func TestExecuteWithPanic(t *testing.T) { contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) require.NoError(t, err) - _, _, bob := keyPubAddr() + _, bob := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, @@ -1008,7 +1015,7 @@ func TestExecuteWithPanic(t *testing.T) { 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: unreachable") + 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) { @@ -1024,7 +1031,7 @@ func TestExecuteWithCpuLoop(t *testing.T) { contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) require.NoError(t, err) - _, _, bob := keyPubAddr() + _, bob := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, @@ -1049,12 +1056,13 @@ func TestExecuteWithCpuLoop(t *testing.T) { }() // this should throw out of gas exception (panic) - _, err = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"cpu_loop":{}}`), nil) + _, _ = 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)) @@ -1066,7 +1074,7 @@ func TestExecuteWithStorageLoop(t *testing.T) { contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) require.NoError(t, err) - _, _, bob := keyPubAddr() + _, bob := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, @@ -1091,7 +1099,7 @@ func TestExecuteWithStorageLoop(t *testing.T) { }() // this should throw out of gas exception (panic) - _, err = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"storage_loop":{}}`), nil) + _, _ = keepers.ContractKeeper.Execute(ctx, addr, fred, []byte(`{"storage_loop":{}}`), nil) require.True(t, false, "We must panic before this line") } @@ -1135,7 +1143,7 @@ func TestMigrate(t *testing.T) { fromCodeID uint64 toCodeID uint64 migrateMsg []byte - expErr *sdkerrors.Error + expErr *errorsmod.Error expVerifier sdk.AccAddress expIBCPort bool initMsg []byte @@ -1346,7 +1354,7 @@ func TestMigrateWithDispatchedMessage(t *testing.T) { require.NoError(t, err) require.NotEqual(t, originalContractID, burnerContractID) - _, _, myPayoutAddr := keyPubAddr() + _, myPayoutAddr := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: fred, @@ -1510,8 +1518,8 @@ func TestSudo(t *testing.T) { contractID, _, err := keeper.Create(ctx, creator, hackatomWasm, nil) require.NoError(t, err) - _, _, bob := keyPubAddr() - _, _, fred := keyPubAddr() + _, bob := keyPubAddr() + _, fred := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, @@ -1523,7 +1531,7 @@ func TestSudo(t *testing.T) { require.Equal(t, "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr", addr.String()) // the community is broke - _, _, community := keyPubAddr() + _, community := keyPubAddr() comAcct := accKeeper.GetAccount(ctx, community) require.Nil(t, comAcct) @@ -1569,7 +1577,7 @@ func prettyEvents(t *testing.T, events sdk.Events) string { for i, e := range events { attr := make([]map[string]string, len(e.Attributes)) for j, a := range e.Attributes { - attr[j] = map[string]string{string(a.Key): string(a.Value)} + attr[j] = map[string]string{a.Key: a.Value} } r[i] = prettyEvent{Type: e.Type, Attr: attr} } @@ -1596,7 +1604,7 @@ func TestUpdateContractAdmin(t *testing.T) { originalContractID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) require.NoError(t, err) - _, _, anyAddr := keyPubAddr() + _, anyAddr := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: anyAddr, @@ -1608,7 +1616,7 @@ func TestUpdateContractAdmin(t *testing.T) { newAdmin sdk.AccAddress overrideContractAddr sdk.AccAddress caller sdk.AccAddress - expErr *sdkerrors.Error + expErr *errorsmod.Error }{ "all good with admin set": { instAdmin: fred, @@ -1666,7 +1674,7 @@ func TestClearContractAdmin(t *testing.T) { originalContractID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) require.NoError(t, err) - _, _, anyAddr := keyPubAddr() + _, anyAddr := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: anyAddr, @@ -1677,7 +1685,7 @@ func TestClearContractAdmin(t *testing.T) { instAdmin sdk.AccAddress overrideContractAddr sdk.AccAddress caller sdk.AccAddress - expErr *sdkerrors.Error + expErr *errorsmod.Error }{ "all good when called by proper admin": { instAdmin: fred, @@ -2040,6 +2048,7 @@ func TestSetAccessConfig(t *testing.T) { k := keepers.WasmKeeper creatorAddr := RandomAccountAddress(t) nonCreatorAddr := RandomAccountAddress(t) + const codeID = 1 specs := map[string]struct { authz AuthorizationPolicy @@ -2047,18 +2056,27 @@ func TestSetAccessConfig(t *testing.T) { 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{}, @@ -2079,32 +2097,63 @@ func TestSetAccessConfig(t *testing.T) { 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", + }, }, } - const codeID = 1 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 - k.SetParams(ctx, newParams) + err := k.SetParams(ctx, newParams) + require.NoError(t, err) k.storeCodeInfo(ctx, codeID, types.NewCodeInfo(nil, creatorAddr, types.AllowNobody)) // when @@ -2114,6 +2163,10 @@ func TestSetAccessConfig(t *testing.T) { 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)) }) } } @@ -2152,15 +2205,19 @@ func TestCoinBurnerPruneBalances(t *testing.T) { setupAcc func(t *testing.T, ctx sdk.Context) authtypes.AccountI expBalances sdk.Coins expHandled bool - expErr *sdkerrors.Error + expErr *errorsmod.Error }{ "vesting account - all removed": { - setupAcc: func(t *testing.T, ctx sdk.Context) authtypes.AccountI { return myVestingAccount }, + setupAcc: func(t *testing.T, ctx sdk.Context) authtypes.AccountI { + t.Helper() + 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 { + t.Helper() keepers.Faucet.Fund(ctx, vestingAddr, sdk.NewCoin("other", sdk.NewInt(2))) return myVestingAccount }, @@ -2169,6 +2226,7 @@ func TestCoinBurnerPruneBalances(t *testing.T) { }, "non vesting account - not handled": { setupAcc: func(t *testing.T, ctx sdk.Context) authtypes.AccountI { + t.Helper() return &authtypes.BaseAccount{Address: myVestingAccount.GetAddress().String()} }, expBalances: sdk.NewCoins(sdk.NewCoin("denom", sdk.NewInt(100))), @@ -2230,8 +2288,9 @@ func TestIteratorContractByCreator(t *testing.T) { mockAddress3 := keepers.Faucet.NewFundedRandomAccount(parentCtx, topUp...) contract1ID, _, err := keeper.Create(parentCtx, creator, hackatomWasm, nil) - contract2ID, _, 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{ @@ -2287,3 +2346,77 @@ func TestIteratorContractByCreator(t *testing.T) { }) } } + +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/legacy_querier.go b/x/wasm/keeper/legacy_querier.go deleted file mode 100644 index d1018dc..0000000 --- a/x/wasm/keeper/legacy_querier.go +++ /dev/null @@ -1,154 +0,0 @@ -package keeper - -import ( - "encoding/json" - "reflect" - "strconv" - - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -const ( - QueryListContractByCode = "list-contracts-by-code" - QueryGetContract = "contract-info" - QueryGetContractState = "contract-state" - QueryGetCode = "code" - QueryListCode = "list-code" - QueryContractHistory = "contract-history" -) - -const ( - QueryMethodContractStateSmart = "smart" - QueryMethodContractStateAll = "all" - QueryMethodContractStateRaw = "raw" -) - -// NewLegacyQuerier creates a new querier -// Deprecated: the rest support will be removed. You can use the GRPC gateway instead -func NewLegacyQuerier(keeper types.ViewKeeper, gasLimit sdk.Gas) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - var ( - rsp interface{} - err error - ) - switch path[0] { - case QueryGetContract: - addr, addrErr := sdk.AccAddressFromBech32(path[1]) - if addrErr != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, addrErr.Error()) - } - rsp, err = queryContractInfo(ctx, addr, keeper) - case QueryListContractByCode: - codeID, parseErr := strconv.ParseUint(path[1], 10, 64) - if parseErr != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", parseErr.Error()) - } - rsp = queryContractListByCode(ctx, codeID, keeper) - case QueryGetContractState: - if len(path) < 3 { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint") - } - return queryContractState(ctx, path[1], path[2], req.Data, gasLimit, keeper) - case QueryGetCode: - codeID, parseErr := strconv.ParseUint(path[1], 10, 64) - if parseErr != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", parseErr.Error()) - } - rsp, err = queryCode(ctx, codeID, keeper) - case QueryListCode: - rsp, err = queryCodeList(ctx, keeper) - case QueryContractHistory: - contractAddr, addrErr := sdk.AccAddressFromBech32(path[1]) - if addrErr != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, addrErr.Error()) - } - rsp, err = queryContractHistory(ctx, contractAddr, keeper) - default: - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint") - } - if err != nil { - return nil, err - } - if rsp == nil || reflect.ValueOf(rsp).IsNil() { - return nil, nil - } - bz, err := json.MarshalIndent(rsp, "", " ") - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - } -} - -func queryContractState(ctx sdk.Context, bech, queryMethod string, data []byte, gasLimit sdk.Gas, keeper types.ViewKeeper) (json.RawMessage, error) { - contractAddr, err := sdk.AccAddressFromBech32(bech) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, bech) - } - - switch queryMethod { - case QueryMethodContractStateAll: - resultData := make([]types.Model, 0) - // this returns a serialized json object (which internally encoded binary fields properly) - keeper.IterateContractState(ctx, contractAddr, func(key, value []byte) bool { - resultData = append(resultData, types.Model{Key: key, Value: value}) - return false - }) - bz, err := json.Marshal(resultData) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil - case QueryMethodContractStateRaw: - // this returns the raw data from the state, base64-encoded - return keeper.QueryRaw(ctx, contractAddr, data), nil - case QueryMethodContractStateSmart: - // we enforce a subjective gas limit on all queries to avoid infinite loops - ctx = ctx.WithGasMeter(sdk.NewGasMeter(gasLimit)) - msg := types.RawContractMessage(data) - if err := msg.ValidateBasic(); err != nil { - return nil, sdkerrors.Wrap(err, "json msg") - } - // this returns raw bytes (must be base64-encoded) - bz, err := keeper.QuerySmart(ctx, contractAddr, msg) - return bz, err - default: - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, queryMethod) - } -} - -func queryCodeList(ctx sdk.Context, keeper types.ViewKeeper) ([]types.CodeInfoResponse, error) { - var info []types.CodeInfoResponse - keeper.IterateCodeInfos(ctx, func(i uint64, res types.CodeInfo) bool { - info = append(info, types.CodeInfoResponse{ - CodeID: i, - Creator: res.Creator, - DataHash: res.CodeHash, - InstantiatePermission: res.InstantiateConfig, - }) - return false - }) - return info, nil -} - -func queryContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress, keeper types.ViewKeeper) ([]types.ContractCodeHistoryEntry, error) { - history := keeper.GetContractHistory(ctx, contractAddr) - // redact response - for i := range history { - history[i].Updated = nil - } - return history, nil -} - -func queryContractListByCode(ctx sdk.Context, codeID uint64, keeper types.ViewKeeper) []string { - var contracts []string - keeper.IterateContractsByCode(ctx, codeID, func(addr sdk.AccAddress) bool { - contracts = append(contracts, addr.String()) - return false - }) - return contracts -} diff --git a/x/wasm/keeper/legacy_querier_test.go b/x/wasm/keeper/legacy_querier_test.go deleted file mode 100644 index b44dbb1..0000000 --- a/x/wasm/keeper/legacy_querier_test.go +++ /dev/null @@ -1,364 +0,0 @@ -package keeper - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "os" - "testing" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func TestLegacyQueryContractState(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit.Add(deposit...)...) - anyAddr := keepers.Faucet.NewFundedRandomAccount(ctx, sdk.NewInt64Coin("denom", 5000)) - - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - contractID, _, 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) - - addr, _, err := keepers.ContractKeeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract to query", deposit) - require.NoError(t, err) - - contractModel := []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - } - keeper.importContractState(ctx, addr, contractModel) - - // this gets us full error, not redacted sdk.Error - var defaultQueryGasLimit sdk.Gas = 3000000 - q := NewLegacyQuerier(keeper, defaultQueryGasLimit) - - specs := map[string]struct { - srcPath []string - srcReq abci.RequestQuery - // smart and raw queries (not all queries) return raw bytes from contract not []types.Model - // if this is set, then we just compare - (should be json encoded string) - expRes []byte - // if success and expSmartRes is not set, we parse into []types.Model and compare (all state) - expModelLen int - expModelContains []types.Model - expErr error - }{ - "query all": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateAll}, - expModelLen: 3, - expModelContains: []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - }, - }, - "query raw key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: []byte("foo")}, - expRes: []byte(`"bar"`), - }, - "query raw binary key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: []byte{0x0, 0x1}}, - expRes: []byte(`{"count":8}`), - }, - "query smart": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateSmart}, - srcReq: abci.RequestQuery{Data: []byte(`{"verifier":{}}`)}, - expRes: []byte(fmt.Sprintf(`{"verifier":"%s"}`, anyAddr.String())), - }, - "query smart invalid request": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateSmart}, - srcReq: abci.RequestQuery{Data: []byte(`{"raw":{"key":"config"}}`)}, - expErr: types.ErrQueryFailed, - }, - "query smart with invalid json": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateSmart}, - srcReq: abci.RequestQuery{Data: []byte(`not a json string`)}, - expErr: types.ErrInvalid, - }, - "query non-existent raw key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: []byte("i do not exist")}, - expRes: nil, - }, - "query empty raw key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: []byte("")}, - expRes: nil, - }, - "query nil raw key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: nil}, - expRes: nil, - }, - "query raw with unknown address": { - srcPath: []string{QueryGetContractState, anyAddr.String(), QueryMethodContractStateRaw}, - expRes: nil, - }, - "query all with unknown address": { - srcPath: []string{QueryGetContractState, anyAddr.String(), QueryMethodContractStateAll}, - expModelLen: 0, - }, - "query smart with unknown address": { - srcPath: []string{QueryGetContractState, anyAddr.String(), QueryMethodContractStateSmart}, - srcReq: abci.RequestQuery{Data: []byte(`{}`)}, - expModelLen: 0, - expErr: types.ErrNotFound, - }, - } - - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - binResult, err := q(ctx, spec.srcPath, spec.srcReq) - // require.True(t, spec.expErr.Is(err), "unexpected error") - require.True(t, errors.Is(err, spec.expErr), err) - - // if smart query, check custom response - if spec.srcPath[2] != QueryMethodContractStateAll { - require.Equal(t, spec.expRes, binResult) - return - } - - // otherwise, check returned models - var r []types.Model - if spec.expErr == nil { - require.NoError(t, json.Unmarshal(binResult, &r)) - require.NotNil(t, r) - } - require.Len(t, r, spec.expModelLen) - // and in result set - for _, v := range spec.expModelContains { - assert.Contains(t, r, v) - } - }) - } -} - -func TestLegacyQueryContractListByCodeOrdering(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.Add(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 := range [10]int{} { - // 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 - var defaultQueryGasLimit sdk.Gas = 3000000 - q := NewLegacyQuerier(keeper, defaultQueryGasLimit) - - query := []string{QueryListContractByCode, fmt.Sprintf("%d", codeID)} - data := abci.RequestQuery{} - res, err := q(ctx, query, data) - require.NoError(t, err) - - var contracts []string - err = json.Unmarshal(res, &contracts) - require.NoError(t, err) - - require.Equal(t, 10, len(contracts)) - - for _, contract := range contracts { - assert.NotEmpty(t, contract) - } -} - -func TestLegacyQueryContractHistory(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - var otherAddr sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - - specs := map[string]struct { - srcQueryAddr sdk.AccAddress - srcHistory []types.ContractCodeHistoryEntry - expContent []types.ContractCodeHistoryEntry - }{ - "response with internal fields cleared": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: []byte(`"init message"`), - }}, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Msg: []byte(`"init message"`), - }}, - }, - "response with multiple entries": { - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: []byte(`"init message"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: []byte(`"migrate message 1"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 3, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: []byte(`"migrate message 2"`), - }}, - expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeInit, - CodeID: firstCodeID, - Msg: []byte(`"init message"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 2, - Msg: []byte(`"migrate message 1"`), - }, { - Operation: types.ContractCodeHistoryOperationTypeMigrate, - CodeID: 3, - Msg: []byte(`"migrate message 2"`), - }}, - }, - "unknown contract address": { - srcQueryAddr: otherAddr, - srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.ContractCodeHistoryOperationTypeGenesis, - CodeID: firstCodeID, - Updated: types.NewAbsoluteTxPosition(ctx), - Msg: []byte(`"init message"`), - }}, - expContent: []types.ContractCodeHistoryEntry{}, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - _, _, myContractAddr := keyPubAddr() - keeper.appendToContractHistory(ctx, myContractAddr, spec.srcHistory...) - - var defaultQueryGasLimit sdk.Gas = 3000000 - q := NewLegacyQuerier(keeper, defaultQueryGasLimit) - queryContractAddr := spec.srcQueryAddr - if queryContractAddr == nil { - queryContractAddr = myContractAddr - } - - // when - query := []string{QueryContractHistory, queryContractAddr.String()} - data := abci.RequestQuery{} - resData, err := q(ctx, query, data) - - // then - require.NoError(t, err) - var got []types.ContractCodeHistoryEntry - err = json.Unmarshal(resData, &got) - require.NoError(t, err) - - assert.Equal(t, spec.expContent, got) - }) - } -} - -func TestLegacyQueryCodeList(t *testing.T) { - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - specs := map[string]struct { - codeIDs []uint64 - }{ - "none": {}, - "no gaps": { - codeIDs: []uint64{1, 2, 3}, - }, - "with gaps": { - codeIDs: []uint64{2, 4, 6}, - }, - } - - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) - keeper := keepers.WasmKeeper - - for _, codeID := range spec.codeIDs { - require.NoError(t, keeper.importCode(ctx, codeID, - types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)), - wasmCode), - ) - } - var defaultQueryGasLimit sdk.Gas = 3000000 - q := NewLegacyQuerier(keeper, defaultQueryGasLimit) - // when - query := []string{QueryListCode} - data := abci.RequestQuery{} - resData, err := q(ctx, query, data) - - // then - require.NoError(t, err) - if len(spec.codeIDs) == 0 { - require.Nil(t, resData) - return - } - - var got []map[string]interface{} - err = json.Unmarshal(resData, &got) - require.NoError(t, err) - require.Len(t, got, len(spec.codeIDs)) - for i, exp := range spec.codeIDs { - assert.EqualValues(t, exp, got[i]["id"]) - } - }) - } -} diff --git a/x/wasm/keeper/migrations.go b/x/wasm/keeper/migrations.go index 9000241..7ce1211 100644 --- a/x/wasm/keeper/migrations.go +++ b/x/wasm/keeper/migrations.go @@ -3,25 +3,30 @@ package keeper import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/terpnetwork/terp-core/x/wasm/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 + keeper Keeper + legacySubspace exported.Subspace } // NewMigrator returns a new Migrator. -func NewMigrator(keeper Keeper) Migrator { - return Migrator{keeper: keeper} +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 { - m.keeper.IterateContractInfo(ctx, func(contractAddr sdk.AccAddress, contractInfo types.ContractInfo) bool { - creator := sdk.MustAccAddressFromBech32(contractInfo.Creator) - m.keeper.addToContractCreatorSecondaryIndex(ctx, creator, contractInfo.Created, contractAddr) - return false - }) - return nil + 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 new file mode 100644 index 0000000..0e7a033 --- /dev/null +++ b/x/wasm/keeper/migrations_integration_test.go @@ -0,0 +1,72 @@ +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 index d708b31..392dbd2 100644 --- a/x/wasm/keeper/msg_dispatcher.go +++ b/x/wasm/keeper/msg_dispatcher.go @@ -1,19 +1,20 @@ package keeper import ( - "bytes" "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" - abci "github.com/tendermint/tendermint/abci/types" "github.com/terpnetwork/terp-core/x/wasm/types" ) -// Messenger is an extension point for custom terpd message handling +// 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) @@ -63,7 +64,7 @@ func (d MessageDispatcher) dispatchMsgWithGasLimit(ctx sdk.Context, contractAddr panic(r) } ctx.GasMeter().ConsumeGas(gasLimit, "Sub-Message OutOfGas panic") - err = sdkerrors.Wrap(sdkerrors.ErrOutOfGas, "SubMsg hit gas limit") + err = errorsmod.Wrap(sdkerrors.ErrOutOfGas, "SubMsg hit gas limit") } }() events, data, err = d.messenger.DispatchMsg(subCtx, contractAddr, ibcPort, msg) @@ -83,7 +84,7 @@ func (d MessageDispatcher) DispatchSubmessages(ctx sdk.Context, contractAddr sdk switch msg.ReplyOn { case wasmvmtypes.ReplySuccess, wasmvmtypes.ReplyError, wasmvmtypes.ReplyAlways, wasmvmtypes.ReplyNever: default: - return nil, sdkerrors.Wrap(types.ErrInvalid, "replyOn value") + 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() @@ -115,7 +116,7 @@ func (d MessageDispatcher) DispatchSubmessages(ctx sdk.Context, contractAddr sdk for _, e := range filteredEvents { attributes := e.Attributes sort.SliceStable(attributes, func(i, j int) bool { - return bytes.Compare(attributes[i].Key, attributes[j].Key) < 0 + return strings.Compare(attributes[i].Key, attributes[j].Key) < 0 }) } } @@ -163,7 +164,7 @@ func (d MessageDispatcher) DispatchSubmessages(ctx sdk.Context, contractAddr sdk rspData, err := d.keeper.reply(ctx, contractAddr, reply) switch { case err != nil: - return nil, sdkerrors.Wrap(err, "reply") + return nil, errorsmod.Wrap(err, "reply") case rspData != nil: rsp = rspData } @@ -184,7 +185,7 @@ func redactError(err error) error { // 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, _ := sdkerrors.ABCIInfo(err, false) + codespace, code, _ := errorsmod.ABCIInfo(err, false) return fmt.Errorf("codespace: %s, code: %d", codespace, code) } @@ -214,8 +215,8 @@ func sdkAttributesToWasmVMAttributes(attrs []abci.EventAttribute) []wasmvmtypes. res := make([]wasmvmtypes.EventAttribute, len(attrs)) for i, attr := range attrs { res[i] = wasmvmtypes.EventAttribute{ - Key: string(attr.Key), - Value: string(attr.Value), + 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 index adcb04d..436ad6d 100644 --- a/x/wasm/keeper/msg_dispatcher_test.go +++ b/x/wasm/keeper/msg_dispatcher_test.go @@ -5,13 +5,12 @@ import ( "fmt" "testing" - "github.com/tendermint/tendermint/libs/log" - 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" - abci "github.com/tendermint/tendermint/abci/types" "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" ) @@ -95,7 +94,7 @@ func TestDispatchSubmessages(t *testing.T) { }, 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: []byte("foo"), Value: []byte("bar")}}}} + myEvents := []sdk.Event{{Type: "myEvent", Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}}} return myEvents, [][]byte{[]byte("myData")}, nil }, }, @@ -104,7 +103,7 @@ func TestDispatchSubmessages(t *testing.T) { expEvents: []sdk.Event{ { Type: "myEvent", - Attributes: []abci.EventAttribute{{Key: []byte("foo"), Value: []byte("bar")}}, + Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}, }, sdk.NewEvent("wasm-reply"), }, @@ -116,7 +115,7 @@ func TestDispatchSubmessages(t *testing.T) { 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: []byte("foo"), Value: []byte("bar")}}}} + myEvents := []sdk.Event{{Type: "myEvent", Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}}} ctx.EventManager().EmitEvents(myEvents) return nil, nil, nil }, @@ -124,7 +123,7 @@ func TestDispatchSubmessages(t *testing.T) { expCommits: []bool{true}, expEvents: []sdk.Event{{ Type: "myEvent", - Attributes: []abci.EventAttribute{{Key: []byte("foo"), Value: []byte("bar")}}, + Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}, }}, }, "with context events - discarded on failure": { @@ -134,7 +133,7 @@ func TestDispatchSubmessages(t *testing.T) { 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: []byte("foo"), Value: []byte("bar")}}}} + myEvents := []sdk.Event{{Type: "myEvent", Attributes: []abci.EventAttribute{{Key: "foo", Value: "bar"}}}} ctx.EventManager().EmitEvents(myEvents) return nil, nil, errors.New("testing") }, @@ -395,15 +394,20 @@ func TestDispatchSubmessages(t *testing.T) { 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 - } else { - require.NoError(t, gotErr) - assert.Equal(t, spec.expData, gotData) } + + // 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()) diff --git a/x/wasm/keeper/msg_server.go b/x/wasm/keeper/msg_server.go index 9a47491..66d1cd6 100644 --- a/x/wasm/keeper/msg_server.go +++ b/x/wasm/keeper/msg_server.go @@ -3,22 +3,25 @@ package keeper import ( "context" + errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/terpnetwork/terp-core/x/wasm/types" ) var _ types.MsgServer = msgServer{} +// grpc message server implementation type msgServer struct { - keeper types.ContractOpsKeeper + keeper *Keeper } -func NewMsgServerImpl(k types.ContractOpsKeeper) types.MsgServer { +// 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 @@ -26,16 +29,12 @@ func (m msgServer) StoreCode(goCtx context.Context, msg *types.MsgStoreCode) (*t ctx := sdk.UnwrapSDKContext(goCtx) senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { - return nil, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } - ctx.EventManager().EmitEvent(sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - )) + policy := m.selectAuthorizationPolicy(msg.Sender) - codeID, checksum, err := m.keeper.Create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission) + codeID, checksum, err := m.keeper.create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission, policy) if err != nil { return nil, err } @@ -55,22 +54,18 @@ func (m msgServer) InstantiateContract(goCtx context.Context, msg *types.MsgInst senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { - return nil, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } var adminAddr sdk.AccAddress if msg.Admin != "" { if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { - return nil, sdkerrors.Wrap(err, "admin") + return nil, errorsmod.Wrap(err, "admin") } } - ctx.EventManager().EmitEvent(sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - )) + policy := m.selectAuthorizationPolicy(msg.Sender) - contractAddr, data, err := m.keeper.Instantiate(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds) + 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 } @@ -90,21 +85,20 @@ func (m msgServer) InstantiateContract2(goCtx context.Context, msg *types.MsgIns senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { - return nil, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } var adminAddr sdk.AccAddress if msg.Admin != "" { if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { - return nil, sdkerrors.Wrap(err, "admin") + return nil, errorsmod.Wrap(err, "admin") } } - ctx.EventManager().EmitEvent(sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - )) - contractAddr, data, err := m.keeper.Instantiate2(ctx, msg.CodeID, senderAddr, adminAddr, msg.Msg, msg.Label, msg.Funds, msg.Salt, msg.FixMsg) + 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 } @@ -123,20 +117,14 @@ func (m msgServer) ExecuteContract(goCtx context.Context, msg *types.MsgExecuteC ctx := sdk.UnwrapSDKContext(goCtx) senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { - return nil, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { - return nil, sdkerrors.Wrap(err, "contract") + return nil, errorsmod.Wrap(err, "contract") } - ctx.EventManager().EmitEvent(sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - )) - - data, err := m.keeper.Execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) + data, err := m.keeper.execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) if err != nil { return nil, err } @@ -154,20 +142,16 @@ func (m msgServer) MigrateContract(goCtx context.Context, msg *types.MsgMigrateC ctx := sdk.UnwrapSDKContext(goCtx) senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { - return nil, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { - return nil, sdkerrors.Wrap(err, "contract") + return nil, errorsmod.Wrap(err, "contract") } - ctx.EventManager().EmitEvent(sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - )) + policy := m.selectAuthorizationPolicy(msg.Sender) - data, err := m.keeper.Migrate(ctx, contractAddr, senderAddr, msg.CodeID, msg.Msg) + data, err := m.keeper.migrate(ctx, contractAddr, senderAddr, msg.CodeID, msg.Msg, policy) if err != nil { return nil, err } @@ -185,24 +169,20 @@ func (m msgServer) UpdateAdmin(goCtx context.Context, msg *types.MsgUpdateAdmin) ctx := sdk.UnwrapSDKContext(goCtx) senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { - return nil, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { - return nil, sdkerrors.Wrap(err, "contract") + return nil, errorsmod.Wrap(err, "contract") } newAdminAddr, err := sdk.AccAddressFromBech32(msg.NewAdmin) if err != nil { - return nil, sdkerrors.Wrap(err, "new admin") + return nil, errorsmod.Wrap(err, "new admin") } - ctx.EventManager().EmitEvent(sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - )) + policy := m.selectAuthorizationPolicy(msg.Sender) - if err := m.keeper.UpdateContractAdmin(ctx, contractAddr, senderAddr, newAdminAddr); err != nil { + if err := m.keeper.setContractAdmin(ctx, contractAddr, senderAddr, newAdminAddr, policy); err != nil { return nil, err } @@ -217,22 +197,169 @@ func (m msgServer) ClearAdmin(goCtx context.Context, msg *types.MsgClearAdmin) ( ctx := sdk.UnwrapSDKContext(goCtx) senderAddr, err := sdk.AccAddressFromBech32(msg.Sender) if err != nil { - return nil, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { - return nil, sdkerrors.Wrap(err, "contract") + return nil, errorsmod.Wrap(err, "contract") } - ctx.EventManager().EmitEvent(sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), - sdk.NewAttribute(sdk.AttributeKeySender, msg.Sender), - )) + policy := m.selectAuthorizationPolicy(msg.Sender) - if err := m.keeper.ClearContractAdmin(ctx, contractAddr, senderAddr); err != nil { + 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 index 1d12fbc..11003c0 100644 --- a/x/wasm/keeper/msg_server_integration_test.go +++ b/x/wasm/keeper/msg_server_integration_test.go @@ -3,23 +3,30 @@ 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" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "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(false) + wasmApp := app.Setup(t) ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) _, _, sender := testdata.KeyTestPubAddr() msg := types.MsgStoreCodeFixture(func(m *types.MsgStoreCode) { @@ -44,3 +51,805 @@ func TestStoreCode(t *testing.T) { 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_test.go b/x/wasm/keeper/options_test.go index 81c71a7..737f027 100644 --- a/x/wasm/keeper/options_test.go +++ b/x/wasm/keeper/options_test.go @@ -8,8 +8,6 @@ import ( 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" - distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -26,18 +24,21 @@ func TestConstructorOptions(t *testing.T) { "wasm engine": { srcOpt: WithWasmEngine(&wasmtesting.MockWasmer{}), verify: func(t *testing.T, k Keeper) { + t.Helper() assert.IsType(t, &wasmtesting.MockWasmer{}, k.wasmVM) }, }, "message handler": { srcOpt: WithMessageHandler(&wasmtesting.MockMessageHandler{}), verify: func(t *testing.T, k Keeper) { + t.Helper() assert.IsType(t, &wasmtesting.MockMessageHandler{}, k.messenger) }, }, "query plugins": { srcOpt: WithQueryHandler(&wasmtesting.MockQueryHandler{}), verify: func(t *testing.T, k Keeper) { + t.Helper() assert.IsType(t, &wasmtesting.MockQueryHandler{}, k.wasmVMQueryHandler) }, }, @@ -47,6 +48,7 @@ func TestConstructorOptions(t *testing.T) { return &wasmtesting.MockMessageHandler{} }), verify: func(t *testing.T, k Keeper) { + t.Helper() assert.IsType(t, &wasmtesting.MockMessageHandler{}, k.messenger) }, }, @@ -56,25 +58,29 @@ func TestConstructorOptions(t *testing.T) { return &wasmtesting.MockQueryHandler{} }), verify: func(t *testing.T, k Keeper) { + t.Helper() assert.IsType(t, &wasmtesting.MockQueryHandler{}, k.wasmVMQueryHandler) }, }, "coin transferrer": { srcOpt: WithCoinTransferrer(&wasmtesting.MockCoinTransferrer{}), verify: func(t *testing.T, k Keeper) { + t.Helper() assert.IsType(t, &wasmtesting.MockCoinTransferrer{}, k.bank) }, }, "costs": { srcOpt: WithGasRegister(&wasmtesting.MockGasRegister{}), verify: func(t *testing.T, k Keeper) { + t.Helper() assert.IsType(t, &wasmtesting.MockGasRegister{}, k.gasRegister) }, }, "api costs": { srcOpt: WithAPICosts(1, 2), verify: func(t *testing.T, k Keeper) { - t.Cleanup(setApiDefaults) + t.Helper() + t.Cleanup(setAPIDefaults) assert.Equal(t, uint64(1), costHumanize) assert.Equal(t, uint64(2), costCanonical) }, @@ -82,12 +88,14 @@ func TestConstructorOptions(t *testing.T) { "max recursion query limit": { srcOpt: WithMaxQueryStackSize(1), verify: func(t *testing.T, k Keeper) { + t.Helper() assert.IsType(t, uint32(1), k.maxQueryStackSize) }, }, "accepted account types": { srcOpt: WithAcceptedAccountTypesOnContractInstantiation(&authtypes.BaseAccount{}, &vestingtypes.ContinuousVestingAccount{}), verify: func(t *testing.T, k Keeper) { + t.Helper() exp := map[reflect.Type]struct{}{ reflect.TypeOf(&authtypes.BaseAccount{}): {}, reflect.TypeOf(&vestingtypes.ContinuousVestingAccount{}): {}, @@ -98,19 +106,20 @@ func TestConstructorOptions(t *testing.T) { "account pruner": { srcOpt: WithAccountPruner(VestingCoinBurner{}), verify: func(t *testing.T, k Keeper) { + t.Helper() assert.Equal(t, VestingCoinBurner{}, k.accountPruner) }, }, } for name, spec := range specs { t.Run(name, func(t *testing.T) { - k := NewKeeper(nil, nil, paramtypes.NewSubspace(nil, nil, nil, nil, ""), authkeeper.AccountKeeper{}, &bankkeeper.BaseKeeper{}, stakingkeeper.Keeper{}, distributionkeeper.Keeper{}, nil, nil, nil, nil, nil, nil, "tempDir", types.DefaultWasmConfig(), AvailableCapabilities, spec.srcOpt) + 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() { +func setAPIDefaults() { costHumanize = DefaultGasCostHumanAddress * DefaultGasMultiplier costCanonical = DefaultGasCostCanonicalAddress * DefaultGasMultiplier } diff --git a/x/wasm/keeper/proposal_handler.go b/x/wasm/keeper/proposal_handler.go index 58b9c1a..6cc6214 100644 --- a/x/wasm/keeper/proposal_handler.go +++ b/x/wasm/keeper/proposal_handler.go @@ -5,30 +5,36 @@ import ( "encoding/hex" "fmt" + 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" "github.com/terpnetwork/terp-core/x/wasm/types" ) // NewWasmProposalHandler creates a new governance Handler for wasm proposals -func NewWasmProposalHandler(k decoratedKeeper, enabledProposalTypes []types.ProposalType) govtypes.Handler { +// +// 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 -func NewWasmProposalHandlerX(k types.ContractOpsKeeper, enabledProposalTypes []types.ProposalType) govtypes.Handler { +// +// 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 govtypes.Content) error { + return func(ctx sdk.Context, content v1beta1.Content) error { if content == nil { - return sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "content must not be empty") + return errorsmod.Wrap(sdkerrors.ErrUnknownRequest, "content must not be empty") } if _, ok := enabledTypes[content.ProposalType()]; !ok { - return sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unsupported wasm proposal content type: %q", content.ProposalType()) + return errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unsupported wasm proposal content type: %q", content.ProposalType()) } switch c := content.(type) { case *types.StoreCodeProposal: @@ -56,11 +62,12 @@ func NewWasmProposalHandlerX(k types.ContractOpsKeeper, enabledProposalTypes []t case *types.StoreAndInstantiateContractProposal: return handleStoreAndInstantiateContractProposal(ctx, k, *c) default: - return sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized wasm proposal content type: %T", c) + 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 @@ -68,7 +75,7 @@ func handleStoreCodeProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) if err != nil { - return sdkerrors.Wrap(err, "run as address") + return errorsmod.Wrap(err, "run as address") } codeID, checksum, err := k.Create(ctx, runAsAddr, p.WASMByteCode, p.InstantiatePermission) if err != nil { @@ -86,18 +93,19 @@ func handleStoreCodeProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types 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 sdkerrors.Wrap(err, "run as address") + return errorsmod.Wrap(err, "run as address") } var adminAddr sdk.AccAddress if p.Admin != "" { if adminAddr, err = sdk.AccAddressFromBech32(p.Admin); err != nil { - return sdkerrors.Wrap(err, "admin") + return errorsmod.Wrap(err, "admin") } } @@ -113,6 +121,7 @@ func handleInstantiateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p typ 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 { @@ -122,14 +131,14 @@ func handleInstantiate2Proposal(ctx sdk.Context, k types.ContractOpsKeeper, p ty // Get runAsAddr as AccAddress runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) if err != nil { - return sdkerrors.Wrap(err, "run as address") + 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 sdkerrors.Wrap(err, "admin") + return errorsmod.Wrap(err, "admin") } } @@ -145,18 +154,19 @@ func handleInstantiate2Proposal(ctx sdk.Context, k types.ContractOpsKeeper, p ty 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 sdkerrors.Wrap(err, "run as address") + return errorsmod.Wrap(err, "run as address") } var adminAddr sdk.AccAddress if p.Admin != "" { if adminAddr, err = sdk.AccAddressFromBech32(p.Admin); err != nil { - return sdkerrors.Wrap(err, "admin") + return errorsmod.Wrap(err, "admin") } } @@ -166,7 +176,7 @@ func handleStoreAndInstantiateContractProposal(ctx sdk.Context, k types.Contract } if p.CodeHash != nil && !bytes.Equal(checksum, p.CodeHash) { - return sdkerrors.Wrap(fmt.Errorf("code-hash mismatch: %X, checksum: %X", p.CodeHash, checksum), "code-hash mismatch") + return errorsmod.Wrap(fmt.Errorf("code-hash mismatch: %X, checksum: %X", p.CodeHash, checksum), "code-hash mismatch") } if !p.UnpinCode { @@ -187,6 +197,7 @@ func handleStoreAndInstantiateContractProposal(ctx sdk.Context, k types.Contract return nil } +//nolint:staticcheck func handleMigrateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.MigrateContractProposal) error { if err := p.ValidateBasic(); err != nil { return err @@ -194,7 +205,7 @@ func handleMigrateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.M contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } // runAs is not used if this is permissioned, so just put any valid address there (second contractAddr) @@ -210,6 +221,7 @@ func handleMigrateProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.M return nil } +//nolint:staticcheck func handleSudoProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.SudoContractProposal) error { if err := p.ValidateBasic(); err != nil { return err @@ -217,7 +229,7 @@ func handleSudoProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.Sudo contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } data, err := k.Sudo(ctx, contractAddr, p.Msg) if err != nil { @@ -231,6 +243,7 @@ func handleSudoProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.Sudo return nil } +//nolint:staticcheck func handleExecuteProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.ExecuteContractProposal) error { if err := p.ValidateBasic(); err != nil { return err @@ -238,11 +251,11 @@ func handleExecuteProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.E contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } runAsAddr, err := sdk.AccAddressFromBech32(p.RunAs) if err != nil { - return sdkerrors.Wrap(err, "run as address") + return errorsmod.Wrap(err, "run as address") } data, err := k.Execute(ctx, contractAddr, runAsAddr, p.Msg, p.Funds) if err != nil { @@ -256,22 +269,24 @@ func handleExecuteProposal(ctx sdk.Context, k types.ContractOpsKeeper, p types.E 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 sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } newAdminAddr, err := sdk.AccAddressFromBech32(p.NewAdmin) if err != nil { - return sdkerrors.Wrap(err, "run as address") + 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 @@ -279,38 +294,39 @@ func handleClearAdminProposal(ctx sdk.Context, k types.ContractOpsKeeper, p type contractAddr, err := sdk.AccAddressFromBech32(p.Contract) if err != nil { - return sdkerrors.Wrap(err, "contract") - } - if err := k.ClearContractAdmin(ctx, contractAddr, nil); err != nil { - return err + return errorsmod.Wrap(err, "contract") } - return nil + 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 sdkerrors.Wrapf(err, "code id: %d", v) + 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 sdkerrors.Wrapf(err, "code id: %d", v) + 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 @@ -319,7 +335,7 @@ func handleUpdateInstantiateConfigProposal(ctx sdk.Context, k types.ContractOpsK var emptyCaller sdk.AccAddress for _, accessConfigUpdate := range p.AccessConfigUpdates { if err := k.SetAccessConfig(ctx, accessConfigUpdate.CodeID, emptyCaller, accessConfigUpdate.InstantiatePermission); err != nil { - return sdkerrors.Wrapf(err, "code id: %d", accessConfigUpdate.CodeID) + 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 index 5b5bf11..5e74dec 100644 --- a/x/wasm/keeper/proposal_integration_test.go +++ b/x/wasm/keeper/proposal_integration_test.go @@ -10,9 +10,10 @@ import ( 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" - "github.com/cosmos/cosmos-sdk/x/params/client/utils" - "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + 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" @@ -20,27 +21,41 @@ import ( "github.com/terpnetwork/terp-core/x/wasm/types" ) +const myTestLabel = "testing" + func TestStoreCodeProposal(t *testing.T) { parentCtx, keepers := CreateTestInput(t, false, "staking") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.SetParams(parentCtx, types.Params{ + wasmKeeper := keepers.WasmKeeper + err := wasmKeeper.SetParams(parentCtx, types.Params{ CodeUploadAccess: types.AllowNobody, InstantiateDefaultPermission: types.AccessTypeNobody, }) - wasmCode, err := os.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) - checksum, err := hex.DecodeString("13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5") + 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, }, } @@ -51,19 +66,13 @@ func TestStoreCodeProposal(t *testing.T) { src := types.StoreCodeProposalFixture(func(p *types.StoreCodeProposal) { p.RunAs = myActorAddress - p.WASMByteCode = wasmCode + p.WASMByteCode = spec.code p.UnpinCode = spec.unpinCode p.CodeHash = checksum }) - // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, src) - require.NoError(t, err) - - // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx, storedProposal.GetContent()) - require.NoError(t, err) + // when + mustSubmitAndExecuteLegacyProposal(t, ctx, src, myActorAddress, keepers) // then cInfo := wasmKeeper.GetCodeInfo(ctx, 1) @@ -73,18 +82,52 @@ func TestStoreCodeProposal(t *testing.T) { storedCode, err := wasmKeeper.GetByteCode(ctx, 1) require.NoError(t, err) - assert.Equal(t, wasmCode, storedCode) + 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") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.SetParams(ctx, types.Params{ + 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) @@ -102,18 +145,12 @@ func TestInstantiateProposal(t *testing.T) { p.CodeID = firstCodeID p.RunAs = oneAddress.String() p.Admin = otherAddress.String() - p.Label = "testing" + p.Label = myTestLabel }) em := sdk.NewEventManager() - // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, src) - require.NoError(t, err) - - // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx.WithEventManager(em), storedProposal.GetContent()) - require.NoError(t, err) + // when + mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, oneAddress.String(), keepers) // then contractAddr, err := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") @@ -124,7 +161,7 @@ func TestInstantiateProposal(t *testing.T) { assert.Equal(t, uint64(1), cInfo.CodeID) assert.Equal(t, oneAddress.String(), cInfo.Creator) assert.Equal(t, otherAddress.String(), cInfo.Admin) - assert.Equal(t, "testing", cInfo.Label) + assert.Equal(t, myTestLabel, cInfo.Label) expHistory := []types.ContractCodeHistoryEntry{{ Operation: types.ContractCodeHistoryOperationTypeInit, CodeID: src.CodeID, @@ -143,11 +180,12 @@ func TestInstantiateProposal(t *testing.T) { func TestInstantiate2Proposal(t *testing.T) { ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.SetParams(ctx, types.Params{ + 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) @@ -159,8 +197,8 @@ func TestInstantiate2Proposal(t *testing.T) { var ( oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) otherAddress sdk.AccAddress = bytes.Repeat([]byte{0x2}, types.ContractAddrLen) - label string = "label" - salt []byte = []byte("mySalt") + label = "label" + salt = []byte("mySalt") ) src := types.InstantiateContract2ProposalFixture(func(p *types.InstantiateContract2Proposal) { p.CodeID = firstCodeID @@ -173,14 +211,8 @@ func TestInstantiate2Proposal(t *testing.T) { em := sdk.NewEventManager() - // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, src) - require.NoError(t, err) - - // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx.WithEventManager(em), storedProposal.GetContent()) - require.NoError(t, err) + // when + mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, oneAddress.String(), keepers) cInfo := wasmKeeper.GetContractInfo(ctx, contractAddress) require.NotNil(t, cInfo) @@ -197,7 +229,7 @@ func TestInstantiate2Proposal(t *testing.T) { }} assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddress)) // and event - require.Len(t, em.Events(), 3, "%#v", em.Events()) + 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) @@ -207,11 +239,12 @@ func TestInstantiate2Proposal(t *testing.T) { func TestInstantiateProposal_NoAdmin(t *testing.T) { ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.SetParams(ctx, types.Params{ + 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) @@ -223,72 +256,81 @@ func TestInstantiateProposal_NoAdmin(t *testing.T) { var oneAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, types.ContractAddrLen) - // test invalid admin address - src := types.InstantiateContractProposalFixture(func(p *types.InstantiateContractProposal) { - p.CodeID = firstCodeID - p.RunAs = oneAddress.String() - p.Admin = "invalid" - p.Label = "testing" - }) - _, err = govKeeper.SubmitProposal(ctx, src) - require.Error(t, err) - - // test with no admin - src = types.InstantiateContractProposalFixture(func(p *types.InstantiateContractProposal) { - p.CodeID = firstCodeID - p.RunAs = oneAddress.String() - p.Admin = "" - p.Label = "testing" - }) - em := sdk.NewEventManager() - - // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, src) - require.NoError(t, err) - - // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx.WithEventManager(em), storedProposal.GetContent()) - require.NoError(t, err) - - // then - contractAddr, err := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") - require.NoError(t, err) + 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) { + 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, "testing", 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]) + 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") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.SetParams(ctx, types.Params{ + 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("13a1fc994cc6d1c81b746ee0c0ff6f90043875e0bf1d9be6b7d779fc978dc2a5") + checksum, err := hex.DecodeString("beb3de5e9b93b52e514c74ce87ccddb594b9bcd33b7f1af1bb6da63fc883917b") require.NoError(t, err) var ( @@ -300,19 +342,13 @@ func TestStoreAndInstantiateContractProposal(t *testing.T) { p.WASMByteCode = wasmCode p.RunAs = oneAddress.String() p.Admin = otherAddress.String() - p.Label = "testing" + p.Label = myTestLabel p.CodeHash = checksum }) em := sdk.NewEventManager() - // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, src) - require.NoError(t, err) - - // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx.WithEventManager(em), storedProposal.GetContent()) - require.NoError(t, err) + // when + mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, oneAddress.String(), keepers) // then contractAddr, err := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr") @@ -322,7 +358,7 @@ func TestStoreAndInstantiateContractProposal(t *testing.T) { require.NotNil(t, cInfo) assert.Equal(t, oneAddress.String(), cInfo.Creator) assert.Equal(t, otherAddress.String(), cInfo.Admin) - assert.Equal(t, "testing", cInfo.Label) + assert.Equal(t, myTestLabel, cInfo.Label) expHistory := []types.ContractCodeHistoryEntry{{ Operation: types.ContractCodeHistoryOperationTypeInit, CodeID: cInfo.CodeID, @@ -343,11 +379,12 @@ func TestStoreAndInstantiateContractProposal(t *testing.T) { func TestMigrateProposal(t *testing.T) { ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.SetParams(ctx, types.Params{ + 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) @@ -363,7 +400,7 @@ func TestMigrateProposal(t *testing.T) { ) contractInfo := types.ContractInfoFixture(func(c *types.ContractInfo) { - c.Label = "testing" + c.Label = myTestLabel c.Admin = anyAddress.String() c.Created = types.NewAbsoluteTxPosition(ctx) }) @@ -381,7 +418,7 @@ func TestMigrateProposal(t *testing.T) { migMsgBz, err := json.Marshal(migMsg) require.NoError(t, err) - src := types.MigrateContractProposal{ + src := &types.MigrateContractProposal{ Title: "Foo", Description: "Bar", CodeID: 2, @@ -391,14 +428,8 @@ func TestMigrateProposal(t *testing.T) { em := sdk.NewEventManager() - // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, &src) - require.NoError(t, err) - - // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx.WithEventManager(em), storedProposal.GetContent()) - require.NoError(t, err) + // when + mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, anyAddress.String(), keepers) // then require.NoError(t, err) @@ -406,7 +437,7 @@ func TestMigrateProposal(t *testing.T) { require.NotNil(t, cInfo) assert.Equal(t, uint64(2), cInfo.CodeID) assert.Equal(t, anyAddress.String(), cInfo.Admin) - assert.Equal(t, "testing", cInfo.Label) + assert.Equal(t, myTestLabel, cInfo.Label) expHistory := []types.ContractCodeHistoryEntry{{ Operation: types.ContractCodeHistoryOperationTypeInit, CodeID: firstCodeID, @@ -423,12 +454,12 @@ func TestMigrateProposal(t *testing.T) { 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, string(em.Events()[1].Attributes[0].Key)) + assert.Equal(t, types.AttributeKeyResultDataHex, em.Events()[1].Attributes[0].Key) } func TestExecuteProposal(t *testing.T) { ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, bankKeeper := keepers.GovKeeper, keepers.BankKeeper + bankKeeper := keepers.BankKeeper exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) contractAddr := exampleContract.Contract @@ -444,7 +475,7 @@ func TestExecuteProposal(t *testing.T) { require.NoError(t, err) // try with runAs that doesn't have pemission - badSrc := types.ExecuteContractProposal{ + badSrc := &types.ExecuteContractProposal{ Title: "First", Description: "Beneficiary has no permission to run", Contract: contractAddr.String(), @@ -452,17 +483,18 @@ func TestExecuteProposal(t *testing.T) { RunAs: exampleContract.BeneficiaryAddr.String(), } - em := sdk.NewEventManager() - // fails on store - this doesn't have permission - storedProposal, err := govKeeper.SubmitProposal(ctx, &badSrc) + 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{ + src := &types.ExecuteContractProposal{ Title: "Second", Description: "Verifier can execute", Contract: contractAddr.String(), @@ -470,16 +502,10 @@ func TestExecuteProposal(t *testing.T) { RunAs: exampleContract.VerifierAddr.String(), } - em = sdk.NewEventManager() - - // when stored - storedProposal, err = govKeeper.SubmitProposal(ctx, &src) - require.NoError(t, err) + em := sdk.NewEventManager() - // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx.WithEventManager(em), storedProposal.GetContent()) - require.NoError(t, err) + // when + mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, exampleContract.BeneficiaryAddr.String(), keepers) // balance should be empty (proper release) bal = bankKeeper.GetBalance(ctx, contractAddr, "denom") @@ -488,11 +514,11 @@ func TestExecuteProposal(t *testing.T) { func TestSudoProposal(t *testing.T) { ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, bankKeeper := keepers.GovKeeper, keepers.BankKeeper + bankKeeper := keepers.BankKeeper exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) contractAddr := exampleContract.Contract - _, _, anyAddr := keyPubAddr() + _, anyAddr := keyPubAddr() // check balance bal := bankKeeper.GetBalance(ctx, contractAddr, "denom") @@ -514,7 +540,7 @@ func TestSudoProposal(t *testing.T) { require.NoError(t, err) // sudo can do anything - src := types.SudoContractProposal{ + src := &types.SudoContractProposal{ Title: "Sudo", Description: "Steal funds for the verifier", Contract: contractAddr.String(), @@ -523,14 +549,8 @@ func TestSudoProposal(t *testing.T) { em := sdk.NewEventManager() - // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, &src) - require.NoError(t, err) - - // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx.WithEventManager(em), storedProposal.GetContent()) - require.NoError(t, err) + // when + mustSubmitAndExecuteLegacyProposal(t, ctx.WithEventManager(em), src, exampleContract.BeneficiaryAddr.String(), keepers) // balance should be empty (and verifier richer) bal = bankKeeper.GetBalance(ctx, contractAddr, "denom") @@ -549,7 +569,7 @@ func TestAdminProposals(t *testing.T) { specs := map[string]struct { state types.ContractInfo - srcProposal govtypes.Content + srcProposal v1beta1.Content expAdmin sdk.AccAddress }{ "update with different admin": { @@ -598,11 +618,12 @@ func TestAdminProposals(t *testing.T) { for msg, spec := range specs { t.Run(msg, func(t *testing.T) { ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.SetParams(ctx, types.Params{ + 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)) @@ -616,14 +637,9 @@ func TestAdminProposals(t *testing.T) { } require.NoError(t, wasmKeeper.importContract(ctx, contractAddr, &spec.state, []types.Model{}, entries)) - // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, spec.srcProposal) - require.NoError(t, err) - // and execute proposal - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx, storedProposal.GetContent()) - require.NoError(t, err) + // when + mustSubmitAndExecuteLegacyProposal(t, ctx, spec.srcProposal, otherAddress.String(), keepers) // then cInfo := wasmKeeper.GetContractInfo(ctx, contractAddr) @@ -633,106 +649,9 @@ func TestAdminProposals(t *testing.T) { } } -func TestUpdateParamsProposal(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - - var ( - legacyAmino = keepers.EncodingConfig.Amino - myAddress sdk.AccAddress = make([]byte, types.ContractAddrLen) - oneAddressAccessConfig = types.AccessTypeOnlyAddress.With(myAddress) - ) - - specs := map[string]struct { - src proposal.ParamChange - expUploadConfig types.AccessConfig - expInstantiateType types.AccessType - }{ - "update upload permission param": { - src: proposal.ParamChange{ - Subspace: types.ModuleName, - Key: string(types.ParamStoreKeyUploadAccess), - Value: string(legacyAmino.MustMarshalJSON(&types.AllowNobody)), - }, - expUploadConfig: types.AllowNobody, - expInstantiateType: types.AccessTypeEverybody, - }, - "update upload permission with same as current value": { - src: proposal.ParamChange{ - Subspace: types.ModuleName, - Key: string(types.ParamStoreKeyUploadAccess), - Value: string(legacyAmino.MustMarshalJSON(&types.AllowEverybody)), - }, - expUploadConfig: types.AllowEverybody, - expInstantiateType: types.AccessTypeEverybody, - }, - "update upload permission param with address": { - src: proposal.ParamChange{ - Subspace: types.ModuleName, - Key: string(types.ParamStoreKeyUploadAccess), - Value: string(legacyAmino.MustMarshalJSON(&oneAddressAccessConfig)), - }, - expUploadConfig: oneAddressAccessConfig, - expInstantiateType: types.AccessTypeEverybody, - }, - "update instantiate param": { - src: proposal.ParamChange{ - Subspace: types.ModuleName, - Key: string(types.ParamStoreKeyInstantiateAccess), - Value: string(legacyAmino.MustMarshalJSON(types.AccessTypeNobody)), - }, - expUploadConfig: types.AllowEverybody, - expInstantiateType: types.AccessTypeNobody, - }, - "update instantiate param as default": { - src: proposal.ParamChange{ - Subspace: types.ModuleName, - Key: string(types.ParamStoreKeyInstantiateAccess), - Value: string(legacyAmino.MustMarshalJSON(types.AccessTypeEverybody)), - }, - expUploadConfig: types.AllowEverybody, - expInstantiateType: types.AccessTypeEverybody, - }, - } - for msg, spec := range specs { - t.Run(msg, func(t *testing.T) { - wasmKeeper.SetParams(ctx, types.DefaultParams()) - - // encode + decode as CLI to play nice with amino - bz := legacyAmino.MustMarshalJSON(&utils.ParamChangeProposalJSON{ - Title: "Foo", - Description: "Bar", - Changes: []utils.ParamChangeJSON{{Subspace: spec.src.Subspace, Key: spec.src.Key, Value: json.RawMessage(spec.src.Value)}}, - }) - t.Log(string(bz)) - - var jsonProposal utils.ParamChangeProposalJSON - require.NoError(t, legacyAmino.UnmarshalJSON(bz, &jsonProposal)) - proposal := proposal.ParameterChangeProposal{ - Title: jsonProposal.Title, - Description: jsonProposal.Description, - Changes: jsonProposal.Changes.ToParamChanges(), - } - // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, &proposal) - require.NoError(t, err) - - // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx, storedProposal.GetContent()) - require.NoError(t, err) - - // then - assert.True(t, spec.expUploadConfig.Equals(wasmKeeper.getUploadAccessConfig(ctx)), - "got %#v not %#v", wasmKeeper.getUploadAccessConfig(ctx), spec.expUploadConfig) - assert.Equal(t, spec.expInstantiateType, wasmKeeper.getInstantiateAccessConfig(ctx)) - }) - } -} - func TestPinCodesProposal(t *testing.T) { ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper + wasmKeeper := keepers.WasmKeeper mock := wasmtesting.MockWasmer{ CreateFn: wasmtesting.NoOpCreateFn, @@ -787,17 +706,21 @@ func TestPinCodesProposal(t *testing.T) { 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{ + proposal := &types.PinCodesProposal{ Title: "Foo", Description: "Bar", CodeIDs: spec.srcCodeIDs, } - // when stored - storedProposal, gotErr := govKeeper.SubmitProposal(ctx, &proposal) + 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 @@ -805,9 +728,8 @@ func TestPinCodesProposal(t *testing.T) { require.NoError(t, gotErr) // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - gotErr = handler(ctx, storedProposal.GetContent()) - require.NoError(t, gotErr) + _, err := msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) + require.NoError(t, err) // then for i := range spec.srcCodeIDs { @@ -820,7 +742,7 @@ func TestPinCodesProposal(t *testing.T) { func TestUnpinCodesProposal(t *testing.T) { ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper + wasmKeeper := keepers.WasmKeeper mock := wasmtesting.MockWasmer{ CreateFn: wasmtesting.NoOpCreateFn, @@ -878,14 +800,17 @@ func TestUnpinCodesProposal(t *testing.T) { gotUnpinnedChecksums = nil ctx, _ := parentCtx.CacheContext() mock.UnpinFn = spec.mockFn - proposal := types.UnpinCodesProposal{ + proposal := &types.UnpinCodesProposal{ Title: "Foo", Description: "Bar", CodeIDs: spec.srcCodeIDs, } - // when stored - storedProposal, gotErr := govKeeper.SubmitProposal(ctx, &proposal) + 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 @@ -893,9 +818,8 @@ func TestUnpinCodesProposal(t *testing.T) { require.NoError(t, gotErr) // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - gotErr = handler(ctx, storedProposal.GetContent()) - require.NoError(t, gotErr) + _, err := msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) + require.NoError(t, err) // then for i := range spec.srcCodeIDs { @@ -908,7 +832,7 @@ func TestUnpinCodesProposal(t *testing.T) { func TestUpdateInstantiateConfigProposal(t *testing.T) { ctx, keepers := CreateTestInput(t, false, "staking") - govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper + wasmKeeper := keepers.WasmKeeper mock := wasmtesting.MockWasmer{ CreateFn: wasmtesting.NoOpCreateFn, @@ -917,7 +841,7 @@ func TestUpdateInstantiateConfigProposal(t *testing.T) { anyAddress, err := sdk.AccAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz") require.NoError(t, err) - withAddressAccessConfig := types.AccessTypeOnlyAddress.With(anyAddress) + withAddressAccessConfig := types.AccessTypeAnyOfAddresses.With(anyAddress) var ( nobody = StoreRandomContractWithAccessConfig(t, ctx, keepers, &mock, &types.AllowNobody) everybody = StoreRandomContractWithAccessConfig(t, ctx, keepers, &mock, &types.AllowEverybody) @@ -972,14 +896,16 @@ func TestUpdateInstantiateConfigProposal(t *testing.T) { }) } - proposal := types.UpdateInstantiateConfigProposal{ + govAuthority := keepers.AccountKeeper.GetModuleAddress(govtypes.ModuleName).String() + msgServer := govkeeper.NewMsgServerImpl(keepers.GovKeeper) + proposal := &types.UpdateInstantiateConfigProposal{ Title: "Foo", Description: "Bar", AccessConfigUpdates: updates, } - // when stored - storedProposal, gotErr := govKeeper.SubmitProposal(ctx, &proposal) + // when + contentMsg, gotErr := submitLegacyProposal(t, ctx, proposal, RandomBech32AccountAddress(t), govAuthority, msgServer) if spec.expErr { require.Error(t, gotErr) return @@ -987,9 +913,8 @@ func TestUpdateInstantiateConfigProposal(t *testing.T) { require.NoError(t, gotErr) // and proposal execute - handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - gotErr = handler(ctx, storedProposal.GetContent()) - require.NoError(t, gotErr) + _, err := msgServer.ExecLegacyContent(sdk.WrapSDKContext(ctx), v1.NewMsgExecLegacyContent(contentMsg.Content, govAuthority)) + require.NoError(t, err) // then for i := range spec.accessConfigUpdates { diff --git a/x/wasm/keeper/querier.go b/x/wasm/keeper/querier.go index 1ad2598..ae90461 100644 --- a/x/wasm/keeper/querier.go +++ b/x/wasm/keeper/querier.go @@ -5,33 +5,34 @@ import ( "encoding/binary" "runtime/debug" + errorsmod "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/codec" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "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{} +var _ types.QueryServer = &GrpcQuerier{} -type grpcQuerier struct { +type GrpcQuerier struct { cdc codec.Codec - storeKey sdk.StoreKey + storeKey storetypes.StoreKey keeper types.ViewKeeper queryGasLimit sdk.Gas } // NewGrpcQuerier constructor -func NewGrpcQuerier(cdc codec.Codec, storeKey sdk.StoreKey, keeper types.ViewKeeper, queryGasLimit sdk.Gas) *grpcQuerier { //nolint:revive - return &grpcQuerier{cdc: cdc, storeKey: storeKey, keeper: keeper, queryGasLimit: queryGasLimit} +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) { +func (q GrpcQuerier) ContractInfo(c context.Context, req *types.QueryContractInfoRequest) (*types.QueryContractInfoResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -49,7 +50,7 @@ func (q grpcQuerier) ContractInfo(c context.Context, req *types.QueryContractInf return rsp, nil } -func (q grpcQuerier) ContractHistory(c context.Context, req *types.QueryContractHistoryRequest) (*types.QueryContractHistoryResponse, error) { +func (q GrpcQuerier) ContractHistory(c context.Context, req *types.QueryContractHistoryRequest) (*types.QueryContractHistoryResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -82,12 +83,12 @@ func (q grpcQuerier) ContractHistory(c context.Context, req *types.QueryContract } // ContractsByCode lists all smart contracts for a code id -func (q grpcQuerier) ContractsByCode(c context.Context, req *types.QueryContractsByCodeRequest) (*types.QueryContractsByCodeResponse, error) { +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, sdkerrors.Wrap(types.ErrInvalid, "code id") + return nil, errorsmod.Wrap(types.ErrInvalid, "code id") } ctx := sdk.UnwrapSDKContext(c) r := make([]string, 0) @@ -109,7 +110,7 @@ func (q grpcQuerier) ContractsByCode(c context.Context, req *types.QueryContract }, nil } -func (q grpcQuerier) AllContractState(c context.Context, req *types.QueryAllContractStateRequest) (*types.QueryAllContractStateResponse, error) { +func (q GrpcQuerier) AllContractState(c context.Context, req *types.QueryAllContractStateRequest) (*types.QueryAllContractStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -142,7 +143,7 @@ func (q grpcQuerier) AllContractState(c context.Context, req *types.QueryAllCont }, nil } -func (q grpcQuerier) RawContractState(c context.Context, req *types.QueryRawContractStateRequest) (*types.QueryRawContractStateResponse, error) { +func (q GrpcQuerier) RawContractState(c context.Context, req *types.QueryRawContractStateRequest) (*types.QueryRawContractStateResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -160,7 +161,7 @@ func (q grpcQuerier) RawContractState(c context.Context, req *types.QueryRawCont return &types.QueryRawContractStateResponse{Data: rsp}, nil } -func (q grpcQuerier) SmartContractState(c context.Context, req *types.QuerySmartContractStateRequest) (rsp *types.QuerySmartContractStateResponse, err error) { +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") } @@ -177,7 +178,7 @@ func (q grpcQuerier) SmartContractState(c context.Context, req *types.QuerySmart if r := recover(); r != nil { switch rType := r.(type) { case sdk.ErrorOutOfGas: - err = sdkerrors.Wrapf(sdkerrors.ErrOutOfGas, + err = errorsmod.Wrapf(sdkerrors.ErrOutOfGas, "out of gas in location: %v; gasWanted: %d, gasUsed: %d", rType.Descriptor, ctx.GasMeter().Limit(), ctx.GasMeter().GasConsumed(), ) @@ -203,12 +204,12 @@ func (q grpcQuerier) SmartContractState(c context.Context, req *types.QuerySmart return &types.QuerySmartContractStateResponse{Data: bz}, nil } -func (q grpcQuerier) Code(c context.Context, req *types.QueryCodeRequest) (*types.QueryCodeResponse, error) { +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, sdkerrors.Wrap(types.ErrInvalid, "code id") + return nil, errorsmod.Wrap(types.ErrInvalid, "code id") } rsp, err := queryCode(sdk.UnwrapSDKContext(c), req.CodeId, q.keeper) switch { @@ -223,7 +224,7 @@ func (q grpcQuerier) Code(c context.Context, req *types.QueryCodeRequest) (*type }, nil } -func (q grpcQuerier) Codes(c context.Context, req *types.QueryCodesRequest) (*types.QueryCodesResponse, error) { +func (q GrpcQuerier) Codes(c context.Context, req *types.QueryCodesRequest) (*types.QueryCodesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -280,13 +281,13 @@ func queryCode(ctx sdk.Context, codeID uint64, keeper types.ViewKeeper) (*types. code, err := keeper.GetByteCode(ctx, codeID) if err != nil { - return nil, sdkerrors.Wrap(err, "loading wasm code") + 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) { +func (q GrpcQuerier) PinnedCodes(c context.Context, req *types.QueryPinnedCodesRequest) (*types.QueryPinnedCodesResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } @@ -310,13 +311,13 @@ func (q grpcQuerier) PinnedCodes(c context.Context, req *types.QueryPinnedCodesR } // Params returns params of the module. -func (q grpcQuerier) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { +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) { +func (q GrpcQuerier) ContractsByCreator(c context.Context, req *types.QueryContractsByCreatorRequest) (*types.QueryContractsByCreatorResponse, error) { if req == nil { return nil, status.Error(codes.InvalidArgument, "empty request") } diff --git a/x/wasm/keeper/querier_test.go b/x/wasm/keeper/querier_test.go index a17a69d..31cd190 100644 --- a/x/wasm/keeper/querier_test.go +++ b/x/wasm/keeper/querier_test.go @@ -9,18 +9,18 @@ import ( "testing" "time" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - + 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" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/log" + "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" @@ -43,7 +43,7 @@ func TestQueryAllContractState(t *testing.T) { srcQuery *types.QueryAllContractStateRequest expModelContains []types.Model expModelContainsNot []types.Model - expErr *sdkErrors.Error + expErr *errorsmod.Error }{ "query all": { srcQuery: &types.QueryAllContractStateRequest{Address: contractAddr.String()}, @@ -168,7 +168,7 @@ func TestQuerySmartContractPanics(t *testing.T) { specs := map[string]struct { doInContract func() - expErr *sdkErrors.Error + expErr *errorsmod.Error }{ "out of gas": { doInContract: func() { @@ -217,7 +217,7 @@ func TestQueryRawContractState(t *testing.T) { specs := map[string]struct { srcQuery *types.QueryRawContractStateRequest expData []byte - expErr *sdkErrors.Error + expErr *errorsmod.Error }{ "query raw key": { srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("foo")}, @@ -271,7 +271,7 @@ func TestQueryContractListByCodeOrdering(t *testing.T) { codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, wasmCode, nil) require.NoError(t, err) - _, _, bob := keyPubAddr() + _, bob := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: anyAddr, Beneficiary: bob, @@ -543,18 +543,19 @@ func TestQueryContractInfo(t *testing.T) { // register an example extension. must be protobuf keepers.EncodingConfig.InterfaceRegistry.RegisterImplementations( (*types.ContractInfoExtension)(nil), - &govtypes.Proposal{}, + &govv1beta1.Proposal{}, ) - govtypes.RegisterInterfaces(keepers.EncodingConfig.InterfaceRegistry) + 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 := govtypes.NewProposal(&govtypes.TextProposal{Title: "foo", Description: "bar"}, 1, anyDate, anyDate) + myExt, err := govv1beta1.NewProposal(&govv1beta1.TextProposal{Title: "foo", Description: "bar"}, 1, anyDate, anyDate) require.NoError(t, err) myExt.TotalDeposit = nil - info.SetExtension(&myExt) + err = info.SetExtension(&myExt) + require.NoError(t, err) } specs := map[string]struct { src *types.QueryContractInfoRequest @@ -613,7 +614,7 @@ func TestQueryPinnedCodes(t *testing.T) { specs := map[string]struct { srcQuery *types.QueryPinnedCodesRequest expCodeIDs []uint64 - expErr *sdkErrors.Error + expErr *errorsmod.Error }{ "query all": { srcQuery: &types.QueryPinnedCodesRequest{}, @@ -672,10 +673,11 @@ func TestQueryParams(t *testing.T) { require.Equal(t, paramsResponse.Params.CodeUploadAccess, defaultParams.CodeUploadAccess) require.Equal(t, paramsResponse.Params.InstantiateDefaultPermission, defaultParams.InstantiateDefaultPermission) - keeper.SetParams(ctx, types.Params{ + 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) @@ -695,19 +697,19 @@ func TestQueryCodeInfo(t *testing.T) { anyAddress, err := sdk.AccAddressFromBech32("cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz") require.NoError(t, err) specs := map[string]struct { - codeId uint64 + codeID uint64 accessConfig types.AccessConfig }{ "everybody": { - codeId: 1, + codeID: 1, accessConfig: types.AllowEverybody, }, "nobody": { - codeId: 10, + codeID: 10, accessConfig: types.AllowNobody, }, "with_address": { - codeId: 20, + codeID: 20, accessConfig: types.AccessTypeOnlyAddress.With(anyAddress), }, } @@ -715,19 +717,19 @@ func TestQueryCodeInfo(t *testing.T) { 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, + 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, + CodeId: spec.codeID, }) require.NoError(t, err) expectedResponse := &types.QueryCodeResponse{ CodeInfoResponse: &types.CodeInfoResponse{ - CodeID: spec.codeId, + CodeID: spec.codeID, Creator: codeInfo.Creator, DataHash: codeInfo.CodeHash, InstantiatePermission: spec.accessConfig, @@ -757,22 +759,22 @@ func TestQueryCodeInfoList(t *testing.T) { codes := []struct { name string - codeId uint64 + codeID uint64 codeInfo types.CodeInfo }{ { name: "everybody", - codeId: 1, + codeID: 1, codeInfo: codeInfoWithConfig(types.AllowEverybody), }, { - codeId: 10, + codeID: 10, name: "nobody", codeInfo: codeInfoWithConfig(types.AllowNobody), }, { name: "with_address", - codeId: 20, + codeID: 20, codeInfo: codeInfoWithConfig(types.AccessTypeOnlyAddress.With(anyAddress)), }, } @@ -780,14 +782,14 @@ func TestQueryCodeInfoList(t *testing.T) { 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, + require.NoError(t, keeper.importCode(ctx, code.codeID, code.codeInfo, wasmCode), ) }) allCodesResponse = append(allCodesResponse, types.CodeInfoResponse{ - CodeID: code.codeId, + CodeID: code.codeID, Creator: code.codeInfo.Creator, DataHash: code.codeInfo.CodeHash, InstantiatePermission: code.codeInfo.InstantiateConfig, @@ -818,7 +820,7 @@ func TestQueryContractsByCreatorList(t *testing.T) { codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, wasmCode, nil) require.NoError(t, err) - _, _, bob := keyPubAddr() + _, bob := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: anyAddr, Beneficiary: bob, diff --git a/x/wasm/keeper/query_plugins.go b/x/wasm/keeper/query_plugins.go index 02d311a..b85c582 100644 --- a/x/wasm/keeper/query_plugins.go +++ b/x/wasm/keeper/query_plugins.go @@ -5,19 +5,18 @@ import ( "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" - abci "github.com/tendermint/tendermint/abci/types" - - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - - "github.com/terpnetwork/terp-core/x/wasm/types" - - wasmvmtypes "github.com/CosmWasm/wasmvm/types" 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 { @@ -61,10 +60,10 @@ func (q QueryHandler) Query(request wasmvmtypes.QueryRequest, gasLimit uint64) ( return res, nil } - // special mappings to system error (which are not redacted) - var noSuchContract *types.ErrNoSuchContract - if ok := errors.As(err, &noSuchContract); ok { - err = wasmvmtypes.NoSuchContract{Addr: noSuchContract.Addr} + // 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 @@ -92,6 +91,7 @@ type contractMetaDataSource interface { 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 @@ -169,7 +169,7 @@ func BankQuerier(bankKeeper types.BankViewKeeper) func(ctx sdk.Context, request if request.AllBalances != nil { addr, err := sdk.AccAddressFromBech32(request.AllBalances.Address) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.AllBalances.Address) + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.AllBalances.Address) } coins := bankKeeper.GetAllBalances(ctx, addr) res := wasmvmtypes.AllBalancesResponse{ @@ -180,7 +180,7 @@ func BankQuerier(bankKeeper types.BankViewKeeper) func(ctx sdk.Context, request if request.Balance != nil { addr, err := sdk.AccAddressFromBech32(request.Balance.Address) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Balance.Address) + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Balance.Address) } coin := bankKeeper.GetBalance(ctx, addr, request.Balance.Denom) res := wasmvmtypes.BalanceResponse{ @@ -370,7 +370,7 @@ func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKee if request.AllDelegations != nil { delegator, err := sdk.AccAddressFromBech32(request.AllDelegations.Delegator) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.AllDelegations.Delegator) + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.AllDelegations.Delegator) } sdkDels := keeper.GetAllDelegatorDelegations(ctx, delegator) delegations, err := sdkToDelegations(ctx, keeper, sdkDels) @@ -385,11 +385,11 @@ func StakingQuerier(keeper types.StakingKeeper, distKeeper types.DistributionKee if request.Delegation != nil { delegator, err := sdk.AccAddressFromBech32(request.Delegation.Delegator) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Delegator) + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Delegator) } validator, err := sdk.ValAddressFromBech32(request.Delegation.Validator) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Validator) + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Validator) } var res wasmvmtypes.DelegationResponse @@ -413,18 +413,18 @@ func sdkToDelegations(ctx sdk.Context, keeper types.StakingKeeper, delegations [ for i, d := range delegations { delAddr, err := sdk.AccAddressFromBech32(d.DelegatorAddress) if err != nil { - return nil, sdkerrors.Wrap(err, "delegator address") + return nil, errorsmod.Wrap(err, "delegator address") } valAddr, err := sdk.ValAddressFromBech32(d.ValidatorAddress) if err != nil { - return nil, sdkerrors.Wrap(err, "validator address") + 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, sdkerrors.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") + return nil, errorsmod.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") } amount := sdk.NewCoin(bondDenom, val.TokensFromShares(d.Shares).TruncateInt()) @@ -440,15 +440,15 @@ func sdkToDelegations(ctx sdk.Context, keeper types.StakingKeeper, delegations [ 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, sdkerrors.Wrap(err, "delegator address") + return nil, errorsmod.Wrap(err, "delegator address") } valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) if err != nil { - return nil, sdkerrors.Wrap(err, "validator address") + return nil, errorsmod.Wrap(err, "validator address") } val, found := keeper.GetValidator(ctx, valAddr) if !found { - return nil, sdkerrors.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") + 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()) @@ -514,29 +514,30 @@ func WasmQuerier(k wasmQueryKeeper) func(ctx sdk.Context, request *wasmvmtypes.W case request.Smart != nil: addr, err := sdk.AccAddressFromBech32(request.Smart.ContractAddr) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Smart.ContractAddr) + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Smart.ContractAddr) } msg := types.RawContractMessage(request.Smart.Msg) if err := msg.ValidateBasic(); err != nil { - return nil, sdkerrors.Wrap(err, "json msg") + 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, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Raw.ContractAddr) + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, request.Raw.ContractAddr) } return k.QueryRaw(ctx, addr, request.Raw.Key), nil case request.ContractInfo != nil: - addr, err := sdk.AccAddressFromBech32(request.ContractInfo.ContractAddr) + contractAddr := request.ContractInfo.ContractAddr + addr, err := sdk.AccAddressFromBech32(contractAddr) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.ContractInfo.ContractAddr) + return nil, errorsmod.Wrap(sdkerrors.ErrInvalidAddress, contractAddr) } info := k.GetContractInfo(ctx, addr) if info == nil { - return nil, &types.ErrNoSuchContract{Addr: request.ContractInfo.ContractAddr} + return nil, types.ErrNoSuchContractFn(contractAddr). + Wrapf("address %s", contractAddr) } - res := wasmvmtypes.ContractInfoResponse{ CodeID: info.CodeID, Creator: info.Creator, @@ -545,6 +546,22 @@ func WasmQuerier(k wasmQueryKeeper) func(ctx sdk.Context, request *wasmvmtypes.W 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"} } @@ -574,14 +591,15 @@ func ConvertProtoToJSONMarshal(cdc codec.Codec, protoResponse codec.ProtoMarshal // unmarshal binary into stargate response data structure err := cdc.Unmarshal(bz, protoResponse) if err != nil { - return nil, sdkerrors.Wrap(err, "to proto") + return nil, errorsmod.Wrap(err, "to proto") } bz, err = cdc.MarshalJSON(protoResponse) if err != nil { - return nil, sdkerrors.Wrap(err, "to json") + return nil, errorsmod.Wrap(err, "to json") } + protoResponse.Reset() return bz, nil } diff --git a/x/wasm/keeper/query_plugins_test.go b/x/wasm/keeper/query_plugins_test.go index 182f4d7..f90b926 100644 --- a/x/wasm/keeper/query_plugins_test.go +++ b/x/wasm/keeper/query_plugins_test.go @@ -7,23 +7,23 @@ import ( "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" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "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" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - "github.com/gogo/protobuf/proto" + "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" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" "github.com/terpnetwork/terp-core/app" "github.com/terpnetwork/terp-core/x/wasm/keeper" @@ -89,8 +89,8 @@ func TestIBCQuerier(t *testing.T) { srcQuery *wasmvmtypes.IBCQuery wasmKeeper *mockWasmQueryKeeper channelKeeper *wasmtesting.MockChannelKeeper - expJsonResult string - expErr *sdkerrors.Error + expJSONResult string + expErr *errorsmod.Error }{ "query port id": { srcQuery: &wasmvmtypes.IBCQuery{ @@ -102,7 +102,7 @@ func TestIBCQuerier(t *testing.T) { }, }, channelKeeper: &wasmtesting.MockChannelKeeper{}, - expJsonResult: `{"port_id":"myIBCPortID"}`, + expJSONResult: `{"port_id":"myIBCPortID"}`, }, "query list channels - all": { srcQuery: &wasmvmtypes.IBCQuery{ @@ -111,7 +111,7 @@ func TestIBCQuerier(t *testing.T) { channelKeeper: &wasmtesting.MockChannelKeeper{ IterateChannelsFn: wasmtesting.MockChannelKeeperIterator(myExampleChannels), }, - expJsonResult: `{ + expJSONResult: `{ "channels": [ { "endpoint": { @@ -151,7 +151,7 @@ func TestIBCQuerier(t *testing.T) { channelKeeper: &wasmtesting.MockChannelKeeper{ IterateChannelsFn: wasmtesting.MockChannelKeeperIterator(myExampleChannels), }, - expJsonResult: `{ + expJSONResult: `{ "channels": [ { "endpoint": { @@ -178,7 +178,7 @@ func TestIBCQuerier(t *testing.T) { channelKeeper: &wasmtesting.MockChannelKeeper{ IterateChannelsFn: wasmtesting.MockChannelKeeperIterator(myExampleChannels), }, - expJsonResult: `{"channels": []}`, + expJSONResult: `{"channels": []}`, }, "query channel": { srcQuery: &wasmvmtypes.IBCQuery{ @@ -201,7 +201,7 @@ func TestIBCQuerier(t *testing.T) { }, true }, }, - expJsonResult: `{ + expJSONResult: `{ "channel": { "endpoint": { "port_id": "myQueryPortID", @@ -242,7 +242,7 @@ func TestIBCQuerier(t *testing.T) { }, true }, }, - expJsonResult: `{ + expJSONResult: `{ "channel": { "endpoint": { "port_id": "myLoadedPortID", @@ -278,7 +278,7 @@ func TestIBCQuerier(t *testing.T) { }, true }, }, - expJsonResult: "{}", + expJSONResult: "{}", }, "query channel in closed state": { srcQuery: &wasmvmtypes.IBCQuery{ @@ -301,7 +301,7 @@ func TestIBCQuerier(t *testing.T) { }, true }, }, - expJsonResult: "{}", + expJSONResult: "{}", }, "query channel - empty result": { srcQuery: &wasmvmtypes.IBCQuery{ @@ -315,7 +315,7 @@ func TestIBCQuerier(t *testing.T) { return channeltypes.Channel{}, false }, }, - expJsonResult: "{}", + expJSONResult: "{}", }, } for name, spec := range specs { @@ -326,7 +326,7 @@ func TestIBCQuerier(t *testing.T) { if spec.expErr != nil { return } - assert.JSONEq(t, spec.expJsonResult, string(gotResult), string(gotResult)) + assert.JSONEq(t, spec.expJSONResult, string(gotResult), string(gotResult)) }) } } @@ -460,6 +460,73 @@ func TestContractInfoWasmQuerier(t *testing.T) { } } +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 @@ -467,13 +534,21 @@ func TestQueryErrors(t *testing.T) { }{ "no error": {}, "no such contract": { - src: &types.ErrNoSuchContract{Addr: "contract-addr"}, + src: types.ErrNoSuchContractFn("contract-addr"), expErr: wasmvmtypes.NoSuchContract{Addr: "contract-addr"}, }, "no such contract - wrapped": { - src: sdkerrors.Wrap(&types.ErrNoSuchContract{Addr: "contract-addr"}, "my additional data"), + 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) { @@ -491,9 +566,10 @@ func TestQueryErrors(t *testing.T) { func TestAcceptListStargateQuerier(t *testing.T) { wasmApp := app.SetupWithEmptyStore(t) ctx := wasmApp.NewUncachedContext(false, tmproto.Header{ChainID: "foo", Height: 1, Time: time.Now()}) - wasmApp.StakingKeeper.SetParams(ctx, stakingtypes.DefaultParams()) + err := wasmApp.StakingKeeper.SetParams(ctx, stakingtypes.DefaultParams()) + require.NoError(t, err) - addrs := app.AddTestAddrs(wasmApp, ctx, 2, sdk.NewInt(1_000_000)) + 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{}, @@ -558,6 +634,7 @@ type mockWasmQueryKeeper struct { 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 { @@ -588,6 +665,13 @@ func (m mockWasmQueryKeeper) IsPinnedCode(ctx sdk.Context, codeID uint64) bool { 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 @@ -666,6 +750,31 @@ func TestConvertProtoToJSONMarshal(t *testing.T) { } } +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) { diff --git a/x/wasm/keeper/recurse_test.go b/x/wasm/keeper/recurse_test.go index c55195f..e611767 100644 --- a/x/wasm/keeper/recurse_test.go +++ b/x/wasm/keeper/recurse_test.go @@ -16,9 +16,8 @@ import ( ) type Recurse struct { - Depth uint32 `json:"depth"` - Work uint32 `json:"work"` - Contract sdk.AccAddress `json:"contract"` + Depth uint32 `json:"depth"` + Work uint32 `json:"work"` } type recurseWrapper struct { @@ -26,6 +25,7 @@ type recurseWrapper struct { } func buildRecurseQuery(t *testing.T, msg Recurse) []byte { + t.Helper() wrapper := recurseWrapper{Recurse: msg} bz, err := json.Marshal(wrapper) require.NoError(t, err) @@ -39,7 +39,8 @@ type recurseResponse struct { // number os wasm queries called from a contract var totalWasmQueryCounter int -func initRecurseContract(t *testing.T) (contract sdk.AccAddress, creator sdk.AccAddress, ctx sdk.Context, keeper *Keeper) { +func initRecurseContract(t *testing.T) (contract sdk.AccAddress, ctx sdk.Context, keeper *Keeper) { + t.Helper() countingQuerierDec := func(realWasmQuerier WasmVMQueryHandler) WasmVMQueryHandler { return WasmVMQueryHandlerFn(func(ctx sdk.Context, caller sdk.AccAddress, request wasmvmtypes.QueryRequest) ([]byte, error) { totalWasmQueryCounter++ @@ -49,17 +50,17 @@ func initRecurseContract(t *testing.T) (contract sdk.AccAddress, creator sdk.Acc ctx, keepers := CreateTestInput(t, false, AvailableCapabilities, WithQueryHandlerDecorator(countingQuerierDec)) keeper = keepers.WasmKeeper exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) - return exampleContract.Contract, exampleContract.CreatorAddr, ctx, keeper + return exampleContract.Contract, ctx, keeper } func TestGasCostOnQuery(t *testing.T) { const ( - GasNoWork uint64 = 63_958 + GasNoWork uint64 = 63_950 // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork50 uint64 = 64_401 // this is a little shy of 50k gas - to keep an eye on the limit + GasWork50 uint64 = 64_218 // this is a little shy of 50k gas - to keep an eye on the limit - GasReturnUnhashed uint64 = 33 - GasReturnHashed uint64 = 25 + GasReturnUnhashed uint64 = 32 + GasReturnHashed uint64 = 27 ) cases := map[string]struct { @@ -92,7 +93,7 @@ func TestGasCostOnQuery(t *testing.T) { Depth: 1, Work: 50, }, - expectedGas: 2*GasWork50 + GasReturnHashed + 1, // +1 for rounding + expectedGas: 2*GasWork50 + GasReturnHashed, }, "recursion 4, some work": { gasLimit: 400_000, @@ -100,11 +101,11 @@ func TestGasCostOnQuery(t *testing.T) { Depth: 4, Work: 50, }, - expectedGas: 5*GasWork50 + 4*GasReturnHashed + 1, + expectedGas: 5*GasWork50 + 4*GasReturnHashed, }, } - contractAddr, _, ctx, keeper := initRecurseContract(t) + contractAddr, ctx, keeper := initRecurseContract(t) for name, tc := range cases { t.Run(name, func(t *testing.T) { @@ -117,7 +118,6 @@ func TestGasCostOnQuery(t *testing.T) { // do the query recurse := tc.msg - recurse.Contract = contractAddr msg := buildRecurseQuery(t, recurse) data, err := keeper.QuerySmart(ctx, contractAddr, msg) require.NoError(t, err) @@ -181,12 +181,11 @@ func TestGasOnExternalQuery(t *testing.T) { }, } - contractAddr, _, ctx, keeper := initRecurseContract(t) + contractAddr, ctx, keeper := initRecurseContract(t) for name, tc := range cases { t.Run(name, func(t *testing.T) { recurse := tc.msg - recurse.Contract = contractAddr msg := buildRecurseQuery(t, recurse) querier := NewGrpcQuerier(keeper.cdc, keeper.storeKey, keeper, tc.gasLimit) @@ -211,9 +210,9 @@ func TestLimitRecursiveQueryGas(t *testing.T) { const ( // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork2k uint64 = 84_236 // = NewContractInstanceCosts + x // we have 6x gas used in cpu than in the instance + 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 = 26 + GasReturnHashed uint64 = 27 ) cases := map[string]struct { @@ -241,10 +240,10 @@ func TestLimitRecursiveQueryGas(t *testing.T) { }, expectQueriesFromContract: 5, // FIXME: why -1 ... confused a bit by calculations, seems like rounding issues - expectedGas: GasWork2k + 5*(GasWork2k+GasReturnHashed) - 1, + expectedGas: GasWork2k + 5*(GasWork2k+GasReturnHashed), }, // this is where we expect an error... - // it has enough gas to run 4 times and die on the 5th (4th time dispatching to sub-contract) + // 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, @@ -252,7 +251,7 @@ func TestLimitRecursiveQueryGas(t *testing.T) { Depth: 50, Work: 2000, }, - expectQueriesFromContract: 4, + expectQueriesFromContract: 5, expectOutOfGas: true, }, "very deep recursion, hits recursion limit": { @@ -263,12 +262,12 @@ func TestLimitRecursiveQueryGas(t *testing.T) { }, expectQueriesFromContract: 10, expectOutOfGas: false, - expectError: "query wasm contract failed", // Error we get from the contract instance doing the failing query, not terpd - expectedGas: 10*(GasWork2k+GasReturnHashed) - 264, + 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) + contractAddr, ctx, keeper := initRecurseContract(t) for name, tc := range cases { t.Run(name, func(t *testing.T) { @@ -281,7 +280,6 @@ func TestLimitRecursiveQueryGas(t *testing.T) { // prepare the query recurse := tc.msg - recurse.Contract = contractAddr msg := buildRecurseQuery(t, recurse) // if we expect out of gas, make sure this panics diff --git a/x/wasm/keeper/reflect_test.go b/x/wasm/keeper/reflect_test.go index 7115cbe..2e959b9 100644 --- a/x/wasm/keeper/reflect_test.go +++ b/x/wasm/keeper/reflect_test.go @@ -6,6 +6,7 @@ import ( "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" @@ -14,7 +15,7 @@ import ( 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/golang/protobuf/proto" + "github.com/cosmos/gogoproto/proto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -25,12 +26,16 @@ import ( // ReflectInitMsg is {} func buildReflectQuery(t *testing.T, query *testdata.ReflectQueryMsg) []byte { + t.Helper() + bz, err := json.Marshal(query) require.NoError(t, err) return bz } func mustParse(t *testing.T, data []byte, res interface{}) { + t.Helper() + err := json.Unmarshal(data, res) require.NoError(t, err) } @@ -44,7 +49,7 @@ func TestReflectContractSend(t *testing.T) { deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, _, bob := keyPubAddr() + _, bob := keyPubAddr() // upload reflect code reflectID, _, err := keeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) @@ -124,7 +129,7 @@ func TestReflectCustomMsg(t *testing.T) { deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) bob := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, _, fred := keyPubAddr() + _, fred := keyPubAddr() // upload code codeID, _, err := keeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) @@ -262,7 +267,7 @@ func TestReflectStargateQuery(t *testing.T) { funds := sdk.NewCoins(sdk.NewInt64Coin("denom", 320000)) contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) - expectedBalance := funds.Sub(contractStart) + expectedBalance := funds.Sub(contractStart...) creator := keepers.Faucet.NewFundedRandomAccount(ctx, funds...) // upload code @@ -331,7 +336,7 @@ func TestReflectTotalSupplyQuery(t *testing.T) { Chain: &testdata.ChainQuery{ Request: &wasmvmtypes.QueryRequest{ Bank: &wasmvmtypes.BankQuery{ - Supply: &wasmvmtypes.SupplyQuery{spec.denom}, + Supply: &wasmvmtypes.SupplyQuery{Denom: spec.denom}, }, }, }, @@ -373,6 +378,7 @@ func TestReflectInvalidStargateQuery(t *testing.T) { Address: creator.String(), } protoQueryBin, err := proto.Marshal(&protoQuery) + require.NoError(t, err) protoRequest := wasmvmtypes.QueryRequest{ Stargate: &wasmvmtypes.StargateQuery{ Path: "/cosmos.bank.v1beta1.Query/AllBalances", @@ -542,7 +548,31 @@ func TestWasmRawQueryWithNil(t *testing.T) { 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) { + t.Helper() acct := accKeeper.GetAccount(ctx, addr) if expected == nil { assert.Nil(t, acct) @@ -567,21 +597,21 @@ type reflectCustomMsg struct { // 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) { - any, err := codectypes.NewAnyWithValue(msg) + codecAny, err := codectypes.NewAnyWithValue(msg) if err != nil { return wasmvmtypes.CosmosMsg{}, err } - rawBz, err := cdc.MarshalJSON(any) + rawBz, err := cdc.MarshalJSON(codecAny) if err != nil { - return wasmvmtypes.CosmosMsg{}, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + return wasmvmtypes.CosmosMsg{}, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) } - customMsg, err := json.Marshal(reflectCustomMsg{ + customMsg, _ := json.Marshal(reflectCustomMsg{ Raw: rawBz, }) res := wasmvmtypes.CosmosMsg{ Custom: customMsg, } - return res, nil + return res, err } // reflectEncoders needs to be registered in test setup to handle custom message callbacks @@ -598,23 +628,23 @@ func fromReflectRawMsg(cdc codec.Codec) CustomEncoder { var custom reflectCustomMsg err := json.Unmarshal(msg, &custom) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) + return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } if custom.Raw != nil { - var any codectypes.Any - if err := cdc.UnmarshalJSON(custom.Raw, &any); err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) + 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(&any, &msg); err != nil { + if err := cdc.UnpackAny(&codecAny, &msg); err != nil { return nil, err } return []sdk.Msg{msg}, nil } if custom.Debug != "" { - return nil, sdkerrors.Wrapf(types.ErrInvalidMsg, "Custom Debug: %s", custom.Debug) + return nil, errorsmod.Wrapf(types.ErrInvalidMsg, "Custom Debug: %s", custom.Debug) } - return nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown Custom message variant") + return nil, errorsmod.Wrap(types.ErrInvalidMsg, "Unknown Custom message variant") } } @@ -628,19 +658,11 @@ type customQueryResponse struct { Msg string `json:"msg"` } -// these are the return values from contract -> go depending on type of query -type ownerResponse struct { - Owner string `json:"owner"` -} - +// this is from the contract to the go code (capitalized or ping) type capitalizedResponse struct { Text string `json:"text"` } -type chainResponse struct { - Data []byte `json:"data"` -} - // reflectPlugins needs to be registered in test setup to handle custom query callbacks func reflectPlugins() *QueryPlugins { return &QueryPlugins{ @@ -652,7 +674,7 @@ func performCustomQuery(_ sdk.Context, request json.RawMessage) ([]byte, error) var custom reflectCustomQuery err := json.Unmarshal(request, &custom) if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) + return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } if custom.Capitalized != nil { msg := strings.ToUpper(custom.Capitalized.Text) @@ -661,5 +683,5 @@ func performCustomQuery(_ sdk.Context, request json.RawMessage) ([]byte, error) if custom.Ping != nil { return json.Marshal(customQueryResponse{Msg: "pong"}) } - return nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown Custom query variant") + return nil, errorsmod.Wrap(types.ErrInvalidMsg, "Unknown Custom query variant") } diff --git a/x/wasm/keeper/relay.go b/x/wasm/keeper/relay.go index b10c886..a265179 100644 --- a/x/wasm/keeper/relay.go +++ b/x/wasm/keeper/relay.go @@ -3,10 +3,10 @@ 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" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/terpnetwork/terp-core/x/wasm/types" ) @@ -36,7 +36,7 @@ func (k Keeper) OnOpenChannel( 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 "", sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) + return "", errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) } if res != nil { return res.Version, nil @@ -69,7 +69,7 @@ func (k Keeper) OnConnectChannel( 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 sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) + return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) } return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) @@ -100,7 +100,7 @@ func (k Keeper) OnCloseChannel( 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 sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) + return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) } return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) @@ -130,10 +130,10 @@ func (k Keeper) OnRecvPacket( res, gasUsed, execErr := k.wasmVM.IBCPacketReceive(codeInfo.CodeHash, env, msg, prefixStore, cosmwasmAPI, querier, ctx.GasMeter(), gas, costJSONDeserialization) k.consumeRuntimeGas(ctx, gasUsed) if execErr != nil { - return nil, sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) + panic(execErr) } if res.Err != "" { // handle error case as before https://github.com/CosmWasm/wasmvm/commit/c300106fe5c9426a495f8e10821e00a9330c56c6 - return nil, sdkerrors.Wrap(types.ErrExecuteFailed, res.Err) + 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) @@ -164,7 +164,7 @@ func (k Keeper) OnAckPacket( 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 sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) + return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) } return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) } @@ -191,7 +191,7 @@ func (k Keeper) OnTimeoutPacket( 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 sdkerrors.Wrap(types.ErrExecuteFailed, execErr.Error()) + return errorsmod.Wrap(types.ErrExecuteFailed, execErr.Error()) } return k.handleIBCBasicContractResponse(ctx, contractAddr, contractInfo.IBCPortID, res) diff --git a/x/wasm/keeper/relay_test.go b/x/wasm/keeper/relay_test.go index 36c18d8..26c35c4 100644 --- a/x/wasm/keeper/relay_test.go +++ b/x/wasm/keeper/relay_test.go @@ -174,6 +174,7 @@ func TestOnConnectChannel(t *testing.T) { Channel: myChannel, }, } + err := keepers.WasmKeeper.OnConnectChannel(ctx, spec.contractAddr, msg) // then @@ -325,6 +326,7 @@ func TestOnRecvPacket(t *testing.T) { expContractGas sdk.Gas expAck []byte expErr bool + expPanic bool expEventTypes []string }{ "consume contract gas": { @@ -349,7 +351,7 @@ func TestOnRecvPacket(t *testing.T) { Attributes: []wasmvmtypes.EventAttribute{{Key: "Foo", Value: "Bar"}}, }, contractErr: errors.New("test, ignore"), - expErr: true, + expPanic: true, }, "dispatch contract messages on success": { contractAddr: example.Contract, @@ -444,6 +446,12 @@ func TestOnRecvPacket(t *testing.T) { // when msg := wasmvmtypes.IBCPacketReceiveMsg{Packet: myPacket} + if spec.expPanic { + assert.Panics(t, func() { + _, _ = keepers.WasmKeeper.OnRecvPacket(ctx, spec.contractAddr, msg) + }) + return + } gotAck, err := keepers.WasmKeeper.OnRecvPacket(ctx, spec.contractAddr, msg) // then diff --git a/x/wasm/keeper/snapshotter.go b/x/wasm/keeper/snapshotter.go index f4b1a1f..3642c51 100644 --- a/x/wasm/keeper/snapshotter.go +++ b/x/wasm/keeper/snapshotter.go @@ -4,12 +4,11 @@ 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" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - protoio "github.com/gogo/protobuf/io" - "github.com/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/terpnetwork/terp-core/x/wasm/ioutils" "github.com/terpnetwork/terp-core/x/wasm/types" @@ -45,7 +44,7 @@ func (ws *WasmSnapshotter) SupportedFormats() []uint32 { return []uint32{SnapshotFormat} } -func (ws *WasmSnapshotter) Snapshot(height uint64, protoWriter protoio.Writer) error { +func (ws *WasmSnapshotter) SnapshotExtension(height uint64, payloadWriter snapshot.ExtensionPayloadWriter) error { cacheMS, err := ws.cms.CacheMultiStoreWithVersion(int64(height)) if err != nil { return err @@ -77,7 +76,7 @@ func (ws *WasmSnapshotter) Snapshot(height uint64, protoWriter protoio.Writer) e return true } - err = snapshot.WriteExtensionItem(protoWriter, compressedWasm) + err = payloadWriter(compressedWasm) if err != nil { rerr = err return true @@ -89,28 +88,26 @@ func (ws *WasmSnapshotter) Snapshot(height uint64, protoWriter protoio.Writer) e return rerr } -func (ws *WasmSnapshotter) Restore( - height uint64, format uint32, protoReader protoio.Reader, -) (snapshot.SnapshotItem, error) { +func (ws *WasmSnapshotter) RestoreExtension(height uint64, format uint32, payloadReader snapshot.ExtensionPayloadReader) error { if format == SnapshotFormat { - return ws.processAllItems(height, protoReader, restoreV1, finalizeV1) + return ws.processAllItems(height, payloadReader, restoreV1, finalizeV1) } - return snapshot.SnapshotItem{}, snapshot.ErrUnknownFormat + return snapshot.ErrUnknownFormat } -func restoreV1(ctx sdk.Context, k *Keeper, compressedCode []byte) error { +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 sdkerrors.Wrap(types.ErrCreateFailed, err.Error()) + return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) } // FIXME: check which codeIDs the checksum matches?? _, err = k.wasmVM.Create(wasmCode) if err != nil { - return sdkerrors.Wrap(types.ErrCreateFailed, err.Error()) + return errorsmod.Wrap(types.ErrCreateFailed, err.Error()) } return nil } @@ -122,35 +119,23 @@ func finalizeV1(ctx sdk.Context, k *Keeper) error { func (ws *WasmSnapshotter) processAllItems( height uint64, - protoReader protoio.Reader, + payloadReader snapshot.ExtensionPayloadReader, cb func(sdk.Context, *Keeper, []byte) error, finalize func(sdk.Context, *Keeper) error, -) (snapshot.SnapshotItem, error) { +) error { ctx := sdk.NewContext(ws.cms, tmproto.Header{Height: int64(height)}, false, log.NewNopLogger()) - - // keep the last item here... if we break, it will either be empty (if we hit io.EOF) - // or contain the last item (if we hit payload == nil) - var item snapshot.SnapshotItem for { - item = snapshot.SnapshotItem{} - err := protoReader.ReadMsg(&item) + payload, err := payloadReader() if err == io.EOF { break } else if err != nil { - return snapshot.SnapshotItem{}, sdkerrors.Wrap(err, "invalid protobuf message") - } - - // if it is not another ExtensionPayload message, then it is not for us. - // we should return it an let the manager handle this one - payload := item.GetExtensionPayload() - if payload == nil { - break + return err } - if err := cb(ctx, ws.wasm, payload.Payload); err != nil { - return snapshot.SnapshotItem{}, sdkerrors.Wrap(err, "processing snapshot item") + if err := cb(ctx, ws.wasm, payload); err != nil { + return errorsmod.Wrap(err, "processing snapshot item") } } - return item, finalize(ctx, ws.wasm) + return finalize(ctx, ws.wasm) } diff --git a/x/wasm/keeper/snapshotter_integration_test.go b/x/wasm/keeper/snapshotter_integration_test.go index 01f7774..0d3b7ef 100644 --- a/x/wasm/keeper/snapshotter_integration_test.go +++ b/x/wasm/keeper/snapshotter_integration_test.go @@ -10,14 +10,14 @@ import ( "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" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - tmtypes "github.com/tendermint/tendermint/types" "github.com/terpnetwork/terp-core/app" "github.com/terpnetwork/terp-core/x/wasm/keeper" @@ -48,7 +48,7 @@ func TestSnapshotter(t *testing.T) { Height: srcTerpApp.LastBlockHeight() + 1, Time: time.Now(), }) - wasmKeeper := app.NewTestSupport(t, srcTerpApp).WasmKeeper() + wasmKeeper := srcTerpApp.WasmKeeper contractKeeper := keeper.NewDefaultPermissionKeeper(&wasmKeeper) srcCodeIDToChecksum := make(map[uint64][]byte, len(spec.wasmFiles)) @@ -81,7 +81,7 @@ func TestSnapshotter(t *testing.T) { } // then all wasm contracts are imported - wasmKeeper = app.NewTestSupport(t, destTerpApp).WasmKeeper() + wasmKeeper = destTerpApp.WasmKeeper ctx = destTerpApp.NewUncachedContext(false, tmproto.Header{ ChainID: "foo", Height: destTerpApp.LastBlockHeight() + 1, @@ -103,6 +103,7 @@ func TestSnapshotter(t *testing.T) { } func newWasmExampleApp(t *testing.T) (*app.TerpApp, sdk.AccAddress) { + t.Helper() senderPrivKey := ed25519.GenPrivKey() pubKey, err := cryptocodec.ToTmPubKeyInterface(senderPrivKey.PubKey()) require.NoError(t, err) diff --git a/x/wasm/keeper/staking_test.go b/x/wasm/keeper/staking_test.go index b26d6fd..b161bb3 100644 --- a/x/wasm/keeper/staking_test.go +++ b/x/wasm/keeper/staking_test.go @@ -12,10 +12,8 @@ import ( 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" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/staking" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" - "github.com/cosmos/cosmos-sdk/x/staking/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -30,7 +28,7 @@ type StakingInitMsg struct { Decimals uint8 `json:"decimals"` Validator sdk.ValAddress `json:"validator"` ExitTax sdk.Dec `json:"exit_tax"` - // MinWithdrawal is uint128 encoded as a string (use sdk.Int?) + // MinWithdrawal is uint128 encoded as a string (use math.Int?) MinWithdrawl string `json:"min_withdrawal"` } @@ -88,7 +86,7 @@ type InvestmentResponse struct { Owner sdk.AccAddress `json:"owner"` Validator sdk.ValAddress `json:"validator"` ExitTax sdk.Dec `json:"exit_tax"` - // MinWithdrawl is uint128 encoded as a string (use sdk.Int?) + // MinWithdrawl is uint128 encoded as a string (use math.Int?) MinWithdrawl string `json:"min_withdrawal"` } @@ -132,7 +130,7 @@ func TestInitializeStaking(t *testing.T) { checkAccount(t, ctx, accKeeper, bankKeeper, creator, deposit) // try to register with a validator not on the list and it fails - _, _, bob := keyPubAddr() + _, bob := keyPubAddr() badInitMsg := StakingInitMsg{ Name: "Missing Validator", Symbol: "MISS", @@ -159,7 +157,7 @@ type initInfo struct { ctx sdk.Context accKeeper authkeeper.AccountKeeper - stakingKeeper stakingkeeper.Keeper + stakingKeeper *stakingkeeper.Keeper distKeeper distributionkeeper.Keeper wasmKeeper Keeper contractKeeper wasmtypes.ContractOpsKeeper @@ -168,18 +166,13 @@ type initInfo struct { } func initializeStaking(t *testing.T) initInfo { + t.Helper() 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) - // set some baseline - this seems to be needed - k.DistKeeper.SetValidatorHistoricalRewards(ctx, valAddr, 0, distributiontypes.ValidatorHistoricalRewards{ - CumulativeRewardRatio: sdk.DecCoins{}, - ReferenceCount: 1, - }) - v, found := stakingKeeper.GetValidator(ctx, valAddr) assert.True(t, found) assert.Equal(t, v.GetDelegatorShares(), sdk.NewDec(1000000)) @@ -482,7 +475,7 @@ func TestQueryStakingInfo(t *testing.T) { mustParse(t, res, &reflectRes) var allValidatorsRes wasmvmtypes.AllValidatorsResponse mustParse(t, reflectRes.Data, &allValidatorsRes) - require.Len(t, allValidatorsRes.Validators, 1) + 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) @@ -550,7 +543,7 @@ func TestQueryStakingInfo(t *testing.T) { require.Equal(t, funds[0].Denom, delInfo.Amount.Denom) require.Equal(t, funds[0].Amount.String(), delInfo.Amount.Amount) - // test to get one delegations + // test to get one delegation reflectDelegationQuery := testdata.ReflectQueryMsg{Chain: &testdata.ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ Delegation: &wasmvmtypes.DelegationQuery{ Validator: valAddr.String(), @@ -562,6 +555,7 @@ func TestQueryStakingInfo(t *testing.T) { 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) @@ -626,7 +620,7 @@ func TestQueryStakingPlugin(t *testing.T) { Validator: valAddr.String(), }, } - raw, err := StakingQuerier(stakingKeeper, distKeeper)(ctx, &query) + raw, err := StakingQuerier(stakingKeeper, distributionkeeper.NewQuerier(distKeeper))(ctx, &query) require.NoError(t, err) var res wasmvmtypes.DelegationResponse mustParse(t, raw, &res) @@ -651,7 +645,8 @@ func TestQueryStakingPlugin(t *testing.T) { } // 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 { +func addValidator(t *testing.T, ctx sdk.Context, stakingKeeper *stakingkeeper.Keeper, faucet *TestFaucet, value sdk.Coin) sdk.ValAddress { + t.Helper() owner := faucet.NewFundedRandomAccount(ctx, value) privKey := secp256k1.GenPrivKey() @@ -660,11 +655,11 @@ func addValidator(t *testing.T, ctx sdk.Context, stakingKeeper stakingkeeper.Kee pkAny, err := codectypes.NewAnyWithValue(pubKey) require.NoError(t, err) - msg := stakingtypes.MsgCreateValidator{ - Description: types.Description{ + msg := &stakingtypes.MsgCreateValidator{ + Description: stakingtypes.Description{ Moniker: "Validator power", }, - Commission: types.CommissionRates{ + Commission: stakingtypes.CommissionRates{ Rate: sdk.MustNewDecFromStr("0.1"), MaxRate: sdk.MustNewDecFromStr("0.2"), MaxChangeRate: sdk.MustNewDecFromStr("0.01"), @@ -675,23 +670,21 @@ func addValidator(t *testing.T, ctx sdk.Context, stakingKeeper stakingkeeper.Kee Pubkey: pkAny, Value: value, } - - h := staking.NewHandler(stakingKeeper) - _, err = h(ctx, &msg) + _, 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 { +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) { +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) @@ -703,6 +696,7 @@ func setValidatorRewards(ctx sdk.Context, stakingKeeper stakingkeeper.Keeper, di } func assertBalance(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.AccAddress, addr sdk.AccAddress, expected string) { + t.Helper() query := StakingQueryMsg{ Balance: &addressQuery{ Address: addr, @@ -719,6 +713,7 @@ func assertBalance(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.Ac } func assertClaims(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.AccAddress, addr sdk.AccAddress, expected string) { + t.Helper() query := StakingQueryMsg{ Claims: &addressQuery{ Address: addr, @@ -735,6 +730,7 @@ func assertClaims(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.Acc } func assertSupply(t *testing.T, ctx sdk.Context, keeper Keeper, contract sdk.AccAddress, expectedIssued string, expectedBonded sdk.Coin) { + t.Helper() query := StakingQueryMsg{Investment: &struct{}{}} queryBz, err := json.Marshal(query) require.NoError(t, err) diff --git a/x/wasm/keeper/submsg_test.go b/x/wasm/keeper/submsg_test.go index 293c23a..c218fe8 100644 --- a/x/wasm/keeper/submsg_test.go +++ b/x/wasm/keeper/submsg_test.go @@ -27,8 +27,8 @@ func TestDispatchSubMsgSuccessCase(t *testing.T) { contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - creatorBalance := deposit.Sub(contractStart) - _, _, fred := keyPubAddr() + creatorBalance := deposit.Sub(contractStart...) + _, fred := keyPubAddr() // upload code codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) @@ -121,8 +121,8 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { require.NoError(t, err) hackatomID, _, err := keepers.ContractKeeper.Create(ctx, uploader, hackatomCode, nil) require.NoError(t, err) - _, _, bob := keyPubAddr() - _, _, fred := keyPubAddr() + _, bob := keyPubAddr() + _, fred := keyPubAddr() initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, @@ -187,12 +187,14 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { assertReturnedEvents := func(expectedEvents int) assertion { return func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { + t.Helper() 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) { + t.Helper() 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) @@ -201,11 +203,13 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { assertErrorString := func(shouldContain string) assertion { return func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { + t.Helper() assert.Contains(t, response.Err, shouldContain) } } assertGotContractAddr := func(t *testing.T, ctx sdk.Context, contract, emptyAccount string, response wasmvmtypes.SubMsgResult) { + t.Helper() // should get the events emitted on new contract event := response.Ok.Events[0] require.Equal(t, event.Type, "instantiate") @@ -236,7 +240,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { "send tokens": { submsgID: 5, msg: validBankSend, - resultAssertions: []assertion{assertReturnedEvents(0), assertGasUsed(95000, 96000)}, + resultAssertions: []assertion{assertReturnedEvents(0), assertGasUsed(102000, 103000)}, }, "not enough tokens": { submsgID: 6, @@ -256,7 +260,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { 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(95000, 96000)}, + resultAssertions: []assertion{assertReturnedEvents(0), assertGasUsed(102000, 103000)}, }, "not enough tokens with limit": { submsgID: 16, @@ -264,7 +268,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { subMsgError: true, gasLimit: &subGasLimit, // uses same gas as call without limit (note we do not charge the 40k on reply) - resultAssertions: []assertion{assertGasUsed(77800, 77900), assertErrorString("codespace: sdk, code: 5")}, + resultAssertions: []assertion{assertGasUsed(77700, 77800), assertErrorString("codespace: sdk, code: 5")}, }, "out of gas caught with gas limit": { submsgID: 17, @@ -283,7 +287,7 @@ func TestDispatchSubMsgErrorHandling(t *testing.T) { for name, tc := range cases { t.Run(name, func(t *testing.T) { creator := keepers.Faucet.NewFundedRandomAccount(ctx, contractStart...) - _, _, empty := keyPubAddr() + _, empty := keyPubAddr() contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, reflectID, creator, nil, []byte("{}"), fmt.Sprintf("contract %s", name), contractStart) require.NoError(t, err) @@ -367,7 +371,7 @@ func TestDispatchSubMsgEncodeToNoSdkMsg(t *testing.T) { contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, _, fred := keyPubAddr() + _, fred := keyPubAddr() // upload code codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) @@ -433,7 +437,7 @@ func TestDispatchSubMsgConditionalReplyOn(t *testing.T) { contractStart := sdk.NewCoins(sdk.NewInt64Coin("denom", 40000)) creator := keepers.Faucet.NewFundedRandomAccount(ctx, deposit...) - _, _, fred := keyPubAddr() + _, fred := keyPubAddr() // upload code codeID, _, err := keepers.ContractKeeper.Create(ctx, creator, testdata.ReflectContractWasm(), nil) @@ -501,7 +505,7 @@ func TestDispatchSubMsgConditionalReplyOn(t *testing.T) { }, } - var id uint64 = 0 + var id uint64 for name, tc := range cases { id++ t.Run(name, func(t *testing.T) { diff --git a/x/wasm/keeper/test_common.go b/x/wasm/keeper/test_common.go index e2c66fe..328d4b2 100644 --- a/x/wasm/keeper/test_common.go +++ b/x/wasm/keeper/test_common.go @@ -9,10 +9,23 @@ import ( "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" @@ -31,15 +44,17 @@ import ( "github.com/cosmos/cosmos-sdk/x/crisis" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" "github.com/cosmos/cosmos-sdk/x/distribution" - distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client" 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" @@ -56,18 +71,12 @@ import ( 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/v4/modules/apps/transfer" - ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - ibc "github.com/cosmos/ibc-go/v4/modules/core" - ibchost "github.com/cosmos/ibc-go/v4/modules/core/24-host" - ibckeeper "github.com/cosmos/ibc-go/v4/modules/core/keeper" + "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" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/libs/log" - "github.com/tendermint/tendermint/libs/rand" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" wasmappparams "github.com/terpnetwork/terp-core/app/params" "github.com/terpnetwork/terp-core/x/wasm/keeper/wasmtesting" @@ -81,9 +90,11 @@ var moduleBasics = module.NewBasicManager( staking.AppModuleBasic{}, mint.AppModuleBasic{}, distribution.AppModuleBasic{}, - gov.NewAppModuleBasic( - paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, - ), + gov.NewAppModuleBasic([]govclient.ProposalHandler{ + paramsclient.ProposalHandler, + upgradeclient.LegacyProposalHandler, + upgradeclient.LegacyCancelProposalHandler, + }), params.AppModuleBasic{}, crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, @@ -94,8 +105,9 @@ var moduleBasics = module.NewBasicManager( vesting.AppModuleBasic{}, ) -func MakeTestCodec(t testing.TB) codec.Codec { - return MakeEncodingConfig(t).Marshaler +func MakeTestCodec(tb testing.TB) codec.Codec { + tb.Helper() + return MakeEncodingConfig(tb).Marshaler } func MakeEncodingConfig(_ testing.TB) wasmappparams.EncodingConfig { @@ -108,7 +120,7 @@ func MakeEncodingConfig(_ testing.TB) wasmappparams.EncodingConfig { moduleBasics.RegisterLegacyAminoCodec(amino) moduleBasics.RegisterInterfaces(interfaceRegistry) - // add terpd types + // add wasmd types types.RegisterInterfaces(interfaceRegistry) types.RegisterLegacyAminoCodec(amino) @@ -121,6 +133,7 @@ var TestingStakeParams = stakingtypes.Params{ MaxEntries: 10, HistoricalEntries: 10, BondDenom: "stake", + MinCommissionRate: stakingtypes.DefaultMinCommissionRate, } type TestFaucet struct { @@ -131,10 +144,11 @@ type TestFaucet struct { 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() +func NewTestFaucet(tb testing.TB, ctx sdk.Context, bankKeeper bankkeeper.Keeper, minterModuleName string, initialAmount ...sdk.Coin) *TestFaucet { + tb.Helper() + require.NotEmpty(tb, initialAmount) + r := &TestFaucet{t: tb, bankKeeper: bankKeeper, minterModuleName: minterModuleName} + _, addr := keyPubAddr() r.sender = addr r.Mint(ctx, addr, initialAmount...) r.balance = initialAmount @@ -160,76 +174,90 @@ func (f *TestFaucet) Fund(parentCtx sdk.Context, receiver sdk.AccAddress, amount 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) + f.balance = f.balance.Sub(amounts...) } func (f *TestFaucet) NewFundedRandomAccount(ctx sdk.Context, amounts ...sdk.Coin) sdk.AccAddress { - _, _, addr := keyPubAddr() + _, addr := keyPubAddr() f.Fund(ctx, addr, amounts...) return addr } type TestKeepers struct { AccountKeeper authkeeper.AccountKeeper - StakingKeeper stakingkeeper.Keeper + StakingKeeper *stakingkeeper.Keeper DistKeeper distributionkeeper.Keeper BankKeeper bankkeeper.Keeper - GovKeeper govkeeper.Keeper + GovKeeper *govkeeper.Keeper ContractKeeper types.ContractOpsKeeper WasmKeeper *Keeper IBCKeeper *ibckeeper.Keeper - Router *baseapp.Router + 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") +func CreateDefaultTestInput(tb testing.TB) (sdk.Context, TestKeepers) { + tb.Helper() + return CreateTestInput(tb, 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) { +func CreateTestInput(tb testing.TB, isCheckTx bool, availableCapabilities string, opts ...Option) (sdk.Context, TestKeepers) { + tb.Helper() // Load default wasm config - return createTestInput(t, isCheckTx, availableCapabilities, types.DefaultWasmConfig(), dbm.NewMemDB(), opts...) + return createTestInput(tb, 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, + tb testing.TB, isCheckTx bool, availableCapabilities string, wasmConfig types.WasmConfig, db dbm.DB, opts ...Option, ) (sdk.Context, TestKeepers) { - tempDir := t.TempDir() + tb.Helper() + tempDir := tb.TempDir() keys := sdk.NewKVStoreKeys( - authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, - minttypes.StoreKey, distributiontypes.StoreKey, slashingtypes.StoreKey, - govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, - evidencetypes.StoreKey, ibctransfertypes.StoreKey, - capabilitytypes.StoreKey, feegrant.StoreKey, authzkeeper.StoreKey, + 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, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(v, storetypes.StoreTypeIAVL, db) } tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) for _, v := range tkeys { - ms.MountStoreWithDB(v, sdk.StoreTypeTransient, db) + ms.MountStoreWithDB(v, storetypes.StoreTypeTransient, db) } memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) for _, v := range memKeys { - ms.MountStoreWithDB(v, sdk.StoreTypeMemory, db) + ms.MountStoreWithDB(v, storetypes.StoreTypeMemory, db) } - require.NoError(t, ms.LoadLatestVersion()) + require.NoError(tb, ms.LoadLatestVersion()) ctx := sdk.NewContext(ms, tmproto.Header{ Height: 1234567, @@ -237,7 +265,7 @@ func createTestInput( }, isCheckTx, log.NewNopLogger()) ctx = types.WithTXCounter(ctx, 0) - encodingConfig := MakeEncodingConfig(t) + encodingConfig := MakeEncodingConfig(tb) appCodec, legacyAmino := encodingConfig.Marshaler, encodingConfig.Amino paramsKeeper := paramskeeper.NewKeeper( @@ -256,7 +284,7 @@ func createTestInput( crisistypes.ModuleName, ibctransfertypes.ModuleName, capabilitytypes.ModuleName, - ibchost.ModuleName, + ibcexported.ModuleName, govtypes.ModuleName, types.ModuleName, } { @@ -264,7 +292,43 @@ func createTestInput( } subspace := func(m string) paramstypes.Subspace { r, ok := paramsKeeper.GetSubspace(m) - require.True(t, ok) + require.True(tb, 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 @@ -279,45 +343,48 @@ func createTestInput( } accountKeeper := authkeeper.NewAccountKeeper( appCodec, - keys[authtypes.StoreKey], // target store - subspace(authtypes.ModuleName), + 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(tb, accountKeeper.SetParams(ctx, authtypes.DefaultParams())) + bankKeeper := bankkeeper.NewBaseKeeper( appCodec, keys[banktypes.StoreKey], accountKeeper, - subspace(banktypes.ModuleName), blockedAddrs, + authtypes.NewModuleAddress(banktypes.ModuleName).String(), ) - bankKeeper.SetParams(ctx, banktypes.DefaultParams()) + require.NoError(tb, bankKeeper.SetParams(ctx, banktypes.DefaultParams())) stakingKeeper := stakingkeeper.NewKeeper( appCodec, keys[stakingtypes.StoreKey], accountKeeper, bankKeeper, - subspace(stakingtypes.ModuleName), + authtypes.NewModuleAddress(stakingtypes.ModuleName).String(), ) - stakingKeeper.SetParams(ctx, TestingStakeParams) + stakingtypes.DefaultParams() + require.NoError(tb, stakingKeeper.SetParams(ctx, TestingStakeParams)) distKeeper := distributionkeeper.NewKeeper( appCodec, keys[distributiontypes.StoreKey], - subspace(distributiontypes.ModuleName), accountKeeper, bankKeeper, stakingKeeper, authtypes.FeeCollectorName, - nil, + authtypes.NewModuleAddress(distributiontypes.ModuleName).String(), ) - distKeeper.SetParams(ctx, distributiontypes.DefaultParams()) + require.NoError(tb, distKeeper.SetParams(ctx, distributiontypes.DefaultParams())) stakingKeeper.SetHooks(distKeeper.Hooks()) // set genesis items required for distribution @@ -329,9 +396,10 @@ func createTestInput( appCodec, tempDir, nil, + authtypes.NewModuleAddress(upgradetypes.ModuleName).String(), ) - faucet := NewTestFaucet(t, ctx, bankKeeper, minttypes.ModuleName, sdk.NewCoin("stake", sdk.NewInt(100_000_000_000))) + faucet := NewTestFaucet(tb, 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 @@ -344,26 +412,18 @@ func createTestInput( keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey], ) - scopedIBCKeeper := capabilityKeeper.ScopeToModule(ibchost.ModuleName) + scopedIBCKeeper := capabilityKeeper.ScopeToModule(ibcexported.ModuleName) scopedWasmKeeper := capabilityKeeper.ScopeToModule(types.ModuleName) ibcKeeper := ibckeeper.NewKeeper( appCodec, - keys[ibchost.StoreKey], - subspace(ibchost.ModuleName), + keys[ibcexported.StoreKey], + subspace(ibcexported.ModuleName), stakingKeeper, upgradeKeeper, scopedIBCKeeper, ) - router := baseapp.NewRouter() - bh := bank.NewHandler(bankKeeper) - router.AddRoute(sdk.NewRoute(banktypes.RouterKey, bh)) - sh := staking.NewHandler(stakingKeeper) - router.AddRoute(sdk.NewRoute(stakingtypes.RouterKey, sh)) - dh := distribution.NewHandler(distKeeper) - router.AddRoute(sdk.NewRoute(distributiontypes.RouterKey, dh)) - querier := baseapp.NewGRPCQueryRouter() querier.SetInterfaceRegistry(encodingConfig.InterfaceRegistry) msgRouter := baseapp.NewMsgServiceRouter() @@ -375,11 +435,10 @@ func createTestInput( keeper := NewKeeper( appCodec, keys[types.StoreKey], - subspace(types.ModuleName), accountKeeper, bankKeeper, stakingKeeper, - distKeeper, + distributionkeeper.NewQuerier(distKeeper), ibcKeeper.ChannelKeeper, &ibcKeeper.PortKeeper, scopedWasmKeeper, @@ -389,42 +448,42 @@ func createTestInput( tempDir, wasmConfig, availableCapabilities, + authtypes.NewModuleAddress(govtypes.ModuleName).String(), opts..., ) - keeper.SetParams(ctx, types.DefaultParams()) + require.NoError(tb, keeper.SetParams(ctx, types.DefaultParams())) + // add wasm handler so we can loop-back (contracts calling contracts) contractKeeper := NewDefaultPermissionKeeper(&keeper) - router.AddRoute(sdk.NewRoute(types.RouterKey, TestHandler(contractKeeper))) - am := module.NewManager( // minimal module set that we use for message/ query tests - bank.NewAppModule(appCodec, bankKeeper, accountKeeper), - staking.NewAppModule(appCodec, stakingKeeper, accountKeeper, bankKeeper), - distribution.NewAppModule(appCodec, distKeeper, accountKeeper, bankKeeper, stakingKeeper), - ) - am.RegisterServices(module.NewConfigurator(appCodec, msgRouter, querier)) - types.RegisterMsgServer(msgRouter, NewMsgServerImpl(NewDefaultPermissionKeeper(keeper))) - types.RegisterQueryServer(querier, NewGrpcQuerier(appCodec, keys[types.ModuleName], keeper, keeper.queryGasLimit)) - - govRouter := govtypes.NewRouter(). - AddRoute(govtypes.RouterKey, govtypes.ProposalHandler). + govRouter := govv1beta1.NewRouter(). + AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)). - AddRoute(distributiontypes.RouterKey, distribution.NewCommunityPoolSpendProposalHandler(distKeeper)). AddRoute(types.RouterKey, NewWasmProposalHandler(&keeper, types.EnableAllProposals)) govKeeper := govkeeper.NewKeeper( appCodec, keys[govtypes.StoreKey], - subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()), accountKeeper, bankKeeper, stakingKeeper, - govRouter, + msgRouter, + govtypes.DefaultConfig(), + authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) + require.NoError(tb, govKeeper.SetParams(ctx, govv1.DefaultParams())) + govKeeper.SetLegacyRouter(govRouter) + govKeeper.SetProposalID(ctx, 1) - govKeeper.SetProposalID(ctx, govtypes.DefaultStartingProposalID) - govKeeper.SetDepositParams(ctx, govtypes.DefaultDepositParams()) - govKeeper.SetVotingParams(ctx, govtypes.DefaultVotingParams()) - govKeeper.SetTallyParams(ctx, govtypes.DefaultTallyParams()) + 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, @@ -435,18 +494,19 @@ func createTestInput( BankKeeper: bankKeeper, GovKeeper: govKeeper, IBCKeeper: ibcKeeper, - Router: router, + 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) sdk.Handler { - return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { +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: @@ -457,15 +517,23 @@ func TestHandler(k types.ContractOpsKeeper) sdk.Handler { return handleExecute(ctx, k, msg) default: errMsg := fmt.Sprintf("unrecognized wasm message type: %T", msg) - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) + 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, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } codeID, _, err := k.Create(ctx, senderAddr, msg.WASMByteCode, msg.InstantiatePermission) if err != nil { @@ -481,12 +549,12 @@ func handleStoreCode(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgS 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, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } var adminAddr sdk.AccAddress if msg.Admin != "" { if adminAddr, err = sdk.AccAddressFromBech32(msg.Admin); err != nil { - return nil, sdkerrors.Wrap(err, "admin") + return nil, errorsmod.Wrap(err, "admin") } } @@ -504,11 +572,11 @@ func handleInstantiate(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.Ms 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, sdkerrors.Wrap(err, "sender") + return nil, errorsmod.Wrap(err, "sender") } contractAddr, err := sdk.AccAddressFromBech32(msg.Contract) if err != nil { - return nil, sdkerrors.Wrap(err, "admin") + return nil, errorsmod.Wrap(err, "admin") } data, err := k.Execute(ctx, contractAddr, senderAddr, msg.Msg, msg.Funds) if err != nil { @@ -522,7 +590,7 @@ func handleExecute(ctx sdk.Context, k types.ContractOpsKeeper, msg *types.MsgExe } func RandomAccountAddress(_ testing.TB) sdk.AccAddress { - _, _, addr := keyPubAddr() + _, addr := keyPubAddr() return addr } @@ -531,8 +599,9 @@ 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() +func RandomBech32AccountAddress(tb testing.TB) string { + tb.Helper() + return RandomAccountAddress(tb).String() } type ExampleContract struct { @@ -543,32 +612,43 @@ type ExampleContract struct { Checksum []byte } -func StoreHackatomExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContract(t, ctx, keepers, "./testdata/hackatom.wasm") +func StoreHackatomExampleContract(tb testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { + tb.Helper() + return StoreExampleContractWasm(tb, ctx, keepers, testdata.HackatomContractWasm()) } -func StoreBurnerExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContract(t, ctx, keepers, "./testdata/burner.wasm") -} +func StoreBurnerExampleContract(tb testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { + tb.Helper() -func StoreIBCReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContract(t, ctx, keepers, "./testdata/ibc_reflect.wasm") + return StoreExampleContractWasm(tb, ctx, keepers, testdata.BurnerContractWasm()) } -func StoreReflectContract(t testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { - return StoreExampleContract(t, ctx, keepers, "./testdata/reflect.wasm") +func StoreIBCReflectContract(tb testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { + tb.Helper() + + return StoreExampleContractWasm(tb, ctx, keepers, testdata.IBCReflectContractWasm()) } -func StoreExampleContract(t testing.TB, ctx sdk.Context, keepers TestKeepers, wasmFile string) ExampleContract { - anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000)) - creator, _, creatorAddr := keyPubAddr() - fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount) +func StoreReflectContract(tb testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleContract { + tb.Helper() + return StoreExampleContractWasm(tb, ctx, keepers, testdata.ReflectContractWasm()) +} +func StoreExampleContract(tb testing.TB, ctx sdk.Context, keepers TestKeepers, wasmFile string) ExampleContract { + tb.Helper() wasmCode, err := os.ReadFile(wasmFile) - require.NoError(t, err) + require.NoError(tb, err) + return StoreExampleContractWasm(tb, ctx, keepers, wasmCode) +} + +func StoreExampleContractWasm(tb testing.TB, ctx sdk.Context, keepers TestKeepers, wasmCode []byte) ExampleContract { + tb.Helper() + anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000)) + creator, creatorAddr := keyPubAddr() + fundAccounts(tb, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount) codeID, _, err := keepers.ContractKeeper.Create(ctx, creatorAddr, wasmCode, nil) - require.NoError(t, err) + require.NoError(tb, err) hash := keepers.WasmKeeper.GetCodeInfo(ctx, codeID).CodeHash return ExampleContract{anyAmount, creator, creatorAddr, codeID, hash} } @@ -581,11 +661,11 @@ type ExampleContractInstance struct { } // 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) +func SeedNewContractInstance(tb testing.TB, ctx sdk.Context, keepers TestKeepers, mock types.WasmerEngine) ExampleContractInstance { + tb.Helper() + exampleContract := StoreRandomContract(tb, ctx, keepers, mock) contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, exampleContract.CodeID, exampleContract.CreatorAddr, exampleContract.CreatorAddr, []byte(`{}`), "", nil) - require.NoError(t, err) + require.NoError(tb, err) return ExampleContractInstance{ ExampleContract: exampleContract, Contract: contractAddr, @@ -593,24 +673,25 @@ func SeedNewContractInstance(t testing.TB, ctx sdk.Context, keepers TestKeepers, } // 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 StoreRandomContract(tb testing.TB, ctx sdk.Context, keepers TestKeepers, mock types.WasmerEngine) ExampleContract { + tb.Helper() + return StoreRandomContractWithAccessConfig(tb, ctx, keepers, mock, nil) } func StoreRandomContractWithAccessConfig( - t testing.TB, ctx sdk.Context, + tb testing.TB, ctx sdk.Context, keepers TestKeepers, mock types.WasmerEngine, cfg *types.AccessConfig, ) ExampleContract { - t.Helper() + tb.Helper() anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000)) - creator, _, creatorAddr := keyPubAddr() - fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount) + creator, creatorAddr := keyPubAddr() + fundAccounts(tb, 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) + require.NoError(tb, err) exampleContract := ExampleContract{InitialAmount: anyAmount, Creator: creator, CreatorAddr: creatorAddr, CodeID: codeID, Checksum: checksum} return exampleContract } @@ -627,23 +708,24 @@ type HackatomExampleInstance struct { } // 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) +func InstantiateHackatomExampleContract(tb testing.TB, ctx sdk.Context, keepers TestKeepers) HackatomExampleInstance { + tb.Helper() + contract := StoreHackatomExampleContract(tb, ctx, keepers) - verifier, _, verifierAddr := keyPubAddr() - fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, verifierAddr, contract.InitialAmount) + verifier, verifierAddr := keyPubAddr() + fundAccounts(tb, ctx, keepers.AccountKeeper, keepers.BankKeeper, verifierAddr, contract.InitialAmount) - beneficiary, _, beneficiaryAddr := keyPubAddr() + beneficiary, beneficiaryAddr := keyPubAddr() initMsgBz := HackatomExampleInitMsg{ Verifier: verifierAddr, Beneficiary: beneficiaryAddr, - }.GetBytes(t) + }.GetBytes(tb) 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) + require.NoError(tb, err) return HackatomExampleInstance{ ExampleContract: contract, Contract: contractAddr, @@ -664,13 +746,14 @@ type ExampleInstance struct { } // 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) +func InstantiateReflectExampleContract(tb testing.TB, ctx sdk.Context, keepers TestKeepers) ExampleInstance { + tb.Helper() + example := StoreReflectContract(tb, ctx, keepers) initialAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) label := "demo contract to query" - contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, nil, []byte("{}"), label, initialAmount) + contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, example.CodeID, example.CreatorAddr, example.CreatorAddr, []byte("{}"), label, initialAmount) - require.NoError(t, err) + require.NoError(tb, err) return ExampleInstance{ ExampleContract: example, Contract: contractAddr, @@ -684,9 +767,10 @@ type HackatomExampleInitMsg struct { Beneficiary sdk.AccAddress `json:"beneficiary"` } -func (m HackatomExampleInitMsg) GetBytes(t testing.TB) []byte { +func (m HackatomExampleInitMsg) GetBytes(tb testing.TB) []byte { + tb.Helper() initMsgBz, err := json.Marshal(m) - require.NoError(t, err) + require.NoError(tb, err) return initMsgBz } @@ -698,17 +782,18 @@ type IBCReflectExampleInstance struct { } // 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 +func InstantiateIBCReflectContract(tb testing.TB, ctx sdk.Context, keepers TestKeepers) IBCReflectExampleInstance { + tb.Helper() + reflectID := StoreReflectContract(tb, ctx, keepers).CodeID + ibcReflectID := StoreIBCReflectContract(tb, ctx, keepers).CodeID initMsgBz := IBCReflectInitMsg{ ReflectCodeID: reflectID, - }.GetBytes(t) - adminAddr := RandomAccountAddress(t) + }.GetBytes(tb) + adminAddr := RandomAccountAddress(tb) contractAddr, _, err := keepers.ContractKeeper.Instantiate(ctx, ibcReflectID, adminAddr, adminAddr, initMsgBz, "ibc-reflect-factory", nil) - require.NoError(t, err) + require.NoError(tb, err) return IBCReflectExampleInstance{ Admin: adminAddr, Contract: contractAddr, @@ -721,9 +806,10 @@ type IBCReflectInitMsg struct { ReflectCodeID uint64 `json:"reflect_code_id"` } -func (m IBCReflectInitMsg) GetBytes(t testing.TB) []byte { +func (m IBCReflectInitMsg) GetBytes(tb testing.TB) []byte { + tb.Helper() initMsgBz, err := json.Marshal(m) - require.NoError(t, err) + require.NoError(tb, err) return initMsgBz } @@ -731,23 +817,25 @@ type BurnerExampleInitMsg struct { Payout sdk.AccAddress `json:"payout"` } -func (m BurnerExampleInitMsg) GetBytes(t testing.TB) []byte { +func (m BurnerExampleInitMsg) GetBytes(tb testing.TB) []byte { + tb.Helper() initMsgBz, err := json.Marshal(m) - require.NoError(t, err) + require.NoError(tb, err) return initMsgBz } -func fundAccounts(t testing.TB, ctx sdk.Context, am authkeeper.AccountKeeper, bank bankkeeper.Keeper, addr sdk.AccAddress, coins sdk.Coins) { +func fundAccounts(tb testing.TB, ctx sdk.Context, am authkeeper.AccountKeeper, bank bankkeeper.Keeper, addr sdk.AccAddress, coins sdk.Coins) { + tb.Helper() acc := am.NewAccountWithAddress(ctx, addr) am.SetAccount(ctx, acc) - NewTestFaucet(t, ctx, bank, minttypes.ModuleName, coins...).Fund(ctx, addr, coins...) + NewTestFaucet(tb, 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, crypto.PubKey, sdk.AccAddress) { +func keyPubAddr() (crypto.PrivKey, sdk.AccAddress) { keyCounter++ seed := make([]byte, 8) binary.BigEndian.PutUint64(seed, keyCounter) @@ -755,5 +843,5 @@ func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { key := ed25519.GenPrivKeyFromSecret(seed) pub := key.PubKey() addr := sdk.AccAddress(pub.Address()) - return key, pub, addr + return key, addr } diff --git a/x/wasm/keeper/test_fuzz.go b/x/wasm/keeper/test_fuzz.go index 8c1804d..d6acf7b 100644 --- a/x/wasm/keeper/test_fuzz.go +++ b/x/wasm/keeper/test_fuzz.go @@ -3,9 +3,9 @@ package keeper import ( "encoding/json" + tmBytes "github.com/cometbft/cometbft/libs/bytes" sdk "github.com/cosmos/cosmos-sdk/types" fuzz "github.com/google/gofuzz" - tmBytes "github.com/tendermint/tendermint/libs/bytes" "github.com/terpnetwork/terp-core/x/wasm/types" ) @@ -51,10 +51,12 @@ func FuzzContractCodeHistory(m *types.ContractCodeHistoryEntry, c fuzz.Continue) func FuzzStateModel(m *types.Model, c fuzz.Continue) { m.Key = tmBytes.HexBytes(c.RandString()) - if len(m.Key) == 0 { - m.Key = tmBytes.HexBytes("non empty key") + if len(m.Key) != 0 { + c.Fuzz(&m.Value) + return } - c.Fuzz(&m.Value) + // try again, keys must not be empty + FuzzStateModel(m, c) } func FuzzAccessType(m *types.AccessType, c fuzz.Continue) { diff --git a/x/wasm/keeper/testdata/burner.wasm b/x/wasm/keeper/testdata/burner.wasm index 4e65059..6639075 100644 Binary files a/x/wasm/keeper/testdata/burner.wasm and b/x/wasm/keeper/testdata/burner.wasm differ diff --git a/x/wasm/keeper/testdata/reflect.go b/x/wasm/keeper/testdata/contracts.go similarity index 70% rename from x/wasm/keeper/testdata/reflect.go rename to x/wasm/keeper/testdata/contracts.go index 64fed61..6073e4d 100644 --- a/x/wasm/keeper/testdata/reflect.go +++ b/x/wasm/keeper/testdata/contracts.go @@ -7,11 +7,20 @@ import ( "github.com/cosmos/cosmos-sdk/types" ) -//go:embed reflect.wasm -var reflectContract []byte - -//go:embed reflect_1_1.wasm -var migrateReflectContract []byte +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 @@ -21,6 +30,22 @@ 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"` diff --git a/x/wasm/keeper/testdata/cyberpunk.wasm b/x/wasm/keeper/testdata/cyberpunk.wasm new file mode 100644 index 0000000..355804a Binary files /dev/null and b/x/wasm/keeper/testdata/cyberpunk.wasm differ diff --git a/x/wasm/keeper/testdata/download_releases.sh b/x/wasm/keeper/testdata/download_releases.sh index 2757613..544cdd2 100755 --- a/x/wasm/keeper/testdata/download_releases.sh +++ b/x/wasm/keeper/testdata/download_releases.sh @@ -9,7 +9,7 @@ fi tag="$1" -for contract in burner hackatom ibc_reflect ibc_reflect_send reflect staking; do +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" diff --git a/x/wasm/keeper/testdata/hackatom.wasm b/x/wasm/keeper/testdata/hackatom.wasm index 183eef3..baa03a8 100644 Binary files a/x/wasm/keeper/testdata/hackatom.wasm and b/x/wasm/keeper/testdata/hackatom.wasm differ diff --git a/x/wasm/keeper/testdata/hackatom.wasm.gzip b/x/wasm/keeper/testdata/hackatom.wasm.gzip index 29b10c7..3c95e9b 100644 Binary files a/x/wasm/keeper/testdata/hackatom.wasm.gzip and b/x/wasm/keeper/testdata/hackatom.wasm.gzip differ diff --git a/x/wasm/keeper/testdata/ibc_reflect.wasm b/x/wasm/keeper/testdata/ibc_reflect.wasm index ec1739d..ec73710 100644 Binary files a/x/wasm/keeper/testdata/ibc_reflect.wasm and b/x/wasm/keeper/testdata/ibc_reflect.wasm differ diff --git a/x/wasm/keeper/testdata/ibc_reflect_send.wasm b/x/wasm/keeper/testdata/ibc_reflect_send.wasm index 497ceac..0f7d7e4 100644 Binary files a/x/wasm/keeper/testdata/ibc_reflect_send.wasm and b/x/wasm/keeper/testdata/ibc_reflect_send.wasm differ diff --git a/x/wasm/keeper/testdata/reflect.wasm b/x/wasm/keeper/testdata/reflect.wasm index 4122411..3173564 100644 Binary files a/x/wasm/keeper/testdata/reflect.wasm and b/x/wasm/keeper/testdata/reflect.wasm differ diff --git a/x/wasm/keeper/testdata/staking.wasm b/x/wasm/keeper/testdata/staking.wasm index d73c1b1..015ae00 100644 Binary files a/x/wasm/keeper/testdata/staking.wasm and b/x/wasm/keeper/testdata/staking.wasm differ diff --git a/x/wasm/keeper/testdata/version.txt b/x/wasm/keeper/testdata/version.txt index 820bf43..79127d8 100644 --- a/x/wasm/keeper/testdata/version.txt +++ b/x/wasm/keeper/testdata/version.txt @@ -1 +1 @@ -v1.0.0-beta +v1.2.0 diff --git a/x/wasm/keeper/wasmtesting/gas_register.go b/x/wasm/keeper/wasmtesting/gas_register.go index d1975f7..516cd5f 100644 --- a/x/wasm/keeper/wasmtesting/gas_register.go +++ b/x/wasm/keeper/wasmtesting/gas_register.go @@ -52,7 +52,7 @@ func (m MockGasRegister) ReplyCosts(pinned bool, reply wasmvmtypes.Reply) sdk.Ga return m.ReplyCostFn(pinned, reply) } -func (m MockGasRegister) EventCosts(evts []wasmvmtypes.EventAttribute, events wasmvmtypes.Events) sdk.Gas { +func (m MockGasRegister) EventCosts(evts []wasmvmtypes.EventAttribute, _ wasmvmtypes.Events) sdk.Gas { if m.EventCostsFn == nil { panic("not expected to be called") } diff --git a/x/wasm/keeper/wasmtesting/mock_engine.go b/x/wasm/keeper/wasmtesting/mock_engine.go index cc759a8..052d165 100644 --- a/x/wasm/keeper/wasmtesting/mock_engine.go +++ b/x/wasm/keeper/wasmtesting/mock_engine.go @@ -4,10 +4,11 @@ import ( "bytes" "crypto/sha256" + errorsmod "cosmossdk.io/errors" + wasmvm "github.com/CosmWasm/wasmvm" wasmvmtypes "github.com/CosmWasm/wasmvm/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/tendermint/tendermint/libs/rand" + "github.com/cometbft/cometbft/libs/rand" "github.com/terpnetwork/terp-core/x/wasm/types" ) @@ -323,7 +324,7 @@ func NewIBCContractMockWasmer(c IBCContractCallbacks) *MockWasmer { func HashOnlyCreateFn(code wasmvm.WasmCode) (wasmvm.Checksum, error) { if code == nil { - return nil, sdkerrors.Wrap(types.ErrInvalid, "wasm code must not be nil") + return nil, errorsmod.Wrap(types.ErrInvalid, "wasm code must not be nil") } hash := sha256.Sum256(code) return hash[:], nil diff --git a/x/wasm/keeper/wasmtesting/mock_keepers.go b/x/wasm/keeper/wasmtesting/mock_keepers.go index 6b7e4ad..021a29f 100644 --- a/x/wasm/keeper/wasmtesting/mock_keepers.go +++ b/x/wasm/keeper/wasmtesting/mock_keepers.go @@ -3,20 +3,19 @@ package wasmtesting import ( sdk "github.com/cosmos/cosmos-sdk/types" capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - ibcexported "github.com/cosmos/ibc-go/v4/modules/core/exported" + 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) - GetNextSequenceSendFn func(ctx sdk.Context, portID, channelID string) (uint64, bool) - SendPacketFn func(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) 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) + 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) { @@ -33,18 +32,11 @@ func (m *MockChannelKeeper) GetAllChannels(ctx sdk.Context) []channeltypes.Ident return m.GetAllChannelsFn(ctx) } -func (m *MockChannelKeeper) GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) { - if m.GetNextSequenceSendFn == nil { - panic("not supposed to be called!") - } - return m.GetNextSequenceSendFn(ctx, portID, channelID) -} - -func (m *MockChannelKeeper) SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error { +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, packet) + return m.SendPacketFn(ctx, channelCap, sourcePort, sourceChannel, timeoutHeight, timeoutTimestamp, data) } func (m *MockChannelKeeper) ChanCloseInit(ctx sdk.Context, portID, channelID string, chanCap *capabilitytypes.Capability) error { diff --git a/x/wasm/migrations/v1/store.go b/x/wasm/migrations/v1/store.go new file mode 100644 index 0000000..f2c6dbb --- /dev/null +++ b/x/wasm/migrations/v1/store.go @@ -0,0 +1,36 @@ +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/keeper/migrate_test.go b/x/wasm/migrations/v1/store_test.go similarity index 61% rename from x/wasm/keeper/migrate_test.go rename to x/wasm/migrations/v1/store_test.go index 2aafb28..990baac 100644 --- a/x/wasm/keeper/migrate_test.go +++ b/x/wasm/migrations/v1/store_test.go @@ -1,10 +1,12 @@ -package keeper +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" @@ -13,17 +15,18 @@ import ( ) func TestMigrate1To2(t *testing.T) { - ctx, keepers := CreateTestInput(t, false, AvailableCapabilities) + 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 := StoreHackatomExampleContract(t, ctx, keepers) + example := keeper.StoreHackatomExampleContract(t, ctx, keepers) - initMsg := HackatomExampleInitMsg{ - Verifier: RandomAccountAddress(t), - Beneficiary: RandomAccountAddress(t), + initMsg := keeper.HackatomExampleInitMsg{ + Verifier: keeper.RandomAccountAddress(t), + Beneficiary: keeper.RandomAccountAddress(t), } initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) @@ -32,23 +35,30 @@ func TestMigrate1To2(t *testing.T) { // 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(wasmKeeper.storeKey).Delete(types.GetContractByCreatorSecondaryIndexKey(creator, info1.Created.Bytes(), gotContractAddr1)) - ctx.KVStore(wasmKeeper.storeKey).Delete(types.GetContractByCreatorSecondaryIndexKey(creator, info2.Created.Bytes(), gotContractAddr2)) - ctx.KVStore(wasmKeeper.storeKey).Delete(types.GetContractByCreatorSecondaryIndexKey(creator, info3.Created.Bytes(), gotContractAddr3)) + 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 - migrator := NewMigrator(*wasmKeeper) - migrator.Migrate1to2(ctx) + err = keeper.NewMigrator(*wasmKeeper, nil).Migrate1to2(ctx) + require.NoError(t, err) // check new store var allContract []string diff --git a/x/wasm/migrations/v2/store.go b/x/wasm/migrations/v2/store.go new file mode 100644 index 0000000..f6318c0 --- /dev/null +++ b/x/wasm/migrations/v2/store.go @@ -0,0 +1,33 @@ +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/migrations/v2/store_test.go b/x/wasm/migrations/v2/store_test.go new file mode 100644 index 0000000..c5dcc7e --- /dev/null +++ b/x/wasm/migrations/v2/store_test.go @@ -0,0 +1,44 @@ +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/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" +) + +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 +} + +func TestMigrate(t *testing.T) { + cdc := moduletestutil.MakeTestEncodingConfig(wasm.AppModuleBasic{}).Codec + storeKey := sdk.NewKVStoreKey(types.StoreKey) + 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)) + + var res types.Params + bz := store.Get(types.ParamsKey) + require.NoError(t, cdc.Unmarshal(bz, &res)) + require.Equal(t, legacySubspace.ps, res) +} diff --git a/x/wasm/module.go b/x/wasm/module.go index 6668251..371e804 100644 --- a/x/wasm/module.go +++ b/x/wasm/module.go @@ -4,11 +4,15 @@ import ( "context" "encoding/json" "fmt" - "math/rand" "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" @@ -17,22 +21,20 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/spf13/cast" "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" "github.com/terpnetwork/terp-core/x/wasm/client/cli" - "github.com/terpnetwork/terp-core/x/wasm/client/rest" //nolint:staticcheck + "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.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModule{} ) // Module init related flags @@ -45,7 +47,7 @@ const ( // AppModuleBasic defines the basic application module used by the wasm module. type AppModuleBasic struct{} -func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { //nolint:staticcheck +func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { RegisterCodec(amino) } @@ -70,7 +72,7 @@ func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { } // ValidateGenesis performs genesis state validation for the wasm module. -func (b AppModuleBasic) ValidateGenesis(marshaler codec.JSONCodec, config client.TxEncodingConfig, message json.RawMessage) error { +func (b AppModuleBasic) ValidateGenesis(marshaler codec.JSONCodec, _ client.TxEncodingConfig, message json.RawMessage) error { var data GenesisState err := marshaler.UnmarshalJSON(message, &data) if err != nil { @@ -79,11 +81,6 @@ func (b AppModuleBasic) ValidateGenesis(marshaler codec.JSONCodec, config client return ValidateGenesis(data) } -// RegisterRESTRoutes registers the REST routes for the wasm module. -func (AppModuleBasic) RegisterRESTRoutes(cliCtx client.Context, rtr *mux.Router) { - rest.RegisterRoutes(cliCtx, rtr) -} - // GetTxCmd returns the root tx command for the wasm module. func (b AppModuleBasic) GetTxCmd() *cobra.Command { return cli.GetTxCmd() @@ -100,6 +97,7 @@ func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) } // ____________________________________________________________________________ +var _ appmodule.AppModule = AppModule{} // AppModule implements an application module for the wasm module. type AppModule struct { @@ -109,14 +107,11 @@ type AppModule struct { 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 } -// 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 2 } - // NewAppModule creates a new AppModule object func NewAppModule( cdc codec.Codec, @@ -124,6 +119,8 @@ func NewAppModule( validatorSetSource keeper.ValidatorSetSource, ak types.AccountKeeper, bk simulation.BankKeeper, + router *baseapp.MsgServiceRouter, + ss exported.Subspace, ) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, @@ -132,31 +129,42 @@ func NewAppModule( 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(keeper.NewDefaultPermissionKeeper(am.keeper))) + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), NewQuerier(am.keeper)) - m := keeper.NewMigrator(*am.keeper) + m := keeper.NewMigrator(*am.keeper, am.legacySubspace) err := cfg.RegisterMigration(types.ModuleName, 1, m.Migrate1to2) if err != nil { panic(err) } -} - -func (am AppModule) LegacyQuerierHandler(amino *codec.LegacyAmino) sdk.Querier { //nolint:staticcheck - return keeper.NewLegacyQuerier(am.keeper, am.keeper.QueryGasLimit()) + err = cfg.RegisterMigration(types.ModuleName, 2, m.Migrate2to3) + if err != nil { + panic(err) + } } // RegisterInvariants registers the wasm module invariants. -func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {} - -// Route returns the message routing key for the wasm module. -func (am AppModule) Route() sdk.Route { - return sdk.NewRoute(RouterKey, NewHandler(keeper.NewDefaultPermissionKeeper(am.keeper))) -} +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // QuerierRoute returns the wasm module's querier route name. func (AppModule) QuerierRoute() string { @@ -200,18 +208,13 @@ func (AppModule) GenerateGenesisState(simState *module.SimulationState) { simulation.RandomizedGenState(simState) } -// ProposalContents doesn't return any content functions for governance proposals. -func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { - return simulation.ProposalContents(am.bankKeeper, am.keeper) -} - -// RandomizedParams creates randomized bank param changes for the simulator. -func (am AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { - return simulation.ParamChanges(r, am.cdc) +// 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(sdr sdk.StoreDecoderRegistry) { +func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) { } // WeightedOperations returns the all the gov module operations with their respective weights. @@ -246,7 +249,7 @@ func ReadWasmConfig(opts servertypes.AppOptions) (types.WasmConfig, error) { } } if v := opts.Get(flagWasmSimulationGasLimit); v != nil { - if raw, ok := v.(string); ok && raw != "" { + if raw, ok := v.(string); !ok || raw != "" { limit, err := cast.ToUint64E(v) // non empty string set if err != nil { return cfg, err @@ -280,7 +283,7 @@ func getExpectedLibwasmVersion() string { return "" } -func checkLibwasmVersion(cmd *cobra.Command, args []string) error { +func checkLibwasmVersion(_ *cobra.Command, _ []string) error { wasmVersion, err := wasmvm.LibwasmvmVersion() if err != nil { return fmt.Errorf("unable to retrieve libwasmversion %w", err) diff --git a/x/wasm/module_integration_test.go b/x/wasm/module_integration_test.go deleted file mode 100644 index 1df572e..0000000 --- a/x/wasm/module_integration_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package wasm_test - -import ( - "testing" - - 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" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - - "github.com/terpnetwork/terp-core/app" - "github.com/terpnetwork/terp-core/x/wasm" -) - -func TestModuleMigrations(t *testing.T) { - wasmApp := app.Setup(false) - ctx := wasmApp.BaseApp.NewContext(false, tmproto.Header{}) - upgradeHandler := func(ctx sdk.Context, plan upgradetypes.Plan, fromVM module.VersionMap) (module.VersionMap, error) { - return wasmApp.ModuleManager().RunMigrations(ctx, wasmApp.ModuleConfigurator(), fromVM) - } - fromVM := wasmApp.UpgradeKeeper.GetModuleVersionMap(ctx) - fromVM[wasm.ModuleName] = 1 // start with initial version - upgradeHandler(ctx, upgradetypes.Plan{Name: "testing"}, fromVM) - // when - gotVM, err := wasmApp.ModuleManager().RunMigrations(ctx, wasmApp.ModuleConfigurator(), fromVM) - // then - require.NoError(t, err) - assert.Equal(t, uint64(2), gotVM[wasm.ModuleName]) -} diff --git a/x/wasm/module_test.go b/x/wasm/module_test.go index 014520f..d405aee 100644 --- a/x/wasm/module_test.go +++ b/x/wasm/module_test.go @@ -3,58 +3,87 @@ package wasm import ( "bytes" "encoding/json" - "fmt" "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/dvsekhvalnov/jose2go/base64url" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" + "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 module.AppModule - ctx sdk.Context - acctKeeper authkeeper.AccountKeeper - keeper Keeper - bankKeeper bankkeeper.Keeper - stakingKeeper stakingkeeper.Keeper - faucet *keeper.TestFaucet + 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") - cdc := keeper.MakeTestCodec(t) + t.Helper() + ctx, keepers := CreateTestInput(t, false, "iterator,staking,stargate,cosmwasm_1_1,cosmwasm_1_2,token_factory") + encConf := keeper.MakeEncodingConfig(t) + queryRouter := baseapp.NewGRPCQueryRouter() + serviceRouter := baseapp.NewMsgServiceRouter() + queryRouter.SetInterfaceRegistry(encConf.InterfaceRegistry) + serviceRouter.SetInterfaceRegistry(encConf.InterfaceRegistry) data := testData{ - module: NewAppModule(cdc, keepers.WasmKeeper, keepers.StakingKeeper, keepers.AccountKeeper, keepers.BankKeeper), - ctx: ctx, - acctKeeper: keepers.AccountKeeper, - keeper: *keepers.WasmKeeper, - bankKeeper: keepers.BankKeeper, - stakingKeeper: keepers.StakingKeeper, - faucet: keepers.Faucet, + 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() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { +func keyPubAddr() sdk.AccAddress { key := ed25519.GenPrivKey() pub := key.PubKey() addr := sdk.AccAddress(pub.Address()) - return key, pub, addr + return addr } func mustLoad(path string) []byte { @@ -66,11 +95,11 @@ func mustLoad(path string) []byte { } var ( - _, _, addrAcc1 = keyPubAddr() - addr1 = addrAcc1.String() - testContract = mustLoad("./keeper/testdata/hackatom.wasm") - maskContract = testdata.ReflectContractWasm() - oldContract = mustLoad("./testdata/escrow_0.7.wasm") + 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) { @@ -117,18 +146,19 @@ func TestHandleCreate(t *testing.T) { t.Run(name, func(t *testing.T) { data := setupTest(t) - h := data.module.Route().Handler() - q := data.module.LegacyQuerierHandler(nil) + 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) - assertCodeBytes(t, q, data.ctx, 1, nil) + 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) + assertCodeList(t, q, data.ctx, 1, data.encConf.Marshaler) }) } } @@ -148,58 +178,58 @@ func TestHandleInstantiate(t *testing.T) { data := setupTest(t) creator := data.faucet.NewFundedRandomAccount(data.ctx, sdk.NewInt64Coin("denom", 100000)) - h := data.module.Route().Handler() - q := data.module.LegacyQuerierHandler(nil) - 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() + bob := keyPubAddr() + fred := keyPubAddr() - initMsg := initMsg{ + initPayload := initMsg{ Verifier: fred, Beneficiary: bob, } - initMsgBz, err := json.Marshal(initMsg) + initMsgBz, err := json.Marshal(initPayload) require.NoError(t, err) // create with no balance is also legal - initCmd := MsgInstantiateContract{ + initMsg := &MsgInstantiateContract{ Sender: creator.String(), CodeID: firstCodeID, Msg: initMsgBz, Funds: nil, Label: "testing", } - res, err = h(data.ctx, &initCmd) + 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, 3, len(res.Events), prettyEvents(res.Events)) - require.Equal(t, "message", res.Events[0].Type) - assertAttribute(t, "module", "wasm", res.Events[0].Attributes[0]) - require.Equal(t, "instantiate", res.Events[1].Type) - require.Equal(t, "wasm", res.Events[2].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[2].Attributes[0]) - - assertCodeList(t, q, data.ctx, 1) - assertCodeBytes(t, q, data.ctx, 1, testContract) - - assertContractList(t, q, data.ctx, 1, []string{contractBech32Addr}) - assertContractInfo(t, q, data.ctx, contractBech32Addr, 1, creator) + 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) { @@ -211,18 +241,17 @@ func TestHandleExecute(t *testing.T) { creator := data.faucet.NewFundedRandomAccount(data.ctx, deposit.Add(deposit...)...) fred := data.faucet.NewFundedRandomAccount(data.ctx, topUp...) - h := data.module.Route().Handler() - q := data.module.LegacyQuerierHandler(nil) - 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() + bob := keyPubAddr() initMsg := initMsg{ Verifier: fred, Beneficiary: bob, @@ -230,28 +259,27 @@ func TestHandleExecute(t *testing.T) { initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) - initCmd := MsgInstantiateContract{ + initCmd := &MsgInstantiateContract{ Sender: creator.String(), CodeID: firstCodeID, Msg: initMsgBz, Funds: deposit, Label: "testing", } - res, err = h(data.ctx, &initCmd) + 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, 6, len(res.Events), prettyEvents(res.Events)) - require.Equal(t, "message", res.Events[0].Type) - assertAttribute(t, "module", "wasm", res.Events[0].Attributes[0]) - require.Equal(t, "coin_spent", res.Events[1].Type) - require.Equal(t, "coin_received", res.Events[2].Type) - require.Equal(t, "transfer", res.Events[3].Type) - require.Equal(t, "instantiate", res.Events[4].Type) - require.Equal(t, "wasm", res.Events[5].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[5].Attributes[0]) + 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) @@ -269,49 +297,48 @@ func TestHandleExecute(t *testing.T) { require.NotNil(t, contractAcct) assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) - execCmd := MsgExecuteContract{ + execCmd := &MsgExecuteContract{ Sender: fred.String(), Contract: contractBech32Addr, Msg: []byte(`{"release":{}}`), Funds: topUp, } - res, err = h(data.ctx, &execCmd) + 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, 10, len(res.Events), prettyEvents(res.Events)) + require.Equal(t, 9, len(res.Events), prettyEvents(res.Events)) - assert.Equal(t, "message", res.Events[0].Type) - assertAttribute(t, "module", "wasm", res.Events[0].Attributes[0]) - assert.Equal(t, "coin_spent", res.Events[1].Type) - assert.Equal(t, "coin_received", res.Events[2].Type) + assert.Equal(t, "coin_spent", res.Events[0].Type) + assert.Equal(t, "coin_received", res.Events[1].Type) - require.Equal(t, "transfer", res.Events[3].Type) - require.Len(t, res.Events[3].Attributes, 3) - assertAttribute(t, "recipient", contractBech32Addr, res.Events[3].Attributes[0]) - assertAttribute(t, "sender", fred.String(), res.Events[3].Attributes[1]) - assertAttribute(t, "amount", "5000denom", res.Events[3].Attributes[2]) + 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[4].Type) + assert.Equal(t, "execute", res.Events[3].Type) // custom contract event attribute - assert.Equal(t, "wasm", res.Events[5].Type) + 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]) - // custom contract event - assert.Equal(t, "wasm-hackatom", res.Events[6].Type) - assertAttribute(t, "_contract_address", contractBech32Addr, res.Events[6].Attributes[0]) - assertAttribute(t, "action", "release", res.Events[6].Attributes[1]) // second transfer (this without conflicting message) - assert.Equal(t, "coin_spent", res.Events[7].Type) - assert.Equal(t, "coin_received", res.Events[8].Type) + assert.Equal(t, "coin_spent", res.Events[6].Type) + assert.Equal(t, "coin_received", res.Events[7].Type) - assert.Equal(t, "transfer", res.Events[9].Type) - assertAttribute(t, "recipient", bob.String(), res.Events[9].Attributes[0]) - assertAttribute(t, "sender", contractBech32Addr, res.Events[9].Attributes[1]) - assertAttribute(t, "amount", "105000denom", res.Events[9].Attributes[2]) + 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 @@ -321,22 +348,21 @@ func TestHandleExecute(t *testing.T) { 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) - assertCodeBytes(t, q, data.ctx, 1, testContract) + 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}) - assertContractInfo(t, q, data.ctx, contractBech32Addr, 1, creator) + 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) { @@ -348,16 +374,16 @@ func TestHandleExecuteEscrow(t *testing.T) { data.faucet.Fund(data.ctx, creator, sdk.NewInt64Coin("denom", 100000)) fred := data.faucet.NewFundedRandomAccount(data.ctx, topUp...) - h := data.module.Route().Handler() - msg := &MsgStoreCode{ Sender: creator.String(), WASMByteCode: testContract, } - res, err := h(data.ctx, msg) + + h := data.msgServiceRouter.Handler(msg) + _, err := h(data.ctx, msg) require.NoError(t, err) - _, _, bob := keyPubAddr() + bob := keyPubAddr() initMsg := map[string]interface{}{ "verifier": fred.String(), "beneficiary": bob.String(), @@ -372,7 +398,8 @@ func TestHandleExecuteEscrow(t *testing.T) { Funds: deposit, Label: "testing", } - res, err = h(data.ctx, &initCmd) + 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) @@ -389,6 +416,7 @@ func TestHandleExecuteEscrow(t *testing.T) { 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 @@ -408,9 +436,17 @@ func TestHandleExecuteEscrow(t *testing.T) { } 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 AppOptionsMock + src servertypes.AppOptions exp types.WasmConfig }{ "set query gas limit via opts": { @@ -442,8 +478,26 @@ func TestReadWasmConfig(t *testing.T) { }, }, "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) { @@ -489,99 +543,110 @@ func prettyAttrs(attrs []abci.EventAttribute) []sdk.Attribute { } func prettyAttr(attr abci.EventAttribute) sdk.Attribute { - return sdk.NewAttribute(string(attr.Key), string(attr.Value)) + 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, string(attr.Key), prettyAttr(attr)) - assert.Equal(t, value, string(attr.Value), prettyAttr(attr)) + assert.Equal(t, key, attr.Key, prettyAttr(attr)) + assert.Equal(t, value, attr.Value, prettyAttr(attr)) } -func assertCodeList(t *testing.T, q sdk.Querier, ctx sdk.Context, expectedNum int) { - bz, sdkerr := q(ctx, []string{QueryListCode}, abci.RequestQuery{}) +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 []CodeInfo - err := json.Unmarshal(bz, &res) - require.NoError(t, err) - - assert.Equal(t, expectedNum, len(res)) + var res types.QueryCodesResponse + require.NoError(t, marshaler.Unmarshal(bz, &res)) + assert.Equal(t, expectedNum, len(res.CodeInfos)) } -func assertCodeBytes(t *testing.T, q sdk.Querier, ctx sdk.Context, codeID uint64, expectedBytes []byte) { - path := []string{QueryGetCode, fmt.Sprintf("%d", codeID)} - bz, sdkerr := q(ctx, path, abci.RequestQuery{}) - require.NoError(t, sdkerr) +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 { - require.Equal(t, len(bz), 0, "%q", string(bz)) + assert.ErrorIs(t, err, types.ErrNotFound) return } - var res map[string]interface{} - err := json.Unmarshal(bz, &res) require.NoError(t, err) + require.True(t, resp.IsOK()) + bz = resp.Value - require.Contains(t, res, "data") - b, err := base64url.Decode(res["data"].(string)) - require.NoError(t, err) - assert.Equal(t, expectedBytes, b) - assert.EqualValues(t, codeID, res["id"]) + var rsp types.QueryCodeResponse + require.NoError(t, marshaler.Unmarshal(bz, &rsp)) + assert.Equal(t, expectedBytes, rsp.Data) } -func assertContractList(t *testing.T, q sdk.Querier, ctx sdk.Context, codeID uint64, expContractAddrs []string) { - bz, sdkerr := q(ctx, []string{QueryListContractByCode, fmt.Sprintf("%d", codeID)}, abci.RequestQuery{}) - require.NoError(t, sdkerr) +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) - if len(bz) == 0 { - require.Equal(t, len(expContractAddrs), 0) + 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 res []string - err := json.Unmarshal(bz, &res) - require.NoError(t, err) + var rsp types.QueryContractsByCodeResponse + require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - hasAddrs := make([]string, len(res)) - for i, r := range res { + 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 sdk.Querier, ctx sdk.Context, contractBech32Addr string, expected state) { +func assertContractState(t *testing.T, q *baseapp.GRPCQueryRouter, ctx sdk.Context, contractBech32Addr string, expected state, marshaler codec.Codec) { t.Helper() - path := []string{QueryGetContractState, contractBech32Addr, keeper.QueryMethodContractStateAll} - bz, sdkerr := q(ctx, path, abci.RequestQuery{}) - require.NoError(t, sdkerr) - - var res []Model - err := json.Unmarshal(bz, &res) + bz, err := marshaler.Marshal(&types.QueryRawContractStateRequest{Address: contractBech32Addr, QueryData: []byte("config")}) require.NoError(t, err) - require.Equal(t, 1, len(res), "#v", res) - require.Equal(t, []byte("config"), []byte(res[0].Key)) + 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, res[0].Value) + assert.Equal(t, expectedBz, rsp.Data) } -func assertContractInfo(t *testing.T, q sdk.Querier, ctx sdk.Context, contractBech32Addr string, codeID uint64, creator sdk.AccAddress) { +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() - path := []string{QueryGetContract, contractBech32Addr} - bz, sdkerr := q(ctx, path, abci.RequestQuery{}) + 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 res ContractInfo - err := json.Unmarshal(bz, &res) - require.NoError(t, err) + var rsp types.QueryContractInfoResponse + require.NoError(t, marshaler.Unmarshal(bz, &rsp)) - assert.Equal(t, codeID, res.CodeID) - assert.Equal(t, creator.String(), res.Creator) + 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 index 28549cb..932bebb 100644 --- a/x/wasm/relay_pingpong_test.go +++ b/x/wasm/relay_pingpong_test.go @@ -5,15 +5,14 @@ import ( "fmt" "testing" - ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - ibctesting "github.com/cosmos/ibc-go/v4/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" - "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" - clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/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" @@ -49,8 +48,8 @@ func TestPinPong(t *testing.T) { wasmtesting.NewIBCContractMockWasmer(pongContract), )} coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts, chainBOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + 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 ( @@ -137,7 +136,7 @@ type player struct { // Execute starts the ping pong game // Contracts finds all connected channels and broadcasts a ping message -func (p *player) 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) { +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 @@ -175,7 +174,7 @@ func (p *player) Execute(code wasmvm.Checksum, env wasmvmtypes.Env, info wasmvmt } // OnIBCChannelOpen ensures to accept only configured version -func (p player) 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) { +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 } @@ -183,7 +182,7 @@ func (p player) IBCChannelOpen(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg } // OnIBCChannelConnect persists connection endpoints -func (p player) 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) { +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 } @@ -199,20 +198,6 @@ var ( // store keys maxValueKey = []byte("max-value") ) -func (p player) loadEndpoints(store prefix.Store, channelID string) *connectedChannelsModel { - var counterparties []connectedChannelsModel - if bz := store.Get(ibcEndpointsKey); bz != nil { - require.NoError(p.t, json.Unmarshal(bz, &counterparties)) - } - for _, v := range counterparties { - if v.Our.ChannelID == channelID { - return &v - } - } - p.t.Fatalf("no counterparty found for channel %q", channelID) - return nil -} - func (p player) storeEndpoint(store wasmvm.KVStore, channel wasmvmtypes.IBCChannel) { var counterparties []connectedChannelsModel if b := store.Get(ibcEndpointsKey); b != nil { @@ -224,7 +209,7 @@ func (p player) storeEndpoint(store wasmvm.KVStore, channel wasmvmtypes.IBCChann store.Set(ibcEndpointsKey, bz) } -func (p player) 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) { +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") } @@ -237,7 +222,7 @@ var ( // store keys ) // IBCPacketReceive receives the hit and serves a response hit via `wasmvmtypes.IBCPacket` -func (p player) 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) { +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 @@ -283,7 +268,7 @@ func (p player) IBCPacketReceive(codeID wasmvm.Checksum, env wasmvmtypes.Env, ms } // OnIBCPacketAcknowledgement handles the packet acknowledgment frame. Stops the game on an any error -func (p player) 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) { +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 { @@ -305,7 +290,7 @@ func (p player) IBCPacketAck(codeID wasmvm.Checksum, env wasmvmtypes.Env, msg wa return &wasmvmtypes.IBCBasicResponse{}, 0, nil } -func (p player) 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) { +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") } diff --git a/x/wasm/relay_test.go b/x/wasm/relay_test.go index a809d58..9b3cc20 100644 --- a/x/wasm/relay_test.go +++ b/x/wasm/relay_test.go @@ -6,14 +6,15 @@ import ( "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" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - ibctransfertypes "github.com/cosmos/ibc-go/v4/modules/apps/transfer/types" - clienttypes "github.com/cosmos/ibc-go/v4/modules/core/02-client/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - ibctesting "github.com/cosmos/ibc-go/v4/testing" + 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" @@ -31,38 +32,51 @@ func TestFromIBCTransferToContract(t *testing.T) { transferAmount := sdk.NewInt(1) specs := map[string]struct { - contract wasmtesting.IBCContractCallbacks - setupContract func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) - expChainABalanceDiff sdk.Int - expChainBBalanceDiff sdk.Int + 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) { + t.Helper() c := contract.(*ackReceiverContract) c.t = t c.chain = chain }, - expChainABalanceDiff: transferAmount.Neg(), - expChainBBalanceDiff: transferAmount, + expChainAPendingSendPackets: 0, + expChainBPendingSendPackets: 0, + expChainABalanceDiff: transferAmount.Neg(), + expChainBBalanceDiff: transferAmount, }, "nack": { contract: &nackReceiverContract{}, setupContract: func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) { + t.Helper() c := contract.(*nackReceiverContract) c.t = t }, - expChainABalanceDiff: sdk.ZeroInt(), - expChainBBalanceDiff: sdk.ZeroInt(), + expChainAPendingSendPackets: 0, + expChainBPendingSendPackets: 0, + expChainABalanceDiff: sdk.ZeroInt(), + expChainBBalanceDiff: sdk.ZeroInt(), }, "error": { contract: &errorReceiverContract{}, setupContract: func(t *testing.T, contract wasmtesting.IBCContractCallbacks, chain *wasmibctesting.TestChain) { + t.Helper() c := contract.(*errorReceiverContract) c.t = t }, - expChainABalanceDiff: sdk.ZeroInt(), - expChainBBalanceDiff: sdk.ZeroInt(), + expChainAPendingSendPackets: 1, + expChainBPendingSendPackets: 0, + expChainABalanceDiff: transferAmount.Neg(), + expChainBBalanceDiff: sdk.ZeroInt(), + expErr: true, }, } for name, spec := range specs { @@ -72,8 +86,8 @@ func TestFromIBCTransferToContract(t *testing.T) { wasmtesting.NewIBCContractMockWasmer(spec.contract), )} coordinator = wasmibctesting.NewCoordinator(t, 2, []wasmkeeper.Option{}, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) ) coordinator.CommitBlock(chainA, chainB) myContractAddr := chainB.SeedNewContractInstance() @@ -100,7 +114,7 @@ func TestFromIBCTransferToContract(t *testing.T) { // 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) + 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()) @@ -111,11 +125,15 @@ func TestFromIBCTransferToContract(t *testing.T) { // and when relay to chain B and handle Ack on chain A err = coordinator.RelayAndAckPendingPackets(path) - require.NoError(t, err) + if spec.expErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } // then - require.Equal(t, 0, len(chainA.PendingSendPackets)) - require.Equal(t, 0, len(chainB.PendingSendPackets)) + 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) @@ -143,8 +161,8 @@ func TestContractCanInitiateIBCTransferMsg(t *testing.T) { wasmtesting.NewIBCContractMockWasmer(myContract)), } coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) ) myContractAddr := chainA.SeedNewContractInstance() coordinator.CommitBlock(chainA, chainB) @@ -177,6 +195,7 @@ func TestContractCanInitiateIBCTransferMsg(t *testing.T) { ReceiverAddr: receiverAddress.String(), }.GetBytes(), } + // trigger contract to start the transfer _, err := chainA.SendMsgs(startMsg) require.NoError(t, err) @@ -214,8 +233,8 @@ func TestContractCanEmulateIBCTransferMessage(t *testing.T) { } coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) ) myContractAddr := chainA.SeedNewContractInstance() myContract.contractAddr = myContractAddr.String() @@ -289,8 +308,8 @@ func TestContractCanEmulateIBCTransferMessageWithTimeout(t *testing.T) { } coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) ) coordinator.CommitBlock(chainA, chainB) myContractAddr := chainA.SeedNewContractInstance() @@ -375,8 +394,8 @@ func TestContractEmulateIBCTransferMessageOnDiffContractIBCChannel(t *testing.T) coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) ) coordinator.CommitBlock(chainA, chainB) @@ -437,8 +456,8 @@ func TestContractHandlesChannelClose(t *testing.T) { } coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts, chainBOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) ) coordinator.CommitBlock(chainA, chainB) @@ -485,8 +504,8 @@ func TestContractHandlesChannelCloseNotOwned(t *testing.T) { } coordinator = wasmibctesting.NewCoordinator(t, 2, chainAOpts, chainBOpts) - chainA = coordinator.GetChain(wasmibctesting.GetChainID(0)) - chainB = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainA = coordinator.GetChain(wasmibctesting.GetChainID(1)) + chainB = coordinator.GetChain(wasmibctesting.GetChainID(2)) ) coordinator.CommitBlock(chainA, chainB) @@ -531,7 +550,7 @@ type captureCloseContract struct { closeCalled bool } -func (c *captureCloseContract) 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) { +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 } @@ -544,7 +563,7 @@ type sendViaIBCTransferContract struct { t *testing.T } -func (s *sendViaIBCTransferContract) 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) { +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 @@ -555,7 +574,7 @@ func (s *sendViaIBCTransferContract) Execute(code wasmvm.Checksum, env wasmvmtyp Amount: wasmvmtypes.NewCoin(in.CoinsToSend.Amount.Uint64(), in.CoinsToSend.Denom), ChannelID: in.ChannelID, Timeout: wasmvmtypes.IBCTimeout{Block: &wasmvmtypes.IBCTimeoutBlock{ - Revision: 0, + Revision: 1, Height: 110, }}, }, @@ -574,7 +593,7 @@ type sendEmulatedIBCTransferContract struct { contractAddr string } -func (s *sendEmulatedIBCTransferContract) 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) { +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 @@ -583,7 +602,7 @@ func (s *sendEmulatedIBCTransferContract) Execute(code wasmvm.Checksum, env wasm 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, + in.CoinsToSend.Denom, in.CoinsToSend.Amount.String(), info.Sender, in.ReceiverAddr, "memo", ) if err := dataPacket.ValidateBasic(); err != nil { return nil, 0, err @@ -599,7 +618,7 @@ func (s *sendEmulatedIBCTransferContract) Execute(code wasmvm.Checksum, env wasm return &wasmvmtypes.Response{Messages: []wasmvmtypes.SubMsg{{ReplyOn: wasmvmtypes.ReplyNever, Msg: wasmvmtypes.CosmosMsg{IBC: ibcMsg}}}}, 0, nil } -func (c *sendEmulatedIBCTransferContract) 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) { +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 @@ -625,14 +644,13 @@ var _ wasmtesting.IBCContractCallbacks = &closeChannelContract{} type closeChannelContract struct { contractStub - t *testing.T } -func (c *closeChannelContract) 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) { +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 (s *closeChannelContract) 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) { +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 @@ -684,7 +702,7 @@ type ackReceiverContract struct { chain *wasmibctesting.TestChain } -func (c *ackReceiverContract) 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) { +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 @@ -698,7 +716,7 @@ func (c *ackReceiverContract) IBCPacketReceive(codeID wasmvm.Checksum, env wasmv 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, sdkerrors.Wrap(err, "within our smart contract") + return nil, 0, errorsmod.Wrap(err, "within our smart contract") } var log []wasmvmtypes.EventAttribute // note: all events are under `wasm` event type @@ -706,7 +724,7 @@ func (c *ackReceiverContract) IBCPacketReceive(codeID wasmvm.Checksum, env wasmv return &wasmvmtypes.IBCReceiveResult{Ok: &wasmvmtypes.IBCReceiveResponse{Acknowledgement: ack, Attributes: log}}, 0, nil } -func (c *ackReceiverContract) 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) { +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 @@ -723,7 +741,7 @@ func (c *ackReceiverContract) IBCPacketAck(codeID wasmvm.Checksum, env wasmvmtyp ibcPacket := toIBCPacket(msg.OriginalPacket) err := c.chain.App.TransferKeeper.OnAcknowledgementPacket(ctx, ibcPacket, data, ack) if err != nil { - return nil, 0, sdkerrors.Wrap(err, "within our smart contract") + return nil, 0, errorsmod.Wrap(err, "within our smart contract") } return &wasmvmtypes.IBCBasicResponse{}, 0, nil @@ -735,7 +753,7 @@ type nackReceiverContract struct { t *testing.T } -func (c *nackReceiverContract) 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) { +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 @@ -752,7 +770,7 @@ type errorReceiverContract struct { t *testing.T } -func (c *errorReceiverContract) 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) { +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 @@ -766,27 +784,27 @@ func (c *errorReceiverContract) IBCPacketReceive(codeID wasmvm.Checksum, env was // simple helper struct that implements connection setup methods. type contractStub struct{} -func (s *contractStub) 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) { +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(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) { +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(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) { +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(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) { +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(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) { +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(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 (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") } diff --git a/x/wasm/simulation/operations.go b/x/wasm/simulation/operations.go index cd885cc..5ff14e4 100644 --- a/x/wasm/simulation/operations.go +++ b/x/wasm/simulation/operations.go @@ -5,13 +5,16 @@ import ( "math/rand" "os" + errorsmod "cosmossdk.io/errors" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" "github.com/cosmos/cosmos-sdk/baseapp" - simappparams "github.com/cosmos/cosmos-sdk/simapp/params" + "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" "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" @@ -35,6 +38,7 @@ const ( // 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) @@ -109,11 +113,10 @@ func WeightedOperations( panic(err) } } - return simulation.WeightedOperations{ simulation.NewWeightedOperation( weightMsgStoreCode, - SimulateMsgStoreCode(ak, bk, wasmKeeper, wasmBz, 5_000_000), + SimulateMsgStoreCode(ak, bk, wasmKeeper, wasmBz), ), simulation.NewWeightedOperation( weightMsgInstantiateContract, @@ -322,7 +325,12 @@ func SimulateMsgUpdateAmin( } // SimulateMsgStoreCode generates a MsgStoreCode with random values -func SimulateMsgStoreCode(ak types.AccountKeeper, bk BankKeeper, wasmKeeper WasmKeeper, wasmBz []byte, gas uint64) simtypes.Operation { +func SimulateMsgStoreCode( + ak types.AccountKeeper, + bk BankKeeper, + wasmKeeper WasmKeeper, + wasmBz []byte, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, @@ -345,7 +353,7 @@ func SimulateMsgStoreCode(ak types.AccountKeeper, bk BankKeeper, wasmKeeper Wasm InstantiatePermission: &config, } txCtx := BuildOperationInput(r, app, ctx, &msg, simAccount, ak, bk, nil) - return GenAndDeliverTxWithRandFees(txCtx, gas) + return simulation.GenAndDeliverTxWithRandFees(txCtx) } } @@ -366,7 +374,12 @@ func DefaultSimulationCodeIDSelector(ctx sdk.Context, wasmKeeper WasmKeeper) uin } // SimulateMsgInstantiateContract generates a MsgInstantiateContract with random values -func SimulateMsgInstantiateContract(ak types.AccountKeeper, bk BankKeeper, wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.Operation { +func SimulateMsgInstantiateContract( + ak types.AccountKeeper, + bk BankKeeper, + wasmKeeper WasmKeeper, + codeSelector CodeIDSelector, +) simtypes.Operation { return func( r *rand.Rand, app *baseapp.BaseApp, @@ -475,10 +488,12 @@ func BuildOperationInput( 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: simappparams.MakeTestEncodingConfig().TxConfig, + TxGen: txConfig, Cdc: nil, Msg: msg, MsgType: msg.Type(), @@ -506,23 +521,23 @@ func DefaultSimulationExecuteSenderSelector(wasmKeeper WasmKeeper, ctx sdk.Conte var none simtypes.Account bz, err := json.Marshal(testdata.ReflectQueryMsg{Owner: &struct{}{}}) if err != nil { - return none, sdkerrors.Wrap(err, "build smart query") + return none, errorsmod.Wrap(err, "build smart query") } got, err := wasmKeeper.QuerySmart(ctx, contractAddr, bz) if err != nil { - return none, sdkerrors.Wrap(err, "exec smart query") + return none, errorsmod.Wrap(err, "exec smart query") } var ownerRes testdata.OwnerResponse if err := json.Unmarshal(got, &ownerRes); err != nil || ownerRes.Owner == "" { - return none, sdkerrors.Wrap(err, "parse smart query response") + return none, errorsmod.Wrap(err, "parse smart query response") } ownerAddr, err := sdk.AccAddressFromBech32(ownerRes.Owner) if err != nil { - return none, sdkerrors.Wrap(err, "parse contract owner address") + return none, errorsmod.Wrap(err, "parse contract owner address") } simAccount, ok := simtypes.FindAccount(accs, ownerAddr) if !ok { - return none, sdkerrors.Wrap(err, "unknown contract owner address") + return none, errorsmod.Wrap(err, "unknown contract owner address") } return simAccount, nil } diff --git a/x/wasm/simulation/params.go b/x/wasm/simulation/params.go deleted file mode 100644 index b707259..0000000 --- a/x/wasm/simulation/params.go +++ /dev/null @@ -1,32 +0,0 @@ -package simulation - -import ( - "fmt" - "math/rand" - - "github.com/cosmos/cosmos-sdk/codec" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" - - "github.com/terpnetwork/terp-core/x/wasm/types" -) - -func ParamChanges(r *rand.Rand, cdc codec.Codec) []simtypes.ParamChange { - params := types.DefaultParams() - return []simtypes.ParamChange{ - simulation.NewSimParamChange(types.ModuleName, string(types.ParamStoreKeyUploadAccess), - func(r *rand.Rand) string { - jsonBz, err := cdc.MarshalJSON(¶ms.CodeUploadAccess) - if err != nil { - panic(err) - } - return string(jsonBz) - }, - ), - simulation.NewSimParamChange(types.ModuleName, string(types.ParamStoreKeyInstantiateAccess), - func(r *rand.Rand) string { - return fmt.Sprintf("%q", params.CodeUploadAccess.Permission.String()) - }, - ), - } -} diff --git a/x/wasm/simulation/proposals.go b/x/wasm/simulation/proposals.go index a8597ff..04a4c08 100644 --- a/x/wasm/simulation/proposals.go +++ b/x/wasm/simulation/proposals.go @@ -26,14 +26,9 @@ const ( WeightStoreAndInstantiateContractProposal = "weight_store_and_instantiate_contract_proposal" ) -func ProposalContents(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedProposalContent { - return []simtypes.WeightedProposalContent{ - // simulation.NewWeightedProposalContent( - // WeightStoreCodeProposal, - // params.DefaultWeightStoreCodeProposal, - // SimulateStoreCodeProposal(wasmKeeper), - // ), - simulation.NewWeightedProposalContent( +func ProposalMsgs(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedProposalMsg { + return []simtypes.WeightedProposalMsg{ + simulation.NewWeightedProposalMsg( WeightInstantiateContractProposal, params.DefaultWeightInstantiateContractProposal, SimulateInstantiateContractProposal( @@ -42,7 +37,7 @@ func ProposalContents(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedP DefaultSimulationCodeIDSelector, ), ), - simulation.NewWeightedProposalContent( + simulation.NewWeightedProposalMsg( WeightUpdateAdminProposal, params.DefaultWeightUpdateAdminProposal, SimulateUpdateAdminProposal( @@ -50,7 +45,7 @@ func ProposalContents(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedP DefaultSimulateUpdateAdminProposalContractSelector, ), ), - simulation.NewWeightedProposalContent( + simulation.NewWeightedProposalMsg( WeightExeContractProposal, params.DefaultWeightExecuteContractProposal, SimulateExecuteContractProposal( @@ -61,7 +56,7 @@ func ProposalContents(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedP DefaultSimulationExecutePayloader, ), ), - simulation.NewWeightedProposalContent( + simulation.NewWeightedProposalMsg( WeightClearAdminProposal, params.DefaultWeightClearAdminProposal, SimulateClearAdminProposal( @@ -69,7 +64,7 @@ func ProposalContents(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedP DefaultSimulateContractSelector, ), ), - simulation.NewWeightedProposalContent( + simulation.NewWeightedProposalMsg( WeightMigrateContractProposal, params.DefaultWeightMigrateContractProposal, SimulateMigrateContractProposal( @@ -78,15 +73,7 @@ func ProposalContents(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedP DefaultSimulationCodeIDSelector, ), ), - // simulation.NewWeightedProposalContent( - // WeightSudoContractProposal, - // params.DefaultWeightSudoContractProposal, - // SimulateSudoContractProposal( - // wasmKeeper, - // DefaultSimulateContractSelector, - // ), - // ), - simulation.NewWeightedProposalContent( + simulation.NewWeightedProposalMsg( WeightPinCodesProposal, params.DefaultWeightPinCodesProposal, SimulatePinContractProposal( @@ -94,7 +81,7 @@ func ProposalContents(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedP DefaultSimulationCodeIDSelector, ), ), - simulation.NewWeightedProposalContent( + simulation.NewWeightedProposalMsg( WeightUnpinCodesProposal, params.DefaultWeightUnpinCodesProposal, SimulateUnpinContractProposal( @@ -102,7 +89,7 @@ func ProposalContents(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedP DefaultSimulationCodeIDSelector, ), ), - simulation.NewWeightedProposalContent( + simulation.NewWeightedProposalMsg( WeightUpdateInstantiateConfigProposal, params.DefaultWeightUpdateInstantiateConfigProposal, SimulateUpdateInstantiateConfigProposal( @@ -110,45 +97,35 @@ func ProposalContents(bk BankKeeper, wasmKeeper WasmKeeper) []simtypes.WeightedP DefaultSimulationCodeIDSelector, ), ), - // simulation.NewWeightedProposalContent( - // WeightStoreAndInstantiateContractProposal, - // params.DefaultWeightStoreAndInstantiateContractProposal, - // SimulateStoreAndInstantiateContractProposal( - // wasmKeeper, - // ), - // ), } } // 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.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +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.NewStoreCodeProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - simAccount.Address.String(), - wasmBz, - &permission, - false, - "", - "", - []byte{}, - ) + return &types.MsgStoreCode{ + Sender: authority, + WASMByteCode: wasmBz, + InstantiatePermission: &permission, + } } } // Simulate instantiate contract proposal -func SimulateInstantiateContractProposal(bk BankKeeper, wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { - simAccount, _ := simtypes.RandomAcc(r, accs) +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 @@ -157,56 +134,44 @@ func SimulateInstantiateContractProposal(bk BankKeeper, wasmKeeper WasmKeeper, c return nil } - return types.NewInstantiateContractProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - simAccount.Address.String(), - adminAccount.Address.String(), - codeID, - simtypes.RandStringOfLength(r, 10), - []byte(`{}`), - sdk.Coins{}, - ) + 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( - bk BankKeeper, + _ BankKeeper, wasmKeeper WasmKeeper, contractSelector MsgExecuteContractSelector, senderSelector MsgExecuteSenderSelector, payloader MsgExecutePayloader, -) simtypes.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +) 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 } - simAccount, err := senderSelector(wasmKeeper, ctx, ctAddress, accs) - if err != nil { - return nil - } - - msg := types.MsgExecuteContract{ - Sender: simAccount.Address.String(), + msg := &types.MsgExecuteContract{ + Sender: authority, Contract: ctAddress.String(), Funds: sdk.Coins{}, } - if err := payloader(&msg); err != nil { + if err := payloader(msg); err != nil { return nil } - return types.NewExecuteContractProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - simAccount.Address.String(), - ctAddress.String(), - msg.Msg, - sdk.Coins{}, - ) + return msg } } @@ -231,20 +196,20 @@ func DefaultSimulateUpdateAdminProposalContractSelector( } // Simulate update admin contract proposal -func SimulateUpdateAdminProposal(wasmKeeper WasmKeeper, contractSelector UpdateAdminContractSelector) simtypes.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +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.NewUpdateAdminProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - simtypes.RandomAccounts(r, 1)[0].Address.String(), - ctAddress.String(), - ) + return &types.MsgUpdateAdmin{ + Sender: authority, + NewAdmin: simtypes.RandomAccounts(r, 1)[0].Address.String(), + Contract: ctAddress.String(), + } } } @@ -263,26 +228,28 @@ func DefaultSimulateContractSelector( } // Simulate clear admin proposal -func SimulateClearAdminProposal(wasmKeeper WasmKeeper, contractSelector ClearAdminContractSelector) simtypes.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +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.NewClearAdminProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - ctAddress.String(), - ) + 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.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +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 @@ -293,70 +260,74 @@ func SimulateMigrateContractProposal(wasmKeeper WasmKeeper, contractSelector Mig return nil } - return types.NewMigrateContractProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - ctAddress.String(), - codeID, - []byte(`{}`), - ) + 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.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +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.NewSudoContractProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - ctAddress.String(), - []byte(`{}`), - ) + return &types.MsgSudoContract{ + Authority: authority, + Contract: ctAddress.String(), + Msg: []byte(`{}`), + } } } // Simulate pin contract proposal -func SimulatePinContractProposal(wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +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.NewPinCodesProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - []uint64{codeID}, - ) + return &types.MsgPinCodes{ + Authority: authority, + CodeIDs: []uint64{codeID}, + } } } // Simulate unpin contract proposal -func SimulateUnpinContractProposal(wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +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.NewUnpinCodesProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - []uint64{codeID}, - ) + return &types.MsgUnpinCodes{ + Authority: authority, + CodeIDs: []uint64{codeID}, + } } } // Simulate update instantiate config proposal -func SimulateUpdateInstantiateConfigProposal(wasmKeeper WasmKeeper, codeSelector CodeIDSelector) simtypes.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +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 @@ -366,41 +337,33 @@ func SimulateUpdateInstantiateConfigProposal(wasmKeeper WasmKeeper, codeSelector permission := wasmKeeper.GetParams(ctx).InstantiateDefaultPermission config := permission.With(simAccount.Address) - configUpdate := types.AccessConfigUpdate{ - CodeID: codeID, - InstantiatePermission: config, + return &types.MsgUpdateInstantiateConfig{ + Sender: authority, + CodeID: codeID, + NewInstantiatePermission: &config, } - - return types.NewUpdateInstantiateConfigProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - configUpdate, - ) } } -func SimulateStoreAndInstantiateContractProposal(wasmKeeper WasmKeeper) simtypes.ContentSimulatorFn { - return func(r *rand.Rand, ctx sdk.Context, accs []simtypes.Account) simtypes.Content { +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.NewStoreAndInstantiateContractProposal( - simtypes.RandStringOfLength(r, 10), - simtypes.RandStringOfLength(r, 10), - simAccount.Address.String(), - wasmBz, - "", - "", - []byte{}, - &permission, - false, - adminAccount.Address.String(), - simtypes.RandStringOfLength(r, 10), - []byte(`{}`), - sdk.Coins{}, - ) + 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/simulation/sim_utils.go b/x/wasm/simulation/sim_utils.go deleted file mode 100644 index 4f9a00b..0000000 --- a/x/wasm/simulation/sim_utils.go +++ /dev/null @@ -1,53 +0,0 @@ -package simulation - -import ( - "github.com/cosmos/cosmos-sdk/simapp/helpers" - sdk "github.com/cosmos/cosmos-sdk/types" - simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/simulation" -) - -// GenAndDeliverTxWithRandFees generates a transaction with a random fee and delivers it. -func GenAndDeliverTxWithRandFees(txCtx simulation.OperationInput, gas uint64) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - account := txCtx.AccountKeeper.GetAccount(txCtx.Context, txCtx.SimAccount.Address) - spendable := txCtx.Bankkeeper.SpendableCoins(txCtx.Context, account.GetAddress()) - - var fees sdk.Coins - var err error - - coins, hasNeg := spendable.SafeSub(txCtx.CoinsSpentInMsg) - if hasNeg { - return simtypes.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "message doesn't leave room for fees"), nil, err - } - - fees, err = simtypes.RandomFees(txCtx.R, txCtx.Context, coins) - if err != nil { - return simtypes.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to generate fees"), nil, err - } - return GenAndDeliverTx(txCtx, fees, gas) -} - -// GenAndDeliverTx generates a transactions and delivers it. -func GenAndDeliverTx(txCtx simulation.OperationInput, fees sdk.Coins, gas uint64) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { - account := txCtx.AccountKeeper.GetAccount(txCtx.Context, txCtx.SimAccount.Address) - tx, err := helpers.GenTx( - txCtx.TxGen, - []sdk.Msg{txCtx.Msg}, - fees, - gas, - txCtx.Context.ChainID(), - []uint64{account.GetAccountNumber()}, - []uint64{account.GetSequence()}, - txCtx.SimAccount.PrivKey, - ) - if err != nil { - return simtypes.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to generate mock tx"), nil, err - } - - _, _, err = txCtx.App.Deliver(txCtx.TxGen.TxEncoder(), tx) - if err != nil { - return simtypes.NoOpMsg(txCtx.ModuleName, txCtx.MsgType, "unable to deliver tx"), nil, err - } - - return simtypes.NewOperationMsg(txCtx.Msg, true, "", txCtx.Cdc), nil, nil -} diff --git a/x/wasm/types/authz.go b/x/wasm/types/authz.go index 10dd260..9692088 100644 --- a/x/wasm/types/authz.go +++ b/x/wasm/types/authz.go @@ -3,13 +3,12 @@ package types import ( "strings" - "github.com/gogo/protobuf/proto" - + 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) @@ -109,7 +108,7 @@ func validateGrants(g []ContractGrant) error { } for i, v := range g { if err := v.ValidateBasic(); err != nil { - return sdkerrors.Wrapf(err, "position %d", i) + return errorsmod.Wrapf(err, "position %d", i) } } // allow multiple grants for a contract: @@ -146,7 +145,7 @@ func AcceptGrantedMessage[T AuthzableWasmMsg](ctx sdk.Context, grants []Contract result, err := g.GetLimit().Accept(ctx, exec) switch { case err != nil: - return authztypes.AcceptResponse{}, sdkerrors.Wrap(err, "limit") + 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: @@ -158,7 +157,7 @@ func AcceptGrantedMessage[T AuthzableWasmMsg](ctx sdk.Context, grants []Contract ok, err := g.GetFilter().Accept(ctx, exec.GetMsg()) switch { case err != nil: - return authztypes.AcceptResponse{}, sdkerrors.Wrap(err, "filter") + return authztypes.AcceptResponse{}, errorsmod.Wrap(err, "filter") case !ok: // no limit update and continue with next grant continue @@ -229,7 +228,7 @@ func NewContractGrant(contract sdk.AccAddress, limit ContractAuthzLimitX, filter } anyFilter, err := cdctypes.NewAnyWithValue(pFilter) if err != nil { - return nil, sdkerrors.Wrap(err, "filter") + return nil, errorsmod.Wrap(err, "filter") } return ContractGrant{ Contract: contract.String(), @@ -245,7 +244,7 @@ func (g ContractGrant) WithNewLimits(limit ContractAuthzLimitX) (*ContractGrant, } anyLimit, err := cdctypes.NewAnyWithValue(pLimit) if err != nil { - return nil, sdkerrors.Wrap(err, "limit") + return nil, errorsmod.Wrap(err, "limit") } return &ContractGrant{ @@ -259,11 +258,11 @@ func (g ContractGrant) WithNewLimits(limit ContractAuthzLimitX) (*ContractGrant, func (g ContractGrant) UnpackInterfaces(unpacker cdctypes.AnyUnpacker) error { var f ContractAuthzFilterX if err := unpacker.UnpackAny(g.Filter, &f); err != nil { - return sdkerrors.Wrap(err, "filter") + return errorsmod.Wrap(err, "filter") } var l ContractAuthzLimitX if err := unpacker.UnpackAny(g.Limit, &l); err != nil { - return sdkerrors.Wrap(err, "limit") + return errorsmod.Wrap(err, "limit") } return nil } @@ -295,15 +294,15 @@ func (g ContractGrant) GetFilter() ContractAuthzFilterX { // ValidateBasic validates the grant func (g ContractGrant) ValidateBasic() error { if _, err := sdk.AccAddressFromBech32(g.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } // execution limits if err := g.GetLimit().ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "limit") + return errorsmod.Wrap(err, "limit") } // filter if err := g.GetFilter().ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "filter") + return errorsmod.Wrap(err, "filter") } return nil } @@ -312,7 +311,7 @@ func (g ContractGrant) ValidateBasic() error { type UndefinedFilter struct{} // Accept always returns error -func (f *UndefinedFilter) Accept(ctx sdk.Context, msg RawContractMessage) (bool, error) { +func (f *UndefinedFilter) Accept(_ sdk.Context, _ RawContractMessage) (bool, error) { return false, sdkerrors.ErrNotFound.Wrapf("undefined filter") } @@ -327,7 +326,7 @@ func NewAllowAllMessagesFilter() *AllowAllMessagesFilter { } // Accept accepts any valid json message content. -func (f *AllowAllMessagesFilter) Accept(ctx sdk.Context, msg RawContractMessage) (bool, error) { +func (f *AllowAllMessagesFilter) Accept(_ sdk.Context, msg RawContractMessage) (bool, error) { return true, msg.ValidateBasic() } @@ -380,7 +379,7 @@ func NewAcceptedMessagesFilter(msgs ...RawContractMessage) *AcceptedMessagesFilt } // Accept only payload messages which are equal to the granted one. -func (f *AcceptedMessagesFilter) Accept(ctx sdk.Context, msg RawContractMessage) (bool, error) { +func (f *AcceptedMessagesFilter) Accept(_ sdk.Context, msg RawContractMessage) (bool, error) { for _, v := range f.Messages { if v.Equal(msg) { return true, nil @@ -426,7 +425,7 @@ func (u UndefinedLimit) ValidateBasic() error { } // Accept always returns error -func (u UndefinedLimit) Accept(ctx sdk.Context, msg AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { +func (u UndefinedLimit) Accept(_ sdk.Context, _ AuthzableWasmMsg) (*ContractAuthzLimitAcceptResult, error) { return nil, sdkerrors.ErrNotFound.Wrapf("undefined filter") } @@ -472,7 +471,7 @@ func (m MaxFundsLimit) Accept(_ sdk.Context, msg AuthzableWasmMsg) (*ContractAut if !msg.GetFunds().IsAllLTE(m.Amounts) { return &ContractAuthzLimitAcceptResult{Accepted: false}, nil } - newAmounts := m.Amounts.Sub(msg.GetFunds()) + newAmounts := m.Amounts.Sub(msg.GetFunds()...) if newAmounts.IsZero() { return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil } @@ -508,7 +507,7 @@ func (l CombinedLimit) Accept(_ sdk.Context, msg AuthzableWasmMsg) (*ContractAut case 1: return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil default: - remainingAmounts := l.Amounts.Sub(transferFunds) + remainingAmounts := l.Amounts.Sub(transferFunds...) if remainingAmounts.IsZero() { return &ContractAuthzLimitAcceptResult{Accepted: true, DeleteLimit: true}, nil } @@ -528,7 +527,7 @@ func (l CombinedLimit) ValidateBasic() error { return ErrEmpty.Wrap("amounts") } if err := l.Amounts.Validate(); err != nil { - return sdkerrors.Wrap(err, "amounts") + return errorsmod.Wrap(err, "amounts") } return nil } diff --git a/x/wasm/types/authz.pb.go b/x/wasm/types/authz.pb.go index a037907..8bd25bf 100644 --- a/x/wasm/types/authz.pb.go +++ b/x/wasm/types/authz.pb.go @@ -5,21 +5,25 @@ 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/gogo/protobuf/proto" - io "io" - math "math" - math_bits "math/bits" + proto "github.com/cosmos/gogoproto/proto" ) // Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf +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. @@ -28,7 +32,7 @@ var _ = math.Inf const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // ContractExecutionAuthorization defines authorization for wasm execute. -// Since: terpd 0.2.0 +// Since: wasmd 0.30 type ContractExecutionAuthorization struct { // Grants for contract executions Grants []ContractGrant `protobuf:"bytes,1,rep,name=grants,proto3" json:"grants"` @@ -40,9 +44,11 @@ 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) @@ -55,12 +61,15 @@ func (m *ContractExecutionAuthorization) XXX_Marshal(b []byte, deterministic boo 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) } @@ -68,7 +77,7 @@ func (m *ContractExecutionAuthorization) XXX_DiscardUnknown() { var xxx_messageInfo_ContractExecutionAuthorization proto.InternalMessageInfo // ContractMigrationAuthorization defines authorization for wasm contract -// migration. Since: terpd 0.2.0 +// migration. Since: wasmd 0.30 type ContractMigrationAuthorization struct { // Grants for contract migrations Grants []ContractGrant `protobuf:"bytes,1,rep,name=grants,proto3" json:"grants"` @@ -80,9 +89,11 @@ 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) @@ -95,12 +106,15 @@ func (m *ContractMigrationAuthorization) XXX_Marshal(b []byte, deterministic boo 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) } @@ -108,7 +122,7 @@ func (m *ContractMigrationAuthorization) XXX_DiscardUnknown() { var xxx_messageInfo_ContractMigrationAuthorization proto.InternalMessageInfo // ContractGrant a granted permission for a single contract -// Since: terpd 0.2.0 +// 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"` @@ -127,9 +141,11 @@ 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) @@ -142,12 +158,15 @@ func (m *ContractGrant) XXX_Marshal(b []byte, deterministic bool) ([]byte, error 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) } @@ -155,7 +174,7 @@ func (m *ContractGrant) XXX_DiscardUnknown() { var xxx_messageInfo_ContractGrant proto.InternalMessageInfo // MaxCallsLimit limited number of calls to the contract. No funds transferable. -// Since: terpd 0.2.0 +// 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"` @@ -167,9 +186,11 @@ 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) @@ -182,12 +203,15 @@ func (m *MaxCallsLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error 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) } @@ -195,7 +219,7 @@ func (m *MaxCallsLimit) XXX_DiscardUnknown() { var xxx_messageInfo_MaxCallsLimit proto.InternalMessageInfo // MaxFundsLimit defines the maximal amounts that can be sent to the contract. -// Since: terpd 0.2.0 +// 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"` @@ -207,9 +231,11 @@ 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) @@ -222,12 +248,15 @@ func (m *MaxFundsLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error 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) } @@ -236,7 +265,7 @@ 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: terpd 0.2.0 +// 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"` @@ -250,9 +279,11 @@ 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) @@ -265,12 +296,15 @@ func (m *CombinedLimit) XXX_Marshal(b []byte, deterministic bool) ([]byte, error 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) } @@ -279,9 +313,8 @@ var xxx_messageInfo_CombinedLimit proto.InternalMessageInfo // AllowAllMessagesFilter is a wildcard to allow any type of contract payload // message. -// Since: terpd 0.2.0 -type AllowAllMessagesFilter struct { -} +// Since: wasmd 0.30 +type AllowAllMessagesFilter struct{} func (m *AllowAllMessagesFilter) Reset() { *m = AllowAllMessagesFilter{} } func (m *AllowAllMessagesFilter) String() string { return proto.CompactTextString(m) } @@ -289,9 +322,11 @@ 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) @@ -304,12 +339,15 @@ func (m *AllowAllMessagesFilter) XXX_Marshal(b []byte, deterministic bool) ([]by 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) } @@ -318,7 +356,7 @@ var xxx_messageInfo_AllowAllMessagesFilter proto.InternalMessageInfo // AcceptedMessageKeysFilter accept only the specific contract message keys in // the json object to be executed. -// Since: terpd 0.2.0 +// 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"` @@ -330,9 +368,11 @@ 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) @@ -345,12 +385,15 @@ func (m *AcceptedMessageKeysFilter) XXX_Marshal(b []byte, deterministic bool) ([ 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) } @@ -359,7 +402,7 @@ var xxx_messageInfo_AcceptedMessageKeysFilter proto.InternalMessageInfo // AcceptedMessagesFilter accept only the specific raw contract messages to be // executed. -// Since: terpd 0.2.0 +// 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"` @@ -371,9 +414,11 @@ 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) @@ -386,12 +431,15 @@ func (m *AcceptedMessagesFilter) XXX_Marshal(b []byte, deterministic bool) ([]by 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) } @@ -413,44 +461,49 @@ func init() { func init() { proto.RegisterFile("cosmwasm/wasm/v1/authz.proto", fileDescriptor_36ff3a20cf32b258) } var fileDescriptor_36ff3a20cf32b258 = []byte{ - // 584 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x54, 0x3d, 0x6f, 0xda, 0x40, - 0x18, 0xc6, 0x49, 0x9a, 0x26, 0x97, 0xa6, 0x1f, 0x6e, 0x94, 0x12, 0x14, 0x19, 0xc4, 0x52, 0x16, - 0xdb, 0x85, 0x6e, 0x48, 0x1d, 0x00, 0x95, 0xaa, 0x4a, 0x59, 0x3c, 0x45, 0x5d, 0xa2, 0xb3, 0x39, - 0xcc, 0x09, 0xfb, 0x0e, 0xf9, 0xce, 0x7c, 0xfd, 0x89, 0xf6, 0x77, 0x74, 0x66, 0xe8, 0x4f, 0x40, - 0x4c, 0x19, 0x3b, 0xa5, 0x2d, 0xfc, 0x8b, 0x4e, 0x95, 0xef, 0xce, 0x04, 0x90, 0xc8, 0xd8, 0x2e, - 0xc7, 0xbd, 0x1f, 0xcf, 0xf3, 0x3e, 0xf7, 0xbe, 0x2f, 0x06, 0x97, 0x1e, 0x65, 0xe1, 0x10, 0xb2, - 0xd0, 0x16, 0xc7, 0xa0, 0x6c, 0xc3, 0x98, 0x77, 0x27, 0x56, 0x3f, 0xa2, 0x9c, 0xea, 0xcf, 0xd3, - 0xa8, 0x25, 0x8e, 0x41, 0x39, 0x77, 0xe6, 0x53, 0x9f, 0x8a, 0xa0, 0x9d, 0xdc, 0x64, 0x5e, 0xee, - 0x22, 0xc9, 0xa3, 0xec, 0x46, 0x06, 0xa4, 0xa1, 0x42, 0x86, 0xb4, 0x6c, 0x17, 0x32, 0x64, 0x0f, - 0xca, 0x2e, 0xe2, 0xb0, 0x6c, 0x7b, 0x14, 0x93, 0x14, 0xea, 0x53, 0xea, 0x07, 0xc8, 0x16, 0x96, - 0x1b, 0x77, 0x6c, 0x48, 0xc6, 0x32, 0x54, 0x8c, 0x80, 0xd1, 0xa0, 0x84, 0x47, 0xd0, 0xe3, 0xef, - 0x47, 0xc8, 0x8b, 0x39, 0xa6, 0xa4, 0x16, 0xf3, 0x2e, 0x8d, 0xf0, 0x04, 0x26, 0x86, 0xfe, 0x0e, - 0x1c, 0xfa, 0x11, 0x24, 0x9c, 0x65, 0xb5, 0xc2, 0x7e, 0xe9, 0xa4, 0x92, 0xb7, 0xb6, 0x05, 0x5b, - 0x29, 0xc3, 0x87, 0x24, 0xaf, 0x7e, 0x30, 0xbb, 0xcb, 0x67, 0x1c, 0x05, 0xaa, 0xbe, 0x98, 0x4f, - 0xcd, 0xd3, 0x0d, 0xc6, 0xf5, 0x9a, 0x2d, 0xec, 0x47, 0xf0, 0x5f, 0xd4, 0xfc, 0xae, 0x81, 0xd3, - 0x0d, 0x88, 0x9e, 0x03, 0x47, 0x9e, 0x72, 0x64, 0xb5, 0x82, 0x56, 0x3a, 0x76, 0x56, 0xb6, 0xde, - 0x00, 0x8f, 0x02, 0x1c, 0x62, 0x9e, 0xdd, 0x2b, 0x68, 0xa5, 0x93, 0xca, 0x99, 0x25, 0x1b, 0x68, - 0xa5, 0x0d, 0xb4, 0x6a, 0x64, 0x5c, 0x7f, 0x35, 0x9f, 0x9a, 0x2f, 0x53, 0xce, 0xa4, 0xda, 0xe4, - 0x53, 0x82, 0xb9, 0x76, 0x24, 0x56, 0x6f, 0x82, 0xc3, 0x0e, 0x0e, 0x38, 0x8a, 0xb2, 0xfb, 0x0f, - 0xb0, 0x64, 0xe7, 0x53, 0xf3, 0x6c, 0x83, 0xa5, 0x29, 0x40, 0xd7, 0x8e, 0x42, 0x17, 0x9b, 0xe0, - 0xb4, 0x05, 0x47, 0x0d, 0x18, 0x04, 0x4c, 0x14, 0xd0, 0x2f, 0xc1, 0x71, 0x84, 0x42, 0x88, 0x09, - 0x26, 0xbe, 0x90, 0x7e, 0xe0, 0xdc, 0x3b, 0xaa, 0xbb, 0x64, 0x15, 0xbf, 0x68, 0x82, 0xa8, 0x19, - 0x93, 0xb6, 0x22, 0x42, 0xe0, 0x31, 0x0c, 0x69, 0x7c, 0xdf, 0xe7, 0x0b, 0x4b, 0xed, 0x55, 0xb2, - 0x49, 0x96, 0xda, 0x24, 0xab, 0x41, 0x31, 0xa9, 0xbf, 0x49, 0x3a, 0xfc, 0xed, 0x67, 0xbe, 0xe4, - 0x63, 0xde, 0x8d, 0x5d, 0xcb, 0xa3, 0xa1, 0x5a, 0x42, 0xf5, 0x63, 0xb2, 0x76, 0xcf, 0xe6, 0xe3, - 0x3e, 0x62, 0x02, 0xc0, 0x9c, 0x94, 0x7b, 0xb7, 0x22, 0x39, 0x94, 0xd0, 0xc5, 0x04, 0xb5, 0xa5, - 0xa2, 0xd7, 0xe0, 0x99, 0x97, 0x3c, 0xf4, 0x66, 0xfb, 0x81, 0x4f, 0x85, 0xdb, 0x49, 0xbd, 0xeb, - 0xd2, 0xf7, 0xfe, 0x87, 0xf4, 0x0a, 0x38, 0xaf, 0x05, 0x01, 0x1d, 0xd6, 0x82, 0xa0, 0x85, 0x18, - 0x83, 0x3e, 0x62, 0x72, 0x6e, 0xd5, 0x9d, 0x03, 0x2d, 0x7e, 0x04, 0x17, 0x35, 0xcf, 0x43, 0x7d, - 0x8e, 0xda, 0x0a, 0x73, 0x85, 0xc6, 0x0a, 0xa6, 0xeb, 0xe0, 0xa0, 0x87, 0xc6, 0x72, 0x10, 0xc7, - 0x8e, 0xb8, 0x3f, 0x40, 0xd5, 0x01, 0xe7, 0x5b, 0x54, 0x29, 0x4f, 0x05, 0x1c, 0x85, 0xca, 0x23, - 0xb8, 0x9e, 0xd4, 0xcf, 0xff, 0xdc, 0xe5, 0x75, 0x07, 0x0e, 0x57, 0xff, 0x39, 0x19, 0x76, 0x56, - 0x79, 0xbb, 0xeb, 0xd4, 0xaf, 0x66, 0xbf, 0x8d, 0xcc, 0x6c, 0x61, 0x68, 0xb7, 0x0b, 0x43, 0xfb, - 0xb5, 0x30, 0xb4, 0xaf, 0x4b, 0x23, 0x73, 0xbb, 0x34, 0x32, 0x3f, 0x96, 0x46, 0xe6, 0xb3, 0xb9, - 0xd6, 0x50, 0x8e, 0xa2, 0x3e, 0x41, 0x7c, 0x48, 0xa3, 0x9e, 0xb8, 0x9b, 0x1e, 0x8d, 0x90, 0x3d, - 0x92, 0x9f, 0x3c, 0xd1, 0x5b, 0xf7, 0x50, 0x2c, 0xfe, 0xdb, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, - 0x9d, 0x14, 0x16, 0x53, 0x10, 0x05, 0x00, 0x00, + // 665 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x55, 0x4d, 0x4f, 0xd4, 0x40, + 0x18, 0xde, 0x01, 0x44, 0x76, 0x10, 0x3f, 0x1a, 0x42, 0x16, 0x24, 0x5d, 0x52, 0xbf, 0x56, 0x92, + 0x6d, 0xb3, 0x18, 0x2f, 0x7b, 0x31, 0xbb, 0xab, 0x18, 0x23, 0x78, 0x68, 0x4c, 0x20, 0x5e, 0xc8, + 0xb4, 0x3b, 0x94, 0x91, 0x76, 0x86, 0x74, 0xa6, 0xc0, 0x92, 0xf8, 0x07, 0x3c, 0x79, 0xf3, 0x2f, + 0x18, 0x4f, 0x1c, 0xf6, 0xe8, 0x0f, 0x20, 0x9c, 0x38, 0x1a, 0x0f, 0xa8, 0x10, 0xc3, 0x7f, 0xf0, + 0x64, 0x3a, 0x33, 0x5d, 0x58, 0x02, 0x1b, 0xe4, 0xc4, 0x65, 0xda, 0xf7, 0x7d, 0x67, 0x9e, 0xe7, + 0x79, 0x3f, 0xda, 0x81, 0x93, 0x3e, 0xe3, 0xd1, 0x06, 0xe2, 0x91, 0x23, 0x97, 0xf5, 0x8a, 0x83, + 0x12, 0xb1, 0xb2, 0x65, 0xaf, 0xc5, 0x4c, 0x30, 0xe3, 0x76, 0x16, 0xb5, 0xe5, 0xb2, 0x5e, 0x99, + 0x18, 0x0d, 0x58, 0xc0, 0x64, 0xd0, 0x49, 0xdf, 0xd4, 0xbe, 0x89, 0xf1, 0x74, 0x1f, 0xe3, 0x4b, + 0x2a, 0xa0, 0x0c, 0x1d, 0x32, 0x95, 0xe5, 0x78, 0x88, 0x63, 0x67, 0xbd, 0xe2, 0x61, 0x81, 0x2a, + 0x8e, 0xcf, 0x08, 0xcd, 0x8e, 0x06, 0x8c, 0x05, 0x21, 0x76, 0xa4, 0xe5, 0x25, 0xcb, 0x0e, 0xa2, + 0x2d, 0x1d, 0xba, 0x83, 0x22, 0x42, 0x99, 0x23, 0x57, 0xe5, 0xb2, 0xda, 0x00, 0x9a, 0x0d, 0x46, + 0x45, 0x8c, 0x7c, 0xf1, 0x62, 0x13, 0xfb, 0x89, 0x20, 0x8c, 0xd6, 0x12, 0xb1, 0xc2, 0x62, 0xb2, + 0x85, 0x52, 0xc3, 0xa8, 0xc3, 0xc1, 0x20, 0x46, 0x54, 0xf0, 0x02, 0x98, 0xea, 0x2f, 0x0d, 0xcf, + 0x14, 0xed, 0xd3, 0x49, 0xd8, 0x19, 0xc2, 0xcb, 0x74, 0x5f, 0x3d, 0xbf, 0xb3, 0x5f, 0xcc, 0x7d, + 0x39, 0xda, 0x9e, 0x06, 0xae, 0x3e, 0x59, 0x7d, 0xb3, 0xdb, 0x2e, 0x5b, 0x3a, 0x0d, 0x55, 0x0f, + 0xad, 0xdc, 0xee, 0xe2, 0xfa, 0x78, 0xb4, 0x3d, 0x7d, 0x4f, 0xd6, 0xad, 0xb7, 0xa6, 0x2e, 0xd9, + 0xf3, 0x24, 0x88, 0xd1, 0x15, 0x93, 0x7d, 0xb6, 0x26, 0xeb, 0x07, 0x80, 0x23, 0x5d, 0xa4, 0xc6, + 0x04, 0x1c, 0xf2, 0xb5, 0xa3, 0x00, 0xa6, 0x40, 0x29, 0xef, 0x76, 0x6c, 0xe3, 0x2d, 0xbc, 0x16, + 0x92, 0x88, 0x88, 0x42, 0xdf, 0x14, 0x28, 0x0d, 0xcf, 0x8c, 0xda, 0xaa, 0xb3, 0x76, 0xd6, 0x59, + 0xbb, 0x46, 0x5b, 0xf5, 0xd2, 0x6e, 0xbb, 0x7c, 0xff, 0xdc, 0xcc, 0x52, 0xfa, 0xad, 0xb9, 0x14, + 0x64, 0xd1, 0x55, 0x60, 0xc6, 0x02, 0x1c, 0x5c, 0x26, 0xa1, 0xc0, 0x71, 0xa1, 0xbf, 0x07, 0xec, + 0xe3, 0xdd, 0x76, 0xf9, 0x41, 0x6f, 0xd8, 0x59, 0x89, 0xb2, 0xe8, 0x6a, 0x38, 0x8b, 0xc2, 0x91, + 0x79, 0xb4, 0xd9, 0x40, 0x61, 0xc8, 0x25, 0xa3, 0x31, 0x09, 0xf3, 0x31, 0x8e, 0x10, 0xa1, 0x84, + 0x06, 0x32, 0xb9, 0x01, 0xf7, 0xd8, 0x51, 0x7d, 0x76, 0x51, 0xe1, 0x69, 0x75, 0x0d, 0x59, 0xdd, + 0x2e, 0x78, 0xeb, 0x1b, 0x90, 0x84, 0xb3, 0x09, 0x6d, 0x6a, 0xc2, 0xf7, 0xf0, 0x3a, 0x8a, 0x58, + 0x72, 0xdc, 0xf3, 0x71, 0x5b, 0x37, 0x2f, 0xfd, 0x58, 0x3a, 0xbd, 0x6b, 0x30, 0x42, 0xeb, 0x4f, + 0xd3, 0x6e, 0x7f, 0xfd, 0x59, 0x2c, 0x05, 0x44, 0xac, 0x24, 0x9e, 0xed, 0xb3, 0x48, 0x7f, 0x67, + 0xfa, 0x51, 0xe6, 0xcd, 0x55, 0x47, 0xb4, 0xd6, 0x30, 0x97, 0x07, 0xb8, 0x9a, 0x8c, 0x8c, 0xe0, + 0x92, 0xf2, 0x8f, 0xc5, 0x5a, 0x7f, 0xe4, 0x2c, 0x44, 0x1e, 0xa1, 0xb8, 0xa9, 0xe4, 0x3f, 0x82, + 0xb7, 0xfc, 0x34, 0xbd, 0xa5, 0xd3, 0x55, 0xbb, 0x29, 0xdd, 0x6e, 0xe6, 0x3d, 0x99, 0x67, 0xdf, + 0x15, 0xcc, 0xb3, 0x2b, 0x2b, 0xcb, 0x87, 0x63, 0xb5, 0x30, 0x64, 0x1b, 0xb5, 0x30, 0x9c, 0xc7, + 0x9c, 0xa3, 0x00, 0x73, 0x35, 0x39, 0xd5, 0x57, 0x17, 0x9e, 0xb1, 0x14, 0xfb, 0xae, 0xc4, 0x3e, + 0x1b, 0xca, 0xfa, 0x00, 0xc7, 0x6b, 0xbe, 0x8f, 0xd7, 0x04, 0x6e, 0xea, 0xc8, 0x6b, 0xdc, 0xd2, + 0x41, 0xc3, 0x80, 0x03, 0xab, 0xb8, 0xa5, 0x66, 0x22, 0xef, 0xca, 0xf7, 0xea, 0xdc, 0x7f, 0x71, + 0x9b, 0x8a, 0xfb, 0x3c, 0x06, 0xeb, 0x33, 0x80, 0x63, 0xa7, 0xa2, 0x19, 0xf9, 0x0c, 0x1c, 0x8a, + 0xb4, 0x47, 0x0a, 0xb8, 0x51, 0x1f, 0xfb, 0xbb, 0x5f, 0x34, 0x5c, 0xb4, 0xd1, 0xf9, 0x57, 0xa8, + 0xb0, 0xdb, 0xd9, 0x77, 0xb9, 0xc2, 0x9c, 0x49, 0x5f, 0x7f, 0xbe, 0xf3, 0xdb, 0xcc, 0xed, 0x1c, + 0x98, 0x60, 0xef, 0xc0, 0x04, 0xbf, 0x0e, 0x4c, 0xf0, 0xe9, 0xd0, 0xcc, 0xed, 0x1d, 0x9a, 0xb9, + 0xef, 0x87, 0x66, 0xee, 0xdd, 0xc3, 0x13, 0x43, 0xd1, 0x60, 0x3c, 0x5a, 0xc8, 0xee, 0xad, 0xa6, + 0xb3, 0xa9, 0xee, 0x2f, 0x39, 0x18, 0xde, 0xa0, 0xfc, 0x37, 0x3c, 0xf9, 0x17, 0x00, 0x00, 0xff, + 0xff, 0x84, 0xc4, 0x51, 0x3d, 0xdd, 0x06, 0x00, 0x00, } func (m *ContractExecutionAuthorization) Marshal() (dAtA []byte, err error) { @@ -786,6 +839,7 @@ func encodeVarintAuthz(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } + func (m *ContractExecutionAuthorization) Size() (n int) { if m == nil { return 0 @@ -924,9 +978,11 @@ func (m *AcceptedMessagesFilter) Size() (n int) { 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 @@ -1011,6 +1067,7 @@ func (m *ContractExecutionAuthorization) Unmarshal(dAtA []byte) error { } return nil } + func (m *ContractMigrationAuthorization) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1095,6 +1152,7 @@ func (m *ContractMigrationAuthorization) Unmarshal(dAtA []byte) error { } return nil } + func (m *ContractGrant) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1249,6 +1307,7 @@ func (m *ContractGrant) Unmarshal(dAtA []byte) error { } return nil } + func (m *MaxCallsLimit) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1318,6 +1377,7 @@ func (m *MaxCallsLimit) Unmarshal(dAtA []byte) error { } return nil } + func (m *MaxFundsLimit) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1402,6 +1462,7 @@ func (m *MaxFundsLimit) Unmarshal(dAtA []byte) error { } return nil } + func (m *CombinedLimit) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1505,6 +1566,7 @@ func (m *CombinedLimit) Unmarshal(dAtA []byte) error { } return nil } + func (m *AllowAllMessagesFilter) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1555,6 +1617,7 @@ func (m *AllowAllMessagesFilter) Unmarshal(dAtA []byte) error { } return nil } + func (m *AcceptedMessageKeysFilter) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1637,6 +1700,7 @@ func (m *AcceptedMessageKeysFilter) Unmarshal(dAtA []byte) error { } return nil } + func (m *AcceptedMessagesFilter) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1719,6 +1783,7 @@ func (m *AcceptedMessagesFilter) Unmarshal(dAtA []byte) error { } return nil } + func skipAuthz(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/wasm/types/authz_test.go b/x/wasm/types/authz_test.go index 0674769..7e8068c 100644 --- a/x/wasm/types/authz_test.go +++ b/x/wasm/types/authz_test.go @@ -4,6 +4,7 @@ import ( "math" "testing" + errorsmod "cosmossdk.io/errors" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" authztypes "github.com/cosmos/cosmos-sdk/x/authz" @@ -395,17 +396,20 @@ func TestValidateContractGrant(t *testing.T) { }{ "all good": { setup: func(t *testing.T) ContractGrant { + t.Helper() return mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) }, }, "invalid address": { setup: func(t *testing.T) ContractGrant { + t.Helper() return mustGrant([]byte{}, NewMaxCallsLimit(1), NewAllowAllMessagesFilter()) }, expErr: true, }, "invalid limit": { setup: func(t *testing.T) ContractGrant { + t.Helper() return mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(0), NewAllowAllMessagesFilter()) }, expErr: true, @@ -413,12 +417,14 @@ func TestValidateContractGrant(t *testing.T) { "invalid filter ": { setup: func(t *testing.T) ContractGrant { + t.Helper() return mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter()) }, expErr: true, }, "empty limit": { setup: func(t *testing.T) ContractGrant { + t.Helper() r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(0), NewAllowAllMessagesFilter()) r.Limit = nil return r @@ -428,6 +434,7 @@ func TestValidateContractGrant(t *testing.T) { "empty filter ": { setup: func(t *testing.T) ContractGrant { + t.Helper() r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter()) r.Filter = nil return r @@ -436,6 +443,7 @@ func TestValidateContractGrant(t *testing.T) { }, "wrong limit type": { setup: func(t *testing.T) ContractGrant { + t.Helper() r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(0), NewAllowAllMessagesFilter()) r.Limit = r.Filter return r @@ -445,6 +453,7 @@ func TestValidateContractGrant(t *testing.T) { "wrong filter type": { setup: func(t *testing.T) ContractGrant { + t.Helper() r := mustGrant(randBytes(ContractAddrLen), NewMaxCallsLimit(1), NewAcceptedMessageKeysFilter()) r.Filter = r.Limit return r @@ -477,44 +486,52 @@ func TestValidateContractAuthorization(t *testing.T) { }{ "contract execution": { setup: func(t *testing.T) validatable { + t.Helper() return NewContractMigrationAuthorization(*validGrant) }, }, "contract execution - duplicate grants": { setup: func(t *testing.T) validatable { + t.Helper() return NewContractMigrationAuthorization(*validGrant, *validGrant) }, }, "contract execution - invalid grant": { setup: func(t *testing.T) validatable { + t.Helper() return NewContractMigrationAuthorization(*validGrant, *invalidGrant) }, expErr: true, }, "contract execution - empty grants": { setup: func(t *testing.T) validatable { + t.Helper() return NewContractMigrationAuthorization() }, expErr: true, }, "contract migration": { setup: func(t *testing.T) validatable { + t.Helper() return NewContractMigrationAuthorization(*validGrant) }, }, "contract migration - duplicate grants": { setup: func(t *testing.T) validatable { + t.Helper() return NewContractMigrationAuthorization(*validGrant, *validGrant) }, }, "contract migration - invalid grant": { setup: func(t *testing.T) validatable { + t.Helper() return NewContractMigrationAuthorization(*validGrant, *invalidGrant) }, expErr: true, }, "contract migration - empty grant": { setup: func(t *testing.T) validatable { + t.Helper() return NewContractMigrationAuthorization() }, expErr: true, @@ -539,7 +556,7 @@ func TestAcceptGrantedMessage(t *testing.T) { auth authztypes.Authorization msg sdk.Msg expResult authztypes.AcceptResponse - expErr *sdkerrors.Error + expErr *errorsmod.Error }{ "accepted and updated - contract execution": { auth: NewContractExecutionAuthorization(mustGrant(myContractAddr, NewMaxCallsLimit(2), NewAllowAllMessagesFilter())), diff --git a/x/wasm/types/codec.go b/x/wasm/types/codec.go index d1c2b9e..10ff3af 100644 --- a/x/wasm/types/codec.go +++ b/x/wasm/types/codec.go @@ -7,11 +7,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" "github.com/cosmos/cosmos-sdk/x/authz" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + 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) { //nolint:staticcheck +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(&MsgStoreCode{}, "wasm/MsgStoreCode", nil) cdc.RegisterConcrete(&MsgInstantiateContract{}, "wasm/MsgInstantiateContract", nil) cdc.RegisterConcrete(&MsgInstantiateContract2{}, "wasm/MsgInstantiateContract2", nil) @@ -19,6 +22,12 @@ func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { //nolint:staticcheck 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) @@ -31,6 +40,7 @@ func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { //nolint:staticcheck 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) @@ -46,7 +56,6 @@ func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { //nolint:staticcheck cdc.RegisterConcrete(&ContractExecutionAuthorization{}, "wasm/ContractExecutionAuthorization", nil) cdc.RegisterConcrete(&ContractMigrationAuthorization{}, "wasm/ContractMigrationAuthorization", nil) - cdc.RegisterConcrete(&StoreAndInstantiateContractProposal{}, "wasm/StoreAndInstantiateContractProposal", nil) } func RegisterInterfaces(registry types.InterfaceRegistry) { @@ -61,9 +70,15 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { &MsgClearAdmin{}, &MsgIBCCloseChannel{}, &MsgIBCSend{}, + &MsgUpdateInstantiateConfig{}, + &MsgUpdateParams{}, + &MsgSudoContract{}, + &MsgPinCodes{}, + &MsgUnpinCodes{}, + &MsgStoreAndInstantiateContract{}, ) registry.RegisterImplementations( - (*govtypes.Content)(nil), + (*v1beta1.Content)(nil), &StoreCodeProposal{}, &InstantiateContractProposal{}, &InstantiateContract2Proposal{}, @@ -78,9 +93,9 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { &StoreAndInstantiateContractProposal{}, ) - registry.RegisterInterface("ContractInfoExtension", (*ContractInfoExtension)(nil)) + registry.RegisterInterface("cosmwasm.wasm.v1.ContractInfoExtension", (*ContractInfoExtension)(nil)) - registry.RegisterInterface("ContractAuthzFilterX", (*ContractAuthzFilterX)(nil)) + registry.RegisterInterface("cosmwasm.wasm.v1.ContractAuthzFilterX", (*ContractAuthzFilterX)(nil)) registry.RegisterImplementations( (*ContractAuthzFilterX)(nil), &AllowAllMessagesFilter{}, @@ -88,7 +103,7 @@ func RegisterInterfaces(registry types.InterfaceRegistry) { &AcceptedMessagesFilter{}, ) - registry.RegisterInterface("ContractAuthzLimitX", (*ContractAuthzLimitX)(nil)) + registry.RegisterInterface("cosmwasm.wasm.v1.ContractAuthzLimitX", (*ContractAuthzLimitX)(nil)) registry.RegisterImplementations( (*ContractAuthzLimitX)(nil), &MaxCallsLimit{}, @@ -117,4 +132,10 @@ 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 index a7e0464..378c25d 100644 --- a/x/wasm/types/errors.go +++ b/x/wasm/types/errors.go @@ -1,7 +1,8 @@ package types import ( - sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + errorsmod "cosmossdk.io/errors" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" ) // Codes for wasm contract errors @@ -11,86 +12,139 @@ var ( // 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 = sdkErrors.Register(DefaultCodespace, 2, "create wasm contract failed") + ErrCreateFailed = errorsmod.Register(DefaultCodespace, 2, "create wasm contract failed") // ErrAccountExists error for a contract account that already exists - ErrAccountExists = sdkErrors.Register(DefaultCodespace, 3, "contract account already exists") + ErrAccountExists = errorsmod.Register(DefaultCodespace, 3, "contract account already exists") // ErrInstantiateFailed error for rust instantiate contract failure - ErrInstantiateFailed = sdkErrors.Register(DefaultCodespace, 4, "instantiate wasm contract failed") + ErrInstantiateFailed = errorsmod.Register(DefaultCodespace, 4, "instantiate wasm contract failed") // ErrExecuteFailed error for rust execution contract failure - ErrExecuteFailed = sdkErrors.Register(DefaultCodespace, 5, "execute wasm contract failed") + ErrExecuteFailed = errorsmod.Register(DefaultCodespace, 5, "execute wasm contract failed") // ErrGasLimit error for out of gas - ErrGasLimit = sdkErrors.Register(DefaultCodespace, 6, "insufficient gas") + ErrGasLimit = errorsmod.Register(DefaultCodespace, 6, "insufficient gas") // ErrInvalidGenesis error for invalid genesis file syntax - ErrInvalidGenesis = sdkErrors.Register(DefaultCodespace, 7, "invalid genesis") + ErrInvalidGenesis = errorsmod.Register(DefaultCodespace, 7, "invalid genesis") // ErrNotFound error for an entry not found in the store - ErrNotFound = sdkErrors.Register(DefaultCodespace, 8, "not found") + ErrNotFound = errorsmod.Register(DefaultCodespace, 8, "not found") // ErrQueryFailed error for rust smart query contract failure - ErrQueryFailed = sdkErrors.Register(DefaultCodespace, 9, "query wasm contract failed") + ErrQueryFailed = errorsmod.Register(DefaultCodespace, 9, "query wasm contract failed") // ErrInvalidMsg error when we cannot process the error returned from the contract - ErrInvalidMsg = sdkErrors.Register(DefaultCodespace, 10, "invalid CosmosMsg from the contract") + ErrInvalidMsg = errorsmod.Register(DefaultCodespace, 10, "invalid CosmosMsg from the contract") // ErrMigrationFailed error for rust execution contract failure - ErrMigrationFailed = sdkErrors.Register(DefaultCodespace, 11, "migrate wasm contract failed") + ErrMigrationFailed = errorsmod.Register(DefaultCodespace, 11, "migrate wasm contract failed") // ErrEmpty error for empty content - ErrEmpty = sdkErrors.Register(DefaultCodespace, 12, "empty") + ErrEmpty = errorsmod.Register(DefaultCodespace, 12, "empty") // ErrLimit error for content that exceeds a limit - ErrLimit = sdkErrors.Register(DefaultCodespace, 13, "exceeds limit") + ErrLimit = errorsmod.Register(DefaultCodespace, 13, "exceeds limit") // ErrInvalid error for content that is invalid in this context - ErrInvalid = sdkErrors.Register(DefaultCodespace, 14, "invalid") + ErrInvalid = errorsmod.Register(DefaultCodespace, 14, "invalid") // ErrDuplicate error for content that exists - ErrDuplicate = sdkErrors.Register(DefaultCodespace, 15, "duplicate") + ErrDuplicate = errorsmod.Register(DefaultCodespace, 15, "duplicate") // ErrMaxIBCChannels error for maximum number of ibc channels reached - ErrMaxIBCChannels = sdkErrors.Register(DefaultCodespace, 16, "max transfer channels") + ErrMaxIBCChannels = errorsmod.Register(DefaultCodespace, 16, "max transfer channels") // ErrUnsupportedForContract error when a capability is used that is not supported for/ by this contract - ErrUnsupportedForContract = sdkErrors.Register(DefaultCodespace, 17, "unsupported for this contract") + ErrUnsupportedForContract = errorsmod.Register(DefaultCodespace, 17, "unsupported for this contract") // ErrPinContractFailed error for pinning contract failures - ErrPinContractFailed = sdkErrors.Register(DefaultCodespace, 18, "pinning contract failed") + ErrPinContractFailed = errorsmod.Register(DefaultCodespace, 18, "pinning contract failed") // ErrUnpinContractFailed error for unpinning contract failures - ErrUnpinContractFailed = sdkErrors.Register(DefaultCodespace, 19, "unpinning contract failed") + 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 = sdkErrors.Register(DefaultCodespace, 20, "unknown message from the contract") + ErrUnknownMsg = errorsmod.Register(DefaultCodespace, 20, "unknown message from the contract") // ErrInvalidEvent error if an attribute/event from the contract is invalid - ErrInvalidEvent = sdkErrors.Register(DefaultCodespace, 21, "invalid event") + ErrInvalidEvent = errorsmod.Register(DefaultCodespace, 21, "invalid event") - // error if an address does not belong to a contract (just for registration) - _ = sdkErrors.Register(DefaultCodespace, 22, "no such contract") + // 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 = sdkErrors.Register(DefaultCodespace, 27, "max query stack size 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} }, + ) ) -type ErrNoSuchContract struct { - Addr string +// 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 } -func (m *ErrNoSuchContract) Error() string { - return "no such contract: " + m.Addr +// NewWasmVMFlavouredError constructor +func NewWasmVMFlavouredError(sdkErr *errorsmod.Error, wasmVMErr error) WasmVMFlavouredError { + return WasmVMFlavouredError{sdkErr: sdkErr, wasmVMErr: wasmVMErr} } -func (m *ErrNoSuchContract) ABCICode() uint32 { - return 22 +// 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)} + } } -func (m *ErrNoSuchContract) Codespace() string { - return DefaultCodespace +// 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 new file mode 100644 index 0000000..8102b32 --- /dev/null +++ b/x/wasm/types/errors_test.go @@ -0,0 +1,95 @@ +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) { + t.Helper() + assert.True(t, errorsmod.IsOf(myErr, myErr.sdkErr)) + assert.Equal(t, myErr.sdkErr, myErr.Unwrap()) + }, + }, + "unwrapped": { + exec: func(t *testing.T) { + t.Helper() + assert.Equal(t, myErr.sdkErr, myErr.Unwrap()) + }, + }, + "caused": { + exec: func(t *testing.T) { + t.Helper() + assert.Equal(t, myErr.sdkErr, myErr.Cause()) + }, + }, + "wrapped supports WasmVMErrorable": { + exec: func(t *testing.T) { + t.Helper() + 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) { + t.Helper() + 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) { + t.Helper() + 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) { + t.Helper() + 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) { + t.Helper() + 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) { + t.Helper() + 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 index 579024e..442c3ed 100644 --- a/x/wasm/types/events.go +++ b/x/wasm/types/events.go @@ -6,24 +6,29 @@ const ( // 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" + 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" + 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 index 57cc407..e9b5227 100644 --- a/x/wasm/types/expected_keepers.go +++ b/x/wasm/types/expected_keepers.go @@ -6,11 +6,12 @@ import ( 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" - "github.com/cosmos/cosmos-sdk/x/distribution/types" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - connectiontypes "github.com/cosmos/ibc-go/v4/modules/core/03-connection/types" - channeltypes "github.com/cosmos/ibc-go/v4/modules/core/04-channel/types" - ibcexported "github.com/cosmos/ibc-go/v4/modules/core/exported" + 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 @@ -47,7 +48,7 @@ type AccountKeeper interface { // DistributionKeeper defines a subset of methods implemented by the cosmos-sdk distribution keeper type DistributionKeeper interface { - DelegationRewards(c context.Context, req *types.QueryDelegationRewardsRequest) (*types.QueryDelegationRewardsResponse, error) + DelegationRewards(c context.Context, req *distrtypes.QueryDelegationRewardsRequest) (*distrtypes.QueryDelegationRewardsResponse, error) } // StakingKeeper defines a subset of methods implemented by the cosmos-sdk staking keeper @@ -71,8 +72,19 @@ type StakingKeeper interface { // ChannelKeeper defines the expected IBC channel keeper type ChannelKeeper interface { GetChannel(ctx sdk.Context, srcPort, srcChan string) (channel channeltypes.Channel, found bool) - GetNextSequenceSend(ctx sdk.Context, portID, channelID string) (uint64, bool) - SendPacket(ctx sdk.Context, channelCap *capabilitytypes.Capability, packet ibcexported.PacketI) error + + // 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) diff --git a/x/wasm/types/genesis.go b/x/wasm/types/genesis.go index f14dbc3..8a5a156 100644 --- a/x/wasm/types/genesis.go +++ b/x/wasm/types/genesis.go @@ -1,35 +1,35 @@ package types import ( + errorsmod "cosmossdk.io/errors" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) func (s Sequence) ValidateBasic() error { if len(s.IDKey) == 0 { - return sdkerrors.Wrap(ErrEmpty, "id key") + return errorsmod.Wrap(ErrEmpty, "id key") } return nil } func (s GenesisState) ValidateBasic() error { if err := s.Params.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "params") + return errorsmod.Wrap(err, "params") } for i := range s.Codes { if err := s.Codes[i].ValidateBasic(); err != nil { - return sdkerrors.Wrapf(err, "code: %d", i) + return errorsmod.Wrapf(err, "code: %d", i) } } for i := range s.Contracts { if err := s.Contracts[i].ValidateBasic(); err != nil { - return sdkerrors.Wrapf(err, "contract: %d", i) + return errorsmod.Wrapf(err, "contract: %d", i) } } for i := range s.Sequences { if err := s.Sequences[i].ValidateBasic(); err != nil { - return sdkerrors.Wrapf(err, "sequence: %d", i) + return errorsmod.Wrapf(err, "sequence: %d", i) } } @@ -38,31 +38,31 @@ func (s GenesisState) ValidateBasic() error { func (c Code) ValidateBasic() error { if c.CodeID == 0 { - return sdkerrors.Wrap(ErrEmpty, "code id") + return errorsmod.Wrap(ErrEmpty, "code id") } if err := c.CodeInfo.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "code info") + return errorsmod.Wrap(err, "code info") } if err := validateWasmCode(c.CodeBytes, MaxProposalWasmSize); err != nil { - return sdkerrors.Wrap(err, "code bytes") + return errorsmod.Wrap(err, "code bytes") } return nil } func (c Contract) ValidateBasic() error { if _, err := sdk.AccAddressFromBech32(c.ContractAddress); err != nil { - return sdkerrors.Wrap(err, "contract address") + return errorsmod.Wrap(err, "contract address") } if err := c.ContractInfo.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "contract info") + return errorsmod.Wrap(err, "contract info") } if c.ContractInfo.Created == nil { - return sdkerrors.Wrap(ErrInvalid, "created must not be empty") + return errorsmod.Wrap(ErrInvalid, "created must not be empty") } for i := range c.ContractState { if err := c.ContractState[i].ValidateBasic(); err != nil { - return sdkerrors.Wrapf(err, "contract state %d", i) + return errorsmod.Wrapf(err, "contract state %d", i) } } if len(c.ContractCodeHistory) == 0 { @@ -70,7 +70,7 @@ func (c Contract) ValidateBasic() error { } for i, v := range c.ContractCodeHistory { if err := v.ValidateBasic(); err != nil { - return sdkerrors.Wrapf(err, "code history element %d", i) + return errorsmod.Wrapf(err, "code history element %d", i) } } return nil diff --git a/x/wasm/types/genesis.pb.go b/x/wasm/types/genesis.pb.go index f12a1fe..52bd7cc 100644 --- a/x/wasm/types/genesis.pb.go +++ b/x/wasm/types/genesis.pb.go @@ -5,17 +5,21 @@ package types import ( fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/gogo/protobuf/proto" 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 -var _ = fmt.Errorf -var _ = math.Inf +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. @@ -37,9 +41,11 @@ 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) @@ -52,12 +58,15 @@ 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) } @@ -107,9 +116,11 @@ 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) @@ -122,12 +133,15 @@ func (m *Code) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 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) } @@ -176,9 +190,11 @@ 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) @@ -191,12 +207,15 @@ func (m *Contract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 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) } @@ -243,9 +262,11 @@ 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) @@ -258,12 +279,15 @@ func (m *Sequence) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 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) } @@ -294,42 +318,43 @@ func init() { func init() { proto.RegisterFile("cosmwasm/wasm/v1/genesis.proto", fileDescriptor_2ab3f539b23472a6) } var fileDescriptor_2ab3f539b23472a6 = []byte{ - // 551 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x93, 0xcf, 0x6e, 0xd3, 0x40, - 0x10, 0xc6, 0xe3, 0xd4, 0x31, 0xc9, 0x36, 0xd0, 0x6a, 0x29, 0xad, 0x15, 0xc0, 0x89, 0xc2, 0x25, - 0x20, 0x9a, 0xa8, 0x45, 0xe2, 0xc6, 0x01, 0x93, 0xaa, 0x44, 0x15, 0x12, 0x72, 0xc5, 0x85, 0x4b, - 0xe4, 0x78, 0xa7, 0xa9, 0xd5, 0xda, 0x6b, 0xbc, 0x9b, 0x14, 0xbf, 0x05, 0xaf, 0xc0, 0x9d, 0x37, - 0xe0, 0x05, 0x7a, 0xec, 0x91, 0x53, 0x84, 0x92, 0x1b, 0x4f, 0x81, 0xf6, 0x4f, 0x5c, 0xab, 0x69, - 0x2e, 0x96, 0x77, 0xe6, 0x9b, 0x9f, 0xc7, 0xdf, 0xcc, 0x22, 0x27, 0xa0, 0x2c, 0xba, 0xf2, 0x59, - 0xd4, 0x93, 0x8f, 0xe9, 0x41, 0x6f, 0x0c, 0x31, 0xb0, 0x90, 0x75, 0x93, 0x94, 0x72, 0x8a, 0xb7, - 0x97, 0xf9, 0xae, 0x7c, 0x4c, 0x0f, 0x1a, 0x3b, 0x63, 0x3a, 0xa6, 0x32, 0xd9, 0x13, 0x6f, 0x4a, - 0xd7, 0x78, 0xb6, 0xc2, 0xe1, 0x59, 0x02, 0x9a, 0xd2, 0xfe, 0x5d, 0x46, 0xf5, 0x63, 0xc5, 0x3d, - 0xe5, 0x3e, 0x07, 0xfc, 0x16, 0x59, 0x89, 0x9f, 0xfa, 0x11, 0xb3, 0x8d, 0x96, 0xd1, 0xd9, 0x3c, - 0xb4, 0xbb, 0x77, 0xbf, 0xd3, 0xfd, 0x2c, 0xf3, 0xae, 0x79, 0x3d, 0x6b, 0x96, 0x3c, 0xad, 0xc6, - 0x47, 0xa8, 0x12, 0x50, 0x02, 0xcc, 0x2e, 0xb7, 0x36, 0x3a, 0x9b, 0x87, 0xbb, 0xab, 0x65, 0x1f, - 0x28, 0x01, 0x77, 0x4f, 0x14, 0xfd, 0x9b, 0x35, 0xb7, 0xa4, 0xf8, 0x35, 0x8d, 0x42, 0x0e, 0x51, - 0xc2, 0x33, 0x4f, 0x55, 0xe3, 0x2f, 0xa8, 0x16, 0xd0, 0x98, 0xa7, 0x7e, 0xc0, 0x99, 0xbd, 0x21, - 0x51, 0x8d, 0xfb, 0x50, 0x4a, 0xe2, 0x3e, 0xd5, 0xb8, 0xc7, 0x79, 0x51, 0x01, 0x79, 0x4b, 0x12, - 0x58, 0x06, 0xdf, 0x26, 0x10, 0x07, 0xc0, 0x6c, 0x73, 0x1d, 0xf6, 0x54, 0x4b, 0x6e, 0xb1, 0x79, - 0x51, 0x11, 0x9b, 0x07, 0xdb, 0x3f, 0x0d, 0x64, 0x8a, 0xdf, 0xc2, 0x2f, 0xd0, 0x03, 0xd1, 0xff, - 0x30, 0x24, 0xd2, 0x36, 0xd3, 0x45, 0xf3, 0x59, 0xd3, 0x12, 0xa9, 0x41, 0xdf, 0xb3, 0x44, 0x6a, - 0x40, 0xf0, 0x3b, 0xf1, 0x6f, 0x42, 0x14, 0x9f, 0x51, 0xbb, 0x2c, 0xdd, 0x6d, 0xdc, 0x6f, 0xd3, - 0x20, 0x3e, 0xa3, 0xda, 0xdf, 0x6a, 0xa0, 0xcf, 0xf8, 0x39, 0x42, 0xb2, 0x7c, 0x94, 0x71, 0x10, - 0xde, 0x18, 0x9d, 0xba, 0x27, 0x81, 0xae, 0x08, 0xe0, 0x5d, 0x64, 0x25, 0x61, 0x1c, 0x03, 0xb1, - 0xcd, 0x96, 0xd1, 0xa9, 0x7a, 0xfa, 0xd4, 0xfe, 0x55, 0x46, 0xd5, 0xa5, 0x5f, 0xf8, 0x25, 0xda, - 0x5e, 0x9a, 0x32, 0xf4, 0x09, 0x49, 0x81, 0xa9, 0x39, 0xd7, 0xbc, 0xad, 0x65, 0xfc, 0xbd, 0x0a, - 0xe3, 0x01, 0x7a, 0x98, 0x4b, 0x0b, 0x1d, 0x3b, 0xeb, 0xa7, 0x51, 0xe8, 0xba, 0x1e, 0x14, 0x62, - 0xb8, 0x8f, 0x1e, 0xe5, 0x28, 0x26, 0xb6, 0x4c, 0x4f, 0x76, 0x6f, 0x95, 0xf5, 0x89, 0x12, 0xb8, - 0xd4, 0x90, 0xfc, 0xfb, 0x6a, 0x33, 0x09, 0x7a, 0x92, 0x53, 0xa4, 0x11, 0xe7, 0x21, 0xe3, 0x34, - 0xcd, 0xf4, 0x3c, 0x5f, 0xad, 0x6f, 0x4c, 0x58, 0xfa, 0x51, 0x89, 0x8f, 0x62, 0x9e, 0x66, 0x9a, - 0x9f, 0x2f, 0x4d, 0x21, 0xdf, 0x76, 0x51, 0x75, 0xb9, 0x06, 0xb8, 0x85, 0xac, 0x90, 0x0c, 0x2f, - 0x20, 0x93, 0x1e, 0xd5, 0xdd, 0xda, 0x7c, 0xd6, 0xac, 0x0c, 0xfa, 0x27, 0x90, 0x79, 0x95, 0x90, - 0x9c, 0x40, 0x86, 0x77, 0x50, 0x65, 0xea, 0x5f, 0x4e, 0x40, 0x9a, 0x63, 0x7a, 0xea, 0xe0, 0x1e, - 0x5f, 0xcf, 0x1d, 0xe3, 0x66, 0xee, 0x18, 0x7f, 0xe7, 0x8e, 0xf1, 0x63, 0xe1, 0x94, 0x6e, 0x16, - 0x4e, 0xe9, 0xcf, 0xc2, 0x29, 0x7d, 0xdd, 0x1f, 0x87, 0xfc, 0x7c, 0x32, 0xea, 0x06, 0x34, 0xea, - 0x71, 0x48, 0x93, 0x18, 0xf8, 0x15, 0x4d, 0x2f, 0xe4, 0xfb, 0x7e, 0x40, 0x53, 0xe8, 0x7d, 0x57, - 0xd7, 0x54, 0xde, 0xd1, 0x91, 0x25, 0x2f, 0xe9, 0x9b, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff, 0x04, - 0xbe, 0xfe, 0x6e, 0x0c, 0x04, 0x00, 0x00, + // 563 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, 0x22, 0xa1, + 0x32, 0xa1, 0x46, 0x1b, 0x47, 0x2e, 0x90, 0x0d, 0x41, 0x98, 0x40, 0x28, 0x3b, 0x20, 0xed, 0x52, + 0xa5, 0xb1, 0xd7, 0x59, 0x2c, 0x71, 0x88, 0xdd, 0x42, 0xbe, 0x05, 0x9f, 0x02, 0x71, 0xe4, 0xce, + 0x17, 0xd8, 0x8d, 0x1d, 0x39, 0x55, 0x28, 0x3d, 0x20, 0xf1, 0x29, 0x26, 0xdb, 0x49, 0x16, 0xb5, + 0xeb, 0xc5, 0x4a, 0xde, 0xfb, 0xbf, 0x9f, 0xed, 0xbf, 0xdf, 0x03, 0xa6, 0x4f, 0x59, 0xf0, 0xc5, + 0x63, 0x81, 0x25, 0x97, 0xe9, 0x9e, 0x35, 0xc6, 0x21, 0x66, 0x84, 0x0d, 0xa2, 0x98, 0x72, 0x0a, + 0x37, 0xf3, 0xfc, 0x40, 0x2e, 0xd3, 0xbd, 0xf6, 0xd6, 0x98, 0x8e, 0xa9, 0x4c, 0x5a, 0xe2, 0x4b, + 0xe9, 0xda, 0x3b, 0x4b, 0x1c, 0x9e, 0x44, 0x38, 0xa3, 0xb4, 0xef, 0x7a, 0x01, 0x09, 0xa9, 0x25, + 0x57, 0x15, 0xea, 0xfd, 0xae, 0x82, 0xd6, 0x6b, 0xb5, 0xd5, 0x31, 0xf7, 0x38, 0x86, 0xcf, 0x81, + 0x1e, 0x79, 0xb1, 0x17, 0x30, 0x43, 0xeb, 0x6a, 0xfd, 0xf5, 0x7d, 0x63, 0xb0, 0xb8, 0xf5, 0xe0, + 0x83, 0xcc, 0xdb, 0xcd, 0x8b, 0x59, 0xa7, 0xf2, 0xe3, 0xdf, 0xcf, 0x5d, 0xcd, 0xcd, 0x4a, 0xe0, + 0x5b, 0x50, 0xf7, 0x29, 0xc2, 0xcc, 0xa8, 0x76, 0xd7, 0xfa, 0xeb, 0xfb, 0xdb, 0xcb, 0xb5, 0x07, + 0x14, 0x61, 0x7b, 0x47, 0x54, 0xfe, 0x9f, 0x75, 0x36, 0xa4, 0xf8, 0x29, 0x0d, 0x08, 0xc7, 0x41, + 0xc4, 0x13, 0x05, 0x53, 0x08, 0x78, 0x02, 0x9a, 0x3e, 0x0d, 0x79, 0xec, 0xf9, 0x9c, 0x19, 0x6b, + 0x92, 0xd7, 0xbe, 0x89, 0xa7, 0x24, 0x76, 0x37, 0x63, 0xde, 0x2b, 0x8a, 0x16, 0xb9, 0xd7, 0x38, + 0xc1, 0x66, 0xf8, 0xf3, 0x04, 0x87, 0x3e, 0x66, 0x46, 0x6d, 0x15, 0xfb, 0x38, 0x93, 0x5c, 0xb3, + 0x8b, 0xa2, 0x25, 0x76, 0x91, 0xe9, 0x7d, 0xd7, 0x40, 0x4d, 0xdc, 0x12, 0x3e, 0x02, 0xb7, 0xc4, + 0x4d, 0x86, 0x04, 0x49, 0x2b, 0x6b, 0x36, 0x48, 0x67, 0x1d, 0x5d, 0xa4, 0x9c, 0x43, 0x57, 0x17, + 0x29, 0x07, 0x41, 0x5b, 0xdc, 0x52, 0x88, 0xc2, 0x53, 0x6a, 0x54, 0xa5, 0xe3, 0xed, 0x9b, 0x5d, + 0x73, 0xc2, 0x53, 0x5a, 0xf6, 0xbc, 0xe1, 0x67, 0x41, 0xf8, 0x10, 0x00, 0xc9, 0x18, 0x25, 0x1c, + 0x0b, 0xab, 0xb4, 0x7e, 0xcb, 0x95, 0x54, 0x5b, 0x04, 0xe0, 0x36, 0xd0, 0x23, 0x12, 0x86, 0x18, + 0x19, 0xb5, 0xae, 0xd6, 0x6f, 0xb8, 0xd9, 0x5f, 0xef, 0x57, 0x15, 0x34, 0x72, 0xfb, 0xe0, 0x13, + 0xb0, 0x99, 0xdb, 0x33, 0xf4, 0x10, 0x8a, 0x31, 0x53, 0x0d, 0xd0, 0x74, 0x37, 0xf2, 0xf8, 0x4b, + 0x15, 0x86, 0xef, 0xc1, 0xed, 0x42, 0x5a, 0x3a, 0xb6, 0xb9, 0xfa, 0x71, 0x16, 0x8f, 0xde, 0xf2, + 0x4b, 0x09, 0xe8, 0x80, 0x3b, 0x05, 0x8f, 0x89, 0x1e, 0xcc, 0x5e, 0xfb, 0xc1, 0x32, 0xf0, 0x1d, + 0x45, 0xf8, 0xbc, 0x4c, 0x2a, 0x4e, 0xa2, 0x9a, 0x97, 0x80, 0xfb, 0x05, 0x4a, 0x5a, 0x72, 0x46, + 0x18, 0xa7, 0x71, 0x92, 0xbd, 0xf1, 0xee, 0xea, 0x23, 0x0a, 0x87, 0xdf, 0x28, 0xf1, 0xab, 0x90, + 0xc7, 0x49, 0x79, 0x93, 0xa2, 0xa5, 0x4a, 0xa2, 0x9e, 0x0d, 0x1a, 0x79, 0x7f, 0xc0, 0x2e, 0xd0, + 0x09, 0x1a, 0x7e, 0xc2, 0x89, 0xb4, 0xac, 0x65, 0x37, 0xd3, 0x59, 0xa7, 0xee, 0x1c, 0x1e, 0xe1, + 0xc4, 0xad, 0x13, 0x74, 0x84, 0x13, 0xb8, 0x05, 0xea, 0x53, 0xef, 0x7c, 0x82, 0xa5, 0x57, 0x35, + 0x57, 0xfd, 0xd8, 0x2f, 0x2e, 0x52, 0x53, 0xbb, 0x4c, 0x4d, 0xed, 0x6f, 0x6a, 0x6a, 0xdf, 0xe6, + 0x66, 0xe5, 0x72, 0x6e, 0x56, 0xfe, 0xcc, 0xcd, 0xca, 0xc9, 0xe3, 0x31, 0xe1, 0x67, 0x93, 0xd1, + 0xc0, 0xa7, 0x81, 0x75, 0x40, 0x59, 0xf0, 0x31, 0x1f, 0x69, 0x64, 0x7d, 0x55, 0xa3, 0x2d, 0xe7, + 0x7a, 0xa4, 0xcb, 0x29, 0x7e, 0x76, 0x15, 0x00, 0x00, 0xff, 0xff, 0x45, 0x4b, 0xa7, 0x92, 0x40, + 0x04, 0x00, 0x00, } func (m *GenesisState) Marshal() (dAtA []byte, err error) { @@ -576,6 +601,7 @@ 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 @@ -672,9 +698,11 @@ func (m *Sequence) 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 @@ -860,6 +888,7 @@ func (m *GenesisState) Unmarshal(dAtA []byte) error { } return nil } + func (m *Code) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1016,6 +1045,7 @@ func (m *Code) Unmarshal(dAtA []byte) error { } return nil } + func (m *Contract) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1199,6 +1229,7 @@ func (m *Contract) Unmarshal(dAtA []byte) error { } return nil } + func (m *Sequence) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1302,6 +1333,7 @@ func (m *Sequence) Unmarshal(dAtA []byte) error { } return nil } + func skipGenesis(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/wasm/types/genesis_test.go b/x/wasm/types/genesis_test.go index 51c95e4..258528c 100644 --- a/x/wasm/types/genesis_test.go +++ b/x/wasm/types/genesis_test.go @@ -5,16 +5,17 @@ import ( "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" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/stretchr/testify/assert" - "github.com/tendermint/tendermint/libs/rand" - "github.com/stretchr/testify/require" ) +const invalidAddress = "invalid address" + func TestValidateGenesisState(t *testing.T) { specs := map[string]struct { srcMutator func(*GenesisState) @@ -37,7 +38,7 @@ func TestValidateGenesisState(t *testing.T) { }, "contract invalid": { srcMutator: func(s *GenesisState) { - s.Contracts[0].ContractAddress = "invalid" + s.Contracts[0].ContractAddress = invalidAddress }, expError: true, }, @@ -119,13 +120,13 @@ func TestContractValidateBasic(t *testing.T) { "all good": {srcMutator: func(_ *Contract) {}}, "contract address invalid": { srcMutator: func(c *Contract) { - c.ContractAddress = "invalid" + c.ContractAddress = invalidAddress }, expError: true, }, "contract info invalid": { srcMutator: func(c *Contract) { - c.ContractInfo.Creator = "invalid" + c.ContractInfo.Creator = invalidAddress }, expError: true, }, @@ -168,7 +169,7 @@ func TestGenesisContractInfoMarshalUnmarshal(t *testing.T) { 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 := govtypes.NewProposal(&govtypes.TextProposal{Title: "bar"}, 1, anyTime, anyTime) + myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "bar"}, 1, anyTime, anyTime) require.NoError(t, err) myExtension.TotalDeposit = nil @@ -182,10 +183,10 @@ func TestGenesisContractInfoMarshalUnmarshal(t *testing.T) { // register proposal as extension type interfaceRegistry.RegisterImplementations( (*ContractInfoExtension)(nil), - &govtypes.Proposal{}, + &v1beta1.Proposal{}, ) // register gov types for nested Anys - govtypes.RegisterInterfaces(interfaceRegistry) + v1beta1.RegisterInterfaces(interfaceRegistry) // when encode gs := GenesisState{ @@ -205,7 +206,7 @@ func TestGenesisContractInfoMarshalUnmarshal(t *testing.T) { dest := destGs.Contracts[0].ContractInfo assert.Equal(t, src, dest) // and sanity check nested any - var destExt govtypes.Proposal + 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 index 85a4a18..fd3297b 100644 --- a/x/wasm/types/iavl_range_test.go +++ b/x/wasm/types/iavl_range_test.go @@ -3,11 +3,11 @@ 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" - dbm "github.com/tendermint/tm-db" ) // This is modeled close to diff --git a/x/wasm/types/ibc.pb.go b/x/wasm/types/ibc.pb.go index de31ed5..0e25049 100644 --- a/x/wasm/types/ibc.pb.go +++ b/x/wasm/types/ibc.pb.go @@ -5,17 +5,20 @@ package types import ( fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/gogo/protobuf/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 -var _ = fmt.Errorf -var _ = math.Inf +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. @@ -44,9 +47,11 @@ 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) @@ -59,18 +64,65 @@ func (m *MsgIBCSend) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 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"` @@ -80,11 +132,13 @@ 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{1} + 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) @@ -97,12 +151,15 @@ func (m *MsgIBCCloseChannel) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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) } @@ -111,33 +168,35 @@ 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{ - // 308 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4a, 0xce, 0x2f, 0xce, - 0x2d, 0x4f, 0x2c, 0xce, 0xd5, 0x07, 0x13, 0x65, 0x86, 0xfa, 0x99, 0x49, 0xc9, 0x7a, 0x05, 0x45, - 0xf9, 0x25, 0xf9, 0x42, 0x02, 0x30, 0x39, 0x3d, 0x30, 0x51, 0x66, 0x28, 0x25, 0x92, 0x9e, 0x9f, - 0x9e, 0x0f, 0x96, 0xd4, 0x07, 0xb1, 0x20, 0xea, 0x94, 0x1e, 0x31, 0x72, 0x71, 0xf9, 0x16, 0xa7, - 0x7b, 0x3a, 0x39, 0x07, 0xa7, 0xe6, 0xa5, 0x08, 0x19, 0x73, 0xb1, 0x27, 0x67, 0x24, 0xe6, 0xe5, - 0xa5, 0xe6, 0x48, 0x30, 0x29, 0x30, 0x6a, 0x70, 0x3a, 0x49, 0x7e, 0xba, 0x27, 0x2f, 0x5a, 0x99, - 0x98, 0x9b, 0x63, 0xa5, 0x54, 0x9c, 0x5f, 0x5a, 0x94, 0x9c, 0x1a, 0x0f, 0x95, 0x57, 0x0a, 0x82, - 0xa9, 0x14, 0x72, 0xe0, 0xe2, 0x2b, 0xc9, 0xcc, 0x4d, 0xcd, 0x2f, 0x2d, 0x89, 0xcf, 0x48, 0xcd, - 0x4c, 0xcf, 0x28, 0x91, 0x60, 0x51, 0x60, 0xd4, 0x60, 0x41, 0xd6, 0x8b, 0x2a, 0xaf, 0x14, 0xc4, - 0x0b, 0x15, 0xf0, 0x00, 0xf3, 0x85, 0x3c, 0xb9, 0x04, 0x61, 0x2a, 0x40, 0x74, 0x71, 0x49, 0x62, - 0x6e, 0x81, 0x04, 0x2b, 0xd8, 0x10, 0x99, 0x4f, 0xf7, 0xe4, 0x25, 0x50, 0x0d, 0x81, 0x2b, 0x51, - 0x0a, 0x12, 0x80, 0x8a, 0x85, 0xc0, 0x84, 0x84, 0x84, 0xb8, 0x58, 0x52, 0x12, 0x4b, 0x12, 0x25, - 0xd8, 0x14, 0x18, 0x35, 0x78, 0x82, 0xc0, 0x6c, 0x25, 0x4f, 0x2e, 0x21, 0x88, 0x1f, 0x9d, 0x73, - 0xf2, 0x8b, 0x53, 0x9d, 0xa1, 0xce, 0x26, 0xc7, 0xaf, 0x4e, 0xde, 0x27, 0x1e, 0xca, 0x31, 0x9c, - 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, 0x6e, 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, 0x01, 0x89, 0xab, 0x92, 0xca, 0x82, 0xd4, - 0xe2, 0x24, 0x36, 0x70, 0x1c, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x4d, 0xdf, 0xfa, 0xdc, - 0xc9, 0x01, 0x00, 0x00, + // 329 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, 0xc1, 0x70, + 0xa2, 0x12, 0x6e, 0x9e, 0x0c, 0xf5, 0x20, 0x07, 0x2f, 0xd5, 0xc4, 0xc4, 0x0b, 0x29, 0x65, 0xd2, + 0x36, 0x61, 0xbb, 0x95, 0xdd, 0xa2, 0xbc, 0x85, 0x8f, 0xc5, 0x91, 0xa3, 0x27, 0xa2, 0xe5, 0x0d, + 0x78, 0x02, 0xd3, 0xa5, 0x8b, 0x72, 0xf5, 0x32, 0x3b, 0xf3, 0x7d, 0xdf, 0xcc, 0x66, 0xe6, 0xc3, + 0xf5, 0x40, 0x48, 0xfe, 0xea, 0x4b, 0xee, 0xe8, 0x30, 0xed, 0x38, 0xf1, 0x30, 0x68, 0xa7, 0x13, + 0xa1, 0x04, 0xa9, 0x19, 0xae, 0xad, 0xc3, 0xb4, 0x53, 0x3f, 0x0d, 0x45, 0x28, 0x34, 0xe9, 0x14, + 0xd9, 0x46, 0xc7, 0x72, 0x84, 0xf1, 0xbd, 0x0c, 0xfb, 0x3d, 0xf7, 0x01, 0x92, 0x11, 0xe9, 0xe2, + 0xbd, 0x20, 0xf2, 0x93, 0x04, 0xc6, 0xf6, 0xbf, 0x26, 0x6a, 0x1d, 0xf4, 0xce, 0xd7, 0xcb, 0xc6, + 0xd9, 0xcc, 0xe7, 0xe3, 0x6b, 0x26, 0x45, 0x36, 0x09, 0x60, 0x50, 0xf2, 0xcc, 0x33, 0x4a, 0x72, + 0x83, 0x8f, 0x55, 0xcc, 0x41, 0x64, 0x6a, 0x10, 0x41, 0x1c, 0x46, 0xca, 0xae, 0x34, 0x51, 0xab, + 0xf2, 0xbb, 0x77, 0x97, 0x67, 0xde, 0x51, 0x09, 0xdc, 0xe9, 0x9a, 0xf4, 0xf1, 0x89, 0x51, 0x14, + 0xaf, 0x54, 0x3e, 0x4f, 0xed, 0xff, 0x7a, 0xc8, 0xc5, 0x7a, 0xd9, 0xb0, 0x77, 0x87, 0x6c, 0x25, + 0xcc, 0xab, 0x95, 0xd8, 0xa3, 0x81, 0x08, 0xc1, 0x95, 0x91, 0xaf, 0x7c, 0xbb, 0xda, 0x44, 0xad, + 0x43, 0x4f, 0xe7, 0xec, 0x0a, 0x93, 0x9f, 0x1d, 0x3d, 0x90, 0xa9, 0x48, 0x24, 0x90, 0x3a, 0xde, + 0x97, 0xf0, 0x92, 0x41, 0x12, 0x80, 0x8d, 0x8a, 0xbf, 0xbc, 0x6d, 0xcd, 0xfa, 0xa6, 0xc3, 0x1d, + 0x0b, 0x09, 0x6e, 0xb9, 0xe8, 0x5f, 0xae, 0xd3, 0xbb, 0x9d, 0x7f, 0x51, 0x6b, 0x9e, 0x53, 0xb4, + 0xc8, 0x29, 0xfa, 0xcc, 0x29, 0x7a, 0x5f, 0x51, 0x6b, 0xb1, 0xa2, 0xd6, 0xc7, 0x8a, 0x5a, 0xcf, + 0x97, 0x61, 0xac, 0xa2, 0x6c, 0xd8, 0x0e, 0x04, 0x77, 0x5c, 0x21, 0xf9, 0x93, 0xb1, 0x73, 0xe4, + 0xbc, 0x6d, 0x6c, 0x55, 0xb3, 0x14, 0xe4, 0xb0, 0xaa, 0xed, 0xea, 0x7e, 0x07, 0x00, 0x00, 0xff, + 0xff, 0x2c, 0xea, 0x36, 0xb0, 0xf4, 0x01, 0x00, 0x00, } func (m *MsgIBCSend) Marshal() (dAtA []byte, err error) { @@ -187,6 +246,34 @@ func (m *MsgIBCSend) MarshalToSizedBuffer(dAtA []byte) (int, error) { 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) @@ -228,6 +315,7 @@ func encodeVarintIbc(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } + func (m *MsgIBCSend) Size() (n int) { if m == nil { return 0 @@ -251,6 +339,18 @@ func (m *MsgIBCSend) Size() (n int) { 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 @@ -267,9 +367,11 @@ func (m *MsgIBCCloseChannel) Size() (n int) { 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 @@ -424,6 +526,77 @@ func (m *MsgIBCSend) Unmarshal(dAtA []byte) error { } 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 @@ -506,6 +679,7 @@ func (m *MsgIBCCloseChannel) Unmarshal(dAtA []byte) error { } return nil } + func skipIbc(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/wasm/types/json_matching_test.go b/x/wasm/types/json_matching_test.go index 01d2d3e..286fde3 100644 --- a/x/wasm/types/json_matching_test.go +++ b/x/wasm/types/json_matching_test.go @@ -81,11 +81,11 @@ func TestIsJSONObjectWithTopLevelKey(t *testing.T) { expResult: false, }, // not supported: https://github.com/golang/go/issues/24415 - //"errors for duplicate key": { + // "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": { diff --git a/x/wasm/types/keys.go b/x/wasm/types/keys.go index 95078e1..4f60587 100644 --- a/x/wasm/types/keys.go +++ b/x/wasm/types/keys.go @@ -22,7 +22,6 @@ const ( RouterKey = ModuleName ) -// nolint var ( CodeKeyPrefix = []byte{0x01} ContractKeyPrefix = []byte{0x02} @@ -33,6 +32,7 @@ var ( PinnedCodeIndexPrefix = []byte{0x07} TXCounterPrefix = []byte{0x08} ContractsByCreatorPrefix = []byte{0x09} + ParamsKey = []byte{0x10} KeyLastCodeID = append(SequenceKeyPrefix, []byte("lastCodeId")...) KeyLastInstanceID = append(SequenceKeyPrefix, []byte("lastContractId")...) diff --git a/x/wasm/types/keys_test.go b/x/wasm/types/keys_test.go index 3db6bba..a5cbce7 100644 --- a/x/wasm/types/keys_test.go +++ b/x/wasm/types/keys_test.go @@ -123,6 +123,7 @@ func TestGetContractByCreatorSecondaryIndexKey(t *testing.T) { 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) diff --git a/x/wasm/types/params.go b/x/wasm/types/params.go index 0ee7dcb..d06ba7e 100644 --- a/x/wasm/types/params.go +++ b/x/wasm/types/params.go @@ -4,19 +4,13 @@ import ( "encoding/json" "fmt" + errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "github.com/gogo/protobuf/jsonpb" + "github.com/cosmos/gogoproto/jsonpb" "github.com/pkg/errors" "gopkg.in/yaml.v2" ) -var ( - ParamStoreKeyUploadAccess = []byte("uploadAccess") - ParamStoreKeyInstantiateAccess = []byte("instantiateAccess") -) - var AllAccessTypes = []AccessType{ AccessTypeNobody, AccessTypeOnlyAddress, @@ -44,7 +38,7 @@ func (a AccessType) With(addrs ...sdk.AccAddress) AccessConfig { bech32Addrs[i] = v.String() } if err := assertValidAddresses(bech32Addrs); err != nil { - panic(sdkerrors.Wrap(err, "addresses")) + panic(errorsmod.Wrap(err, "addresses")) } return AccessConfig{Permission: AccessTypeAnyOfAddresses, Addresses: bech32Addrs} } @@ -98,11 +92,6 @@ var ( AllowNobody = AccessConfig{Permission: AccessTypeNobody} ) -// ParamKeyTable returns the parameter key table. -func ParamKeyTable() paramtypes.KeyTable { - return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) -} - // DefaultParams returns default wasm parameters func DefaultParams() Params { return Params{ @@ -119,14 +108,6 @@ func (p Params) String() string { return string(out) } -// 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), - } -} - // ValidateBasic performs basic validation on wasm parameters func (p Params) ValidateBasic() error { if err := validateAccessType(p.InstantiateDefaultPermission); err != nil { @@ -152,24 +133,24 @@ func validateAccessType(i interface{}) error { return fmt.Errorf("invalid parameter type: %T", i) } if a == AccessTypeUnspecified { - return sdkerrors.Wrap(ErrEmpty, "type") + return errorsmod.Wrap(ErrEmpty, "type") } for _, v := range AllAccessTypes { if v == a { return nil } } - return sdkerrors.Wrapf(ErrInvalid, "unknown type: %q", a) + return errorsmod.Wrapf(ErrInvalid, "unknown type: %q", a) } // ValidateBasic performs basic validation func (a AccessConfig) ValidateBasic() error { switch a.Permission { case AccessTypeUnspecified: - return sdkerrors.Wrap(ErrEmpty, "type") + return errorsmod.Wrap(ErrEmpty, "type") case AccessTypeNobody, AccessTypeEverybody: if len(a.Address) != 0 { - return sdkerrors.Wrap(ErrInvalid, "address not allowed for this type") + return errorsmod.Wrap(ErrInvalid, "address not allowed for this type") } return nil case AccessTypeOnlyAddress: @@ -182,9 +163,9 @@ func (a AccessConfig) ValidateBasic() error { if a.Address != "" { return ErrInvalid.Wrap("address field set") } - return sdkerrors.Wrap(assertValidAddresses(a.Addresses), "addresses") + return errorsmod.Wrap(assertValidAddresses(a.Addresses), "addresses") } - return sdkerrors.Wrapf(ErrInvalid, "unknown type: %q", a.Permission) + return errorsmod.Wrapf(ErrInvalid, "unknown type: %q", a.Permission) } func assertValidAddresses(addrs []string) error { @@ -194,7 +175,7 @@ func assertValidAddresses(addrs []string) error { idx := make(map[string]struct{}, len(addrs)) for _, a := range addrs { if _, err := sdk.AccAddressFromBech32(a); err != nil { - return sdkerrors.Wrapf(err, "address: %s", a) + return errorsmod.Wrapf(err, "address: %s", a) } if _, exists := idx[a]; exists { return ErrDuplicate.Wrapf("address: %s", a) diff --git a/x/wasm/types/params_legacy.go b/x/wasm/types/params_legacy.go new file mode 100644 index 0000000..db38cb8 --- /dev/null +++ b/x/wasm/types/params_legacy.go @@ -0,0 +1,26 @@ +/* +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/proposal.go b/x/wasm/types/proposal.go index 96e2c9b..468f45b 100644 --- a/x/wasm/types/proposal.go +++ b/x/wasm/types/proposal.go @@ -6,9 +6,11 @@ import ( "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 @@ -58,7 +60,7 @@ func ConvertToProposals(keys []string) ([]ProposalType, error) { proposals := make([]ProposalType, len(keys)) for i, key := range keys { if _, ok := valid[key]; !ok { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "'%s' is not a valid ProposalType", key) + return nil, errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "'%s' is not a valid ProposalType", key) } proposals[i] = ProposalType(key) } @@ -66,30 +68,18 @@ func ConvertToProposals(keys []string) ([]ProposalType, error) { } func init() { // register new content types with the sdk - govtypes.RegisterProposalType(string(ProposalTypeStoreCode)) - govtypes.RegisterProposalType(string(ProposalTypeInstantiateContract)) - govtypes.RegisterProposalType(string(ProposalTypeInstantiateContract2)) - govtypes.RegisterProposalType(string(ProposalTypeMigrateContract)) - govtypes.RegisterProposalType(string(ProposalTypeSudoContract)) - govtypes.RegisterProposalType(string(ProposalTypeExecuteContract)) - govtypes.RegisterProposalType(string(ProposalTypeUpdateAdmin)) - govtypes.RegisterProposalType(string(ProposalTypeClearAdmin)) - govtypes.RegisterProposalType(string(ProposalTypePinCodes)) - govtypes.RegisterProposalType(string(ProposalTypeUnpinCodes)) - govtypes.RegisterProposalType(string(ProposalTypeUpdateInstantiateConfig)) - govtypes.RegisterProposalType(string(ProposalTypeStoreAndInstantiateContractProposal)) - govtypes.RegisterProposalTypeCodec(&StoreCodeProposal{}, "wasm/StoreCodeProposal") - govtypes.RegisterProposalTypeCodec(&InstantiateContractProposal{}, "wasm/InstantiateContractProposal") - govtypes.RegisterProposalTypeCodec(&InstantiateContract2Proposal{}, "wasm/InstantiateContract2Proposal") - govtypes.RegisterProposalTypeCodec(&MigrateContractProposal{}, "wasm/MigrateContractProposal") - govtypes.RegisterProposalTypeCodec(&SudoContractProposal{}, "wasm/SudoContractProposal") - govtypes.RegisterProposalTypeCodec(&ExecuteContractProposal{}, "wasm/ExecuteContractProposal") - govtypes.RegisterProposalTypeCodec(&UpdateAdminProposal{}, "wasm/UpdateAdminProposal") - govtypes.RegisterProposalTypeCodec(&ClearAdminProposal{}, "wasm/ClearAdminProposal") - govtypes.RegisterProposalTypeCodec(&PinCodesProposal{}, "wasm/PinCodesProposal") - govtypes.RegisterProposalTypeCodec(&UnpinCodesProposal{}, "wasm/UnpinCodesProposal") - govtypes.RegisterProposalTypeCodec(&UpdateInstantiateConfigProposal{}, "wasm/UpdateInstantiateConfigProposal") - govtypes.RegisterProposalTypeCodec(&StoreAndInstantiateContractProposal{}, "wasm/StoreAndInstantiateContractProposal") + 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( @@ -124,21 +114,21 @@ func (p StoreCodeProposal) ValidateBasic() error { return err } if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return sdkerrors.Wrap(err, "run as") + return errorsmod.Wrap(err, "run as") } if err := validateWasmCode(p.WASMByteCode, MaxProposalWasmSize); err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) + return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) } if p.InstantiatePermission != nil { if err := p.InstantiatePermission.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "instantiate permission") + return errorsmod.Wrap(err, "instantiate permission") } } if err := ValidateVerificationInfo(p.Source, p.Builder, p.CodeHash); err != nil { - return sdkerrors.Wrapf(err, "code verification info") + return errorsmod.Wrapf(err, "code verification info") } return nil } @@ -212,11 +202,11 @@ func (p InstantiateContractProposal) ValidateBasic() error { return err } if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "run as") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "run as") } if p.CodeID == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") } if err := ValidateLabel(p.Label); err != nil { @@ -233,7 +223,7 @@ func (p InstantiateContractProposal) ValidateBasic() error { } } if err := p.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } return nil } @@ -312,7 +302,7 @@ func (p InstantiateContract2Proposal) ValidateBasic() error { } // Validate run as if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "run as") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "run as") } // Validate admin if len(p.Admin) != 0 { @@ -322,7 +312,7 @@ func (p InstantiateContract2Proposal) ValidateBasic() error { } // Validate codeid if p.CodeID == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") } // Validate label if err := ValidateLabel(p.Label); err != nil { @@ -330,7 +320,7 @@ func (p InstantiateContract2Proposal) ValidateBasic() error { } // Validate msg if err := p.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } // Validate funds if !p.Funds.IsValid() { @@ -338,7 +328,7 @@ func (p InstantiateContract2Proposal) ValidateBasic() error { } // Validate salt if len(p.Salt) == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "salt is required") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "salt is required") } return nil } @@ -435,20 +425,20 @@ func (p StoreAndInstantiateContractProposal) ValidateBasic() error { return err } if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return sdkerrors.Wrap(err, "run as") + return errorsmod.Wrap(err, "run as") } if err := validateWasmCode(p.WASMByteCode, MaxProposalWasmSize); err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) + return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) } if err := ValidateVerificationInfo(p.Source, p.Builder, p.CodeHash); err != nil { - return sdkerrors.Wrap(err, "code info") + return errorsmod.Wrap(err, "code info") } if p.InstantiatePermission != nil { if err := p.InstantiatePermission.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "instantiate permission") + return errorsmod.Wrap(err, "instantiate permission") } } @@ -466,7 +456,7 @@ func (p StoreAndInstantiateContractProposal) ValidateBasic() error { } } if err := p.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } return nil } @@ -557,13 +547,13 @@ func (p MigrateContractProposal) ValidateBasic() error { return err } if p.CodeID == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code_id is required") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code_id is required") } if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } if err := p.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } return nil } @@ -628,10 +618,10 @@ func (p SudoContractProposal) ValidateBasic() error { return err } if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } if err := p.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } return nil } @@ -690,16 +680,16 @@ func (p ExecuteContractProposal) ValidateBasic() error { return err } if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } if _, err := sdk.AccAddressFromBech32(p.RunAs); err != nil { - return sdkerrors.Wrap(err, "run as") + return errorsmod.Wrap(err, "run as") } if !p.Funds.IsValid() { return sdkerrors.ErrInvalidCoins } if err := p.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } return nil } @@ -762,10 +752,10 @@ func (p UpdateAdminProposal) ValidateBasic() error { return err } if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } if _, err := sdk.AccAddressFromBech32(p.NewAdmin); err != nil { - return sdkerrors.Wrap(err, "new admin") + return errorsmod.Wrap(err, "new admin") } return nil } @@ -806,7 +796,7 @@ func (p ClearAdminProposal) ValidateBasic() error { return err } if _, err := sdk.AccAddressFromBech32(p.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } return nil } @@ -850,7 +840,7 @@ func (p PinCodesProposal) ValidateBasic() error { return err } if len(p.CodeIDs) == 0 { - return sdkerrors.Wrap(ErrEmpty, "code ids") + return errorsmod.Wrap(ErrEmpty, "code ids") } return nil } @@ -894,7 +884,7 @@ func (p UnpinCodesProposal) ValidateBasic() error { return err } if len(p.CodeIDs) == 0 { - return sdkerrors.Wrap(ErrEmpty, "code ids") + return errorsmod.Wrap(ErrEmpty, "code ids") } return nil } @@ -910,22 +900,22 @@ func (p UnpinCodesProposal) String() string { func validateProposalCommons(title, description string) error { if strings.TrimSpace(title) != title { - return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal title must not start/end with white spaces") + return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal title must not start/end with white spaces") } if len(title) == 0 { - return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal title cannot be blank") + return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal title cannot be blank") } - if len(title) > govtypes.MaxTitleLength { - return sdkerrors.Wrapf(govtypes.ErrInvalidProposalContent, "proposal title is longer than max length of %d", govtypes.MaxTitleLength) + 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 sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal description must not start/end with white spaces") + return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal description must not start/end with white spaces") } if len(description) == 0 { - return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal description cannot be blank") + return errorsmod.Wrap(govtypes.ErrInvalidProposalContent, "proposal description cannot be blank") } - if len(description) > govtypes.MaxDescriptionLength { - return sdkerrors.Wrapf(govtypes.ErrInvalidProposalContent, "proposal description is longer than max length of %d", govtypes.MaxDescriptionLength) + if len(description) > v1beta1.MaxDescriptionLength { + return errorsmod.Wrapf(govtypes.ErrInvalidProposalContent, "proposal description is longer than max length of %d", v1beta1.MaxDescriptionLength) } return nil } @@ -962,16 +952,16 @@ func (p UpdateInstantiateConfigProposal) ValidateBasic() error { return err } if len(p.AccessConfigUpdates) == 0 { - return sdkerrors.Wrap(ErrEmpty, "code updates") + return errorsmod.Wrap(ErrEmpty, "code updates") } dedup := make(map[uint64]bool) for _, codeUpdate := range p.AccessConfigUpdates { _, found := dedup[codeUpdate.CodeID] if found { - return sdkerrors.Wrapf(ErrDuplicate, "duplicate code: %d", codeUpdate.CodeID) + return errorsmod.Wrapf(ErrDuplicate, "duplicate code: %d", codeUpdate.CodeID) } if err := codeUpdate.InstantiatePermission.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "instantiate permission") + return errorsmod.Wrap(err, "instantiate permission") } dedup[codeUpdate.CodeID] = true } diff --git a/x/wasm/types/proposal.pb.go b/x/wasm/types/proposal.pb.go index 60f8026..b445f8e 100644 --- a/x/wasm/types/proposal.pb.go +++ b/x/wasm/types/proposal.pb.go @@ -6,19 +6,24 @@ package types import ( bytes "bytes" 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/gogo/protobuf/proto" 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 -var _ = fmt.Errorf -var _ = math.Inf +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. @@ -26,7 +31,12 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// StoreCodeProposal gov proposal content type to submit WASM code to the system +// 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"` @@ -55,9 +65,11 @@ 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) @@ -70,20 +82,27 @@ func (m *StoreCodeProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, e 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 -// InstantiateContractProposal gov proposal content type to instantiate a -// contract. +// 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"` @@ -108,9 +127,11 @@ 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) @@ -123,20 +144,27 @@ func (m *InstantiateContractProposal) XXX_Marshal(b []byte, deterministic bool) 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 -// InstantiateContract2Proposal gov proposal content type to instantiate -// contract 2 +// 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"` @@ -166,9 +194,11 @@ 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) @@ -181,19 +211,27 @@ func (m *InstantiateContract2Proposal) XXX_Marshal(b []byte, deterministic bool) 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 -// MigrateContractProposal gov proposal content type to migrate a contract. +// 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"` @@ -212,9 +250,11 @@ 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) @@ -227,19 +267,27 @@ func (m *MigrateContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]b 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 -// SudoContractProposal gov proposal content type to call sudo on a contract. +// 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"` @@ -256,9 +304,11 @@ 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) @@ -271,20 +321,27 @@ func (m *SudoContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte 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 -// ExecuteContractProposal gov proposal content type to call execute on a -// contract. +// 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"` @@ -305,9 +362,11 @@ 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) @@ -320,19 +379,27 @@ func (m *ExecuteContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]b 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 -// UpdateAdminProposal gov proposal content type to set an admin for a contract. +// 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"` @@ -349,9 +416,11 @@ 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) @@ -364,20 +433,27 @@ func (m *UpdateAdminProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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 -// ClearAdminProposal gov proposal content type to clear the admin of a -// contract. +// 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"` @@ -392,9 +468,11 @@ 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) @@ -407,20 +485,27 @@ func (m *ClearAdminProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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 -// PinCodesProposal gov proposal content type to pin a set of code ids in the -// wasmvm cache. +// 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"` @@ -435,9 +520,11 @@ 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) @@ -450,20 +537,27 @@ func (m *PinCodesProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, er 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 -// UnpinCodesProposal gov proposal content type to unpin a set of code ids in -// the wasmvm cache. +// 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"` @@ -478,9 +572,11 @@ 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) @@ -493,12 +589,15 @@ func (m *UnpinCodesProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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) } @@ -519,9 +618,11 @@ 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) @@ -534,20 +635,27 @@ func (m *AccessConfigUpdate) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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 -// UpdateInstantiateConfigProposal gov proposal content type to update -// instantiate config to a set of code ids. +// 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"` @@ -563,9 +671,11 @@ 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) @@ -578,20 +688,27 @@ func (m *UpdateInstantiateConfigProposal) XXX_Marshal(b []byte, deterministic bo 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 -// StoreAndInstantiateContractProposal gov proposal content type to store -// and instantiate the contract. +// 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"` @@ -628,9 +745,11 @@ 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) @@ -643,12 +762,15 @@ func (m *StoreAndInstantiateContractProposal) XXX_Marshal(b []byte, deterministi 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) } @@ -674,69 +796,80 @@ func init() { func init() { proto.RegisterFile("cosmwasm/wasm/v1/proposal.proto", fileDescriptor_be6422d717c730cb) } var fileDescriptor_be6422d717c730cb = []byte{ - // 989 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x57, 0xcf, 0x6f, 0xe3, 0xc4, - 0x17, 0x8f, 0xf3, 0xc3, 0x71, 0x5e, 0xf2, 0xfd, 0x12, 0x66, 0xd3, 0xd6, 0x74, 0x17, 0x3b, 0xf2, - 0x22, 0x94, 0x4b, 0x13, 0x52, 0x24, 0x04, 0xdc, 0xe2, 0x80, 0x44, 0x57, 0xaa, 0x54, 0xb9, 0xaa, - 0x90, 0x40, 0x22, 0x9a, 0xd8, 0x93, 0xc4, 0xda, 0xc4, 0x13, 0x79, 0xc6, 0x4d, 0xfb, 0x5f, 0x80, - 0x84, 0x38, 0xf1, 0x07, 0xa0, 0xbd, 0x20, 0xee, 0xfc, 0x01, 0x15, 0xa7, 0x3d, 0xee, 0x29, 0xb0, - 0xe9, 0x91, 0x5b, 0x4f, 0x88, 0x13, 0xf2, 0x8c, 0x93, 0x4d, 0xbb, 0x6d, 0x76, 0x17, 0x9a, 0x95, - 0x90, 0xb8, 0x24, 0x7e, 0xf3, 0xde, 0xcc, 0xfb, 0xbc, 0x8f, 0xde, 0x1b, 0x7f, 0x0c, 0xa6, 0x4b, - 0xd9, 0x68, 0x82, 0xd9, 0xa8, 0x21, 0x7e, 0x8e, 0x9b, 0x8d, 0x71, 0x48, 0xc7, 0x94, 0xe1, 0x61, - 0x7d, 0x1c, 0x52, 0x4e, 0x51, 0x79, 0x1e, 0x50, 0x17, 0x3f, 0xc7, 0xcd, 0xed, 0x4a, 0x9f, 0xf6, - 0xa9, 0x70, 0x36, 0xe2, 0x27, 0x19, 0xb7, 0x6d, 0xc4, 0x71, 0x94, 0x35, 0xba, 0x98, 0x91, 0xc6, - 0x71, 0xb3, 0x4b, 0x38, 0x6e, 0x36, 0x5c, 0xea, 0x07, 0x89, 0xff, 0xde, 0x73, 0x89, 0xf8, 0xe9, - 0x98, 0x30, 0xe9, 0xb5, 0x7e, 0x4f, 0xc3, 0x9b, 0x87, 0x9c, 0x86, 0xa4, 0x4d, 0x3d, 0x72, 0x90, - 0x20, 0x40, 0x15, 0xc8, 0x71, 0x9f, 0x0f, 0x89, 0xae, 0x54, 0x95, 0x5a, 0xc1, 0x91, 0x06, 0xaa, - 0x42, 0xd1, 0x23, 0xcc, 0x0d, 0xfd, 0x31, 0xf7, 0x69, 0xa0, 0xa7, 0x85, 0x6f, 0x79, 0x09, 0x6d, - 0x80, 0x1a, 0x46, 0x41, 0x07, 0x33, 0x3d, 0x23, 0x37, 0x86, 0x51, 0xd0, 0x62, 0xe8, 0x03, 0xf8, - 0x7f, 0x9c, 0xbb, 0xd3, 0x3d, 0xe5, 0xa4, 0xe3, 0x52, 0x8f, 0xe8, 0xd9, 0xaa, 0x52, 0x2b, 0xd9, - 0xe5, 0xd9, 0xd4, 0x2c, 0x7d, 0xde, 0x3a, 0xdc, 0xb7, 0x4f, 0xb9, 0x00, 0xe0, 0x94, 0xe2, 0xb8, - 0xb9, 0x85, 0x8e, 0x60, 0xd3, 0x0f, 0x18, 0xc7, 0x01, 0xf7, 0x31, 0x27, 0x9d, 0x31, 0x09, 0x47, - 0x3e, 0x63, 0x71, 0xee, 0x7c, 0x55, 0xa9, 0x15, 0x77, 0x8d, 0xfa, 0x55, 0x8e, 0xea, 0x2d, 0xd7, - 0x25, 0x8c, 0xb5, 0x69, 0xd0, 0xf3, 0xfb, 0xce, 0xc6, 0xd2, 0xee, 0x83, 0xc5, 0x66, 0xf4, 0x36, - 0x40, 0x14, 0x8c, 0xfd, 0x40, 0x42, 0xd1, 0xaa, 0x4a, 0x4d, 0x73, 0x0a, 0x62, 0x45, 0x64, 0xdd, - 0x04, 0x95, 0xd1, 0x28, 0x74, 0x89, 0x5e, 0x10, 0x45, 0x24, 0x16, 0xd2, 0x21, 0xdf, 0x8d, 0xfc, - 0xa1, 0x47, 0x42, 0x1d, 0x84, 0x63, 0x6e, 0xa2, 0xbb, 0x50, 0x88, 0x8f, 0xea, 0x0c, 0x30, 0x1b, - 0xe8, 0xc5, 0xb8, 0x34, 0x47, 0x8b, 0x17, 0x3e, 0xc3, 0x6c, 0xf0, 0x20, 0xab, 0xe5, 0xca, 0xea, - 0x83, 0xac, 0xa6, 0x96, 0xf3, 0xd6, 0x2f, 0x69, 0xb8, 0xbb, 0xf7, 0x0c, 0x53, 0x9b, 0x06, 0x3c, - 0xc4, 0x2e, 0x5f, 0x17, 0xef, 0x15, 0xc8, 0x61, 0x6f, 0xe4, 0x07, 0x82, 0xee, 0x82, 0x23, 0x0d, - 0x74, 0x1f, 0xf2, 0x02, 0xad, 0xef, 0xe9, 0xb9, 0xaa, 0x52, 0xcb, 0xda, 0x30, 0x9b, 0x9a, 0x6a, - 0x5c, 0xfa, 0xde, 0x27, 0x8e, 0x1a, 0xbb, 0xf6, 0xbc, 0x78, 0xeb, 0x10, 0x77, 0xc9, 0x50, 0x57, - 0xe5, 0x56, 0x61, 0xa0, 0x1a, 0x64, 0x46, 0xac, 0x2f, 0xd8, 0x2f, 0xd9, 0x9b, 0x7f, 0x4e, 0x4d, - 0xe4, 0xe0, 0xc9, 0xbc, 0x8a, 0x7d, 0xc2, 0x18, 0xee, 0x13, 0x27, 0x0e, 0x41, 0x18, 0x72, 0xbd, - 0x28, 0xf0, 0x98, 0xae, 0x55, 0x33, 0xb5, 0xe2, 0xee, 0x5b, 0x75, 0xd9, 0xa5, 0xf5, 0xb8, 0x4b, - 0xeb, 0x49, 0x97, 0xd6, 0xdb, 0xd4, 0x0f, 0xec, 0xf7, 0xce, 0xa6, 0x66, 0xea, 0xd1, 0xaf, 0x66, - 0xad, 0xef, 0xf3, 0x41, 0xd4, 0xad, 0xbb, 0x74, 0xd4, 0x48, 0x5a, 0x5a, 0xfe, 0xed, 0x30, 0xef, - 0x61, 0xd2, 0xb3, 0xf1, 0x06, 0xe6, 0xc8, 0x93, 0xad, 0x3f, 0xd2, 0x70, 0xef, 0x1a, 0x32, 0x77, - 0xff, 0x63, 0xf3, 0x6f, 0xb0, 0x89, 0x10, 0x64, 0x19, 0x1e, 0x72, 0xd1, 0xf3, 0x25, 0x47, 0x3c, - 0xa3, 0x2d, 0xc8, 0xf7, 0xfc, 0x93, 0x4e, 0x0c, 0x12, 0xc4, 0x94, 0xa8, 0x3d, 0xff, 0x64, 0x9f, - 0xf5, 0xad, 0x9f, 0x15, 0xd8, 0xda, 0xf7, 0xfb, 0xe1, 0x6d, 0xf6, 0xf0, 0x36, 0x68, 0x6e, 0x72, - 0x56, 0xc2, 0xf0, 0xc2, 0x7e, 0x39, 0x92, 0x13, 0x3a, 0xd5, 0x17, 0xd2, 0x69, 0x7d, 0xab, 0x40, - 0xe5, 0x30, 0xf2, 0xe8, 0x5a, 0xb0, 0x67, 0xae, 0x60, 0x4f, 0x60, 0x65, 0x5f, 0x0c, 0xeb, 0x9b, - 0x34, 0x6c, 0x7d, 0x7a, 0x42, 0xdc, 0x68, 0xfd, 0x37, 0xc3, 0x2a, 0xb2, 0x13, 0xc0, 0xb9, 0x57, - 0x68, 0x4b, 0x75, 0x6d, 0x43, 0xfe, 0xbd, 0x02, 0x77, 0x8e, 0xc6, 0x1e, 0xe6, 0xa4, 0x15, 0x8f, - 0xdb, 0x3f, 0xe6, 0xa3, 0x09, 0x85, 0x80, 0x4c, 0x3a, 0x72, 0x90, 0x05, 0x25, 0x76, 0xe5, 0x62, - 0x6a, 0x96, 0x4f, 0xf1, 0x68, 0xf8, 0xb1, 0xb5, 0x70, 0x59, 0x8e, 0x16, 0x90, 0x89, 0x48, 0xb9, - 0x8a, 0x2b, 0x6b, 0x00, 0xa8, 0x3d, 0x24, 0x38, 0xbc, 0x1d, 0x70, 0x2b, 0xda, 0xc8, 0xfa, 0x51, - 0x81, 0xf2, 0x81, 0x7c, 0x43, 0xb1, 0x45, 0xa2, 0x77, 0x2f, 0x25, 0xb2, 0xcb, 0x17, 0x53, 0xb3, - 0x24, 0x2b, 0x11, 0xcb, 0xd6, 0x3c, 0xf5, 0x87, 0xd7, 0xa4, 0xb6, 0x37, 0x2f, 0xa6, 0x26, 0x92, - 0xd1, 0x4b, 0x4e, 0xeb, 0x32, 0xa4, 0x8f, 0x40, 0x4b, 0x26, 0x2f, 0xee, 0xa0, 0x4c, 0x2d, 0x6b, - 0x1b, 0xb3, 0xa9, 0x99, 0x97, 0xa3, 0xc7, 0x2e, 0xa6, 0xe6, 0x1b, 0xf2, 0x84, 0x79, 0x90, 0xe5, - 0xe4, 0xe5, 0x38, 0x32, 0xeb, 0x27, 0x05, 0xd0, 0xd1, 0xfc, 0xad, 0xfa, 0x2f, 0xc1, 0xfc, 0x9d, - 0x02, 0x68, 0x59, 0x42, 0xc8, 0xd6, 0x5b, 0xbe, 0x7f, 0x94, 0x1b, 0xef, 0x9f, 0x2f, 0x6f, 0x54, - 0x2b, 0xe9, 0x97, 0x51, 0x2b, 0x76, 0x36, 0x9e, 0x91, 0x1b, 0x34, 0x8b, 0x75, 0xae, 0x80, 0x29, - 0xc1, 0x5c, 0x7e, 0xe5, 0xf5, 0xfc, 0xfe, 0x6b, 0x64, 0xf6, 0x2b, 0xd8, 0xc0, 0x02, 0x72, 0xc7, - 0x15, 0xa9, 0x3b, 0x91, 0x80, 0x24, 0x69, 0x2e, 0xee, 0xbe, 0xb3, 0xba, 0x42, 0x89, 0x3f, 0xa9, - 0xf3, 0x0e, 0x7e, 0xce, 0xc3, 0xac, 0x47, 0x59, 0xb8, 0x2f, 0xd4, 0x68, 0x2b, 0xf0, 0x5e, 0xa3, - 0x4e, 0xba, 0x7d, 0x7d, 0x9a, 0xbb, 0x3d, 0x7d, 0xaa, 0x5e, 0xd5, 0xa7, 0x0b, 0x1d, 0x92, 0x5f, - 0xd6, 0x21, 0x0b, 0x89, 0xa1, 0x5d, 0x23, 0x31, 0x0a, 0xaf, 0x70, 0x97, 0xc3, 0xda, 0x24, 0xc6, - 0x33, 0x61, 0x5d, 0xbc, 0x49, 0x58, 0x97, 0x56, 0x08, 0xeb, 0xff, 0x5d, 0x16, 0xd6, 0xf6, 0xe1, - 0xd9, 0x53, 0x23, 0xf5, 0xe4, 0xa9, 0x91, 0xfa, 0x61, 0x66, 0x28, 0x67, 0x33, 0x43, 0x79, 0x3c, - 0x33, 0x94, 0xdf, 0x66, 0x86, 0xf2, 0xf5, 0xb9, 0x91, 0x7a, 0x7c, 0x6e, 0xa4, 0x9e, 0x9c, 0x1b, - 0xa9, 0x2f, 0x76, 0x96, 0x50, 0x72, 0x12, 0x8e, 0x03, 0xc2, 0x27, 0x34, 0x7c, 0x28, 0x9e, 0x77, - 0x5c, 0x1a, 0x92, 0xc6, 0x89, 0xfc, 0x30, 0x12, 0x80, 0xbb, 0xaa, 0xf8, 0x2c, 0x7a, 0xff, 0xaf, - 0x00, 0x00, 0x00, 0xff, 0xff, 0x8b, 0xed, 0x7b, 0x3d, 0x9f, 0x0d, 0x00, 0x00, + // 1163 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, + 0xab, 0x68, 0xa5, 0x4d, 0xd4, 0x22, 0x10, 0x84, 0x0f, 0x29, 0x2e, 0x8b, 0xe8, 0x8a, 0x4a, 0x95, + 0xab, 0x6a, 0x25, 0x2e, 0x61, 0x62, 0x4f, 0x52, 0x8b, 0xc4, 0x13, 0x79, 0xec, 0x7e, 0xfc, 0x0b, + 0x9c, 0x38, 0x71, 0xe1, 0x8e, 0x2a, 0x4e, 0x2b, 0xc1, 0xbf, 0x80, 0x54, 0x71, 0xda, 0x03, 0x87, + 0x45, 0x48, 0x81, 0x4d, 0x0f, 0x7b, 0xe0, 0x80, 0xd4, 0x23, 0x07, 0x40, 0x9e, 0x71, 0x52, 0xb7, + 0x4d, 0xe2, 0x2e, 0xb4, 0x2b, 0x21, 0x71, 0x71, 0xf2, 0xe6, 0xcd, 0xd8, 0xbf, 0xdf, 0xfb, 0xcd, + 0x3c, 0xbf, 0x67, 0xa8, 0x9a, 0x94, 0x75, 0x77, 0x31, 0xeb, 0x56, 0xf9, 0x65, 0x67, 0xb9, 0xda, + 0x73, 0x69, 0x8f, 0x32, 0xdc, 0xa9, 0xf4, 0x5c, 0xea, 0x51, 0xb9, 0x38, 0x9c, 0x50, 0xe1, 0x97, + 0x9d, 0xe5, 0xc5, 0xd9, 0x36, 0x6d, 0x53, 0xee, 0xac, 0x06, 0xff, 0xc4, 0xbc, 0xc5, 0x1b, 0xc1, + 0x3c, 0xca, 0x1a, 0xc2, 0x21, 0x8c, 0xd0, 0xa5, 0x08, 0xab, 0xda, 0xc4, 0x8c, 0x54, 0x77, 0x96, + 0x9b, 0xc4, 0xc3, 0xcb, 0x55, 0x93, 0xda, 0x4e, 0xe8, 0x5f, 0x3a, 0x87, 0xc1, 0xdb, 0xef, 0x91, + 0xe1, 0xea, 0x6b, 0xb8, 0x6b, 0x3b, 0xb4, 0xca, 0xaf, 0x62, 0x48, 0x3b, 0x48, 0xc2, 0x6b, 0x9b, + 0x1e, 0x75, 0xc9, 0x2a, 0xb5, 0xc8, 0x46, 0x88, 0x57, 0x9e, 0x85, 0x69, 0xcf, 0xf6, 0x3a, 0x04, + 0x81, 0x12, 0x28, 0xe7, 0x0c, 0x61, 0xc8, 0x25, 0x98, 0xb7, 0x08, 0x33, 0x5d, 0xbb, 0xe7, 0xd9, + 0xd4, 0x41, 0x33, 0xdc, 0x17, 0x1d, 0x92, 0xe7, 0xa0, 0xe4, 0xfa, 0x4e, 0x03, 0x33, 0x94, 0x14, + 0x0b, 0x5d, 0xdf, 0xa9, 0x33, 0xf9, 0x4d, 0xf8, 0x72, 0x00, 0xa7, 0xd1, 0xdc, 0xf7, 0x48, 0xc3, + 0xa4, 0x16, 0x41, 0xa9, 0x12, 0x28, 0x17, 0xf4, 0xe2, 0xa0, 0xaf, 0x16, 0x1e, 0xd6, 0x37, 0xd7, + 0xf5, 0x7d, 0x8f, 0x03, 0x30, 0x0a, 0xc1, 0xbc, 0xa1, 0x25, 0x6f, 0xc1, 0x79, 0xdb, 0x61, 0x1e, + 0x76, 0x3c, 0x1b, 0x7b, 0xa4, 0xd1, 0x23, 0x6e, 0xd7, 0x66, 0x2c, 0x78, 0x76, 0xa6, 0x04, 0xca, + 0xf9, 0x15, 0xa5, 0x72, 0x36, 0xa2, 0x95, 0xba, 0x69, 0x12, 0xc6, 0x56, 0xa9, 0xd3, 0xb2, 0xdb, + 0xc6, 0x5c, 0x64, 0xf5, 0xc6, 0x68, 0xb1, 0xfc, 0x2a, 0x84, 0xbe, 0xd3, 0xb3, 0x1d, 0x01, 0x25, + 0x5b, 0x02, 0xe5, 0xac, 0x91, 0xe3, 0x23, 0xfc, 0xa9, 0xf3, 0x50, 0x62, 0xd4, 0x77, 0x4d, 0x82, + 0x72, 0x9c, 0x44, 0x68, 0xc9, 0x08, 0x66, 0x9a, 0xbe, 0xdd, 0xb1, 0x88, 0x8b, 0x20, 0x77, 0x0c, + 0x4d, 0xf9, 0x26, 0xcc, 0x05, 0xb7, 0x6a, 0x6c, 0x63, 0xb6, 0x8d, 0xf2, 0x01, 0x35, 0x23, 0x1b, + 0x0c, 0x7c, 0x84, 0xd9, 0x76, 0xed, 0x9d, 0x1f, 0xbe, 0xbb, 0xb7, 0x18, 0x8a, 0xd8, 0xa6, 0x3b, + 0x95, 0x50, 0xb5, 0xca, 0x2a, 0x75, 0x3c, 0xe2, 0x78, 0x9f, 0x3f, 0x7b, 0x74, 0x77, 0x9e, 0x8b, + 0x75, 0x4e, 0x06, 0x04, 0x1e, 0xa4, 0xb2, 0xe9, 0xa2, 0xf4, 0x20, 0x95, 0x95, 0x8a, 0x19, 0xed, + 0xcb, 0x24, 0xbc, 0xb9, 0x76, 0x42, 0x28, 0x58, 0xef, 0x62, 0xd3, 0xbb, 0x2a, 0xd1, 0x66, 0x61, + 0x1a, 0x5b, 0x5d, 0xdb, 0xe1, 0x5a, 0xe5, 0x0c, 0x61, 0xc8, 0xb7, 0x60, 0x86, 0x53, 0xb5, 0x2d, + 0x94, 0x2e, 0x81, 0x72, 0x4a, 0x87, 0x83, 0xbe, 0x2a, 0x05, 0xa8, 0xd7, 0x3e, 0x30, 0xa4, 0xc0, + 0xb5, 0x66, 0x05, 0x4b, 0x3b, 0xb8, 0x49, 0x3a, 0x48, 0x12, 0x4b, 0xb9, 0x21, 0x97, 0x61, 0xb2, + 0xcb, 0xda, 0x5c, 0xba, 0x82, 0x3e, 0xff, 0x47, 0x5f, 0x95, 0x0d, 0xbc, 0x3b, 0x64, 0xb1, 0x4e, + 0x18, 0xc3, 0x6d, 0x62, 0x04, 0x53, 0xe4, 0x16, 0x4c, 0xb7, 0x7c, 0xc7, 0x62, 0x28, 0x5b, 0x4a, + 0x96, 0xf3, 0x2b, 0x37, 0x2a, 0x61, 0xf8, 0x82, 0x5d, 0x1f, 0x89, 0x9f, 0xed, 0xe8, 0x6f, 0x1c, + 0xf6, 0xd5, 0xc4, 0x37, 0xbf, 0xa8, 0xe5, 0xb6, 0xed, 0x6d, 0xfb, 0xcd, 0x8a, 0x49, 0xbb, 0xe1, + 0x81, 0x09, 0x7f, 0xee, 0x31, 0xeb, 0xb3, 0xf0, 0x0c, 0x04, 0x0b, 0xd8, 0xc1, 0xb3, 0x47, 0x77, + 0x81, 0x21, 0x6e, 0x5f, 0xbb, 0x1f, 0x2f, 0x4d, 0x89, 0x4b, 0x33, 0x25, 0xec, 0x08, 0x68, 0xdf, + 0x27, 0xe1, 0xd2, 0x98, 0x19, 0x2b, 0xff, 0x2b, 0xf3, 0x4f, 0x95, 0x91, 0x65, 0x98, 0x62, 0xb8, + 0xe3, 0xf1, 0x13, 0x58, 0x30, 0xf8, 0x7f, 0x79, 0x01, 0x66, 0x5a, 0xf6, 0x5e, 0x23, 0x40, 0x0a, + 0xf9, 0x99, 0x95, 0x5a, 0xf6, 0xde, 0x3a, 0x6b, 0xd7, 0x3e, 0x8c, 0x97, 0xf1, 0xb5, 0x49, 0x32, + 0xae, 0x44, 0x74, 0xfc, 0x0b, 0xc0, 0x85, 0x75, 0xbb, 0xed, 0x5e, 0xe6, 0xe1, 0x5a, 0x84, 0x59, + 0x33, 0xbc, 0x57, 0x28, 0xd7, 0xc8, 0xbe, 0x98, 0x62, 0xa1, 0x36, 0x52, 0xac, 0x36, 0xb5, 0x7a, + 0x7c, 0x18, 0x96, 0x78, 0x18, 0x26, 0x70, 0x44, 0x40, 0xfb, 0x11, 0xc0, 0xd9, 0x4d, 0xdf, 0xa2, + 0x57, 0x42, 0x3f, 0x79, 0x86, 0x7e, 0xc8, 0x2c, 0x15, 0xcf, 0xec, 0xfd, 0x78, 0x66, 0x37, 0x44, + 0x0a, 0x1d, 0x83, 0x1d, 0x01, 0xed, 0xa7, 0x19, 0xb8, 0x70, 0x7f, 0x8f, 0x98, 0xfe, 0xd5, 0x67, + 0xcd, 0x69, 0x7a, 0x87, 0x84, 0xd3, 0xcf, 0x71, 0xcc, 0xa4, 0xab, 0x4d, 0x80, 0x17, 0xde, 0x32, + 0x13, 0xa2, 0x87, 0x80, 0xf6, 0x33, 0x80, 0xd7, 0xb7, 0x7a, 0x16, 0xf6, 0x48, 0x3d, 0x48, 0x43, + 0xff, 0x3a, 0xae, 0xcb, 0x30, 0xe7, 0x90, 0xdd, 0x86, 0x48, 0x70, 0x3c, 0xb4, 0xfa, 0xec, 0x71, + 0x5f, 0x2d, 0xee, 0xe3, 0x6e, 0xa7, 0xa6, 0x8d, 0x5c, 0x9a, 0x91, 0x75, 0xc8, 0x2e, 0x7f, 0xe4, + 0xb4, 0x98, 0xd7, 0xde, 0x8b, 0x67, 0x88, 0x38, 0xc3, 0x31, 0x1c, 0x10, 0xd0, 0xbe, 0x06, 0x50, + 0x5e, 0xed, 0x10, 0xec, 0x5e, 0x0e, 0xb9, 0x29, 0xc7, 0xa1, 0xf6, 0x6e, 0x3c, 0xd2, 0x05, 0x8e, + 0xf4, 0x3c, 0x1e, 0x04, 0xb4, 0xdf, 0x00, 0x2c, 0x6e, 0x88, 0x02, 0x86, 0x8d, 0x60, 0xde, 0x39, + 0x05, 0x53, 0x2f, 0x1e, 0xf7, 0xd5, 0x82, 0x88, 0x23, 0x1f, 0xd6, 0x86, 0xc0, 0xdf, 0x1a, 0x03, + 0x5c, 0x9f, 0x3f, 0xee, 0xab, 0xb2, 0x98, 0x1d, 0x71, 0x6a, 0xa7, 0x09, 0xbd, 0x0d, 0xb3, 0x61, + 0x0a, 0x0b, 0xce, 0x41, 0xb2, 0x9c, 0xd2, 0x95, 0x41, 0x5f, 0xcd, 0x88, 0x1c, 0xc6, 0x8e, 0xfb, + 0xea, 0x2b, 0xe2, 0x0e, 0xc3, 0x49, 0x9a, 0x91, 0x11, 0x79, 0x8d, 0xd5, 0x6a, 0xf1, 0x7c, 0xe7, + 0x38, 0xdf, 0xb3, 0xb4, 0x10, 0xd0, 0x7e, 0x07, 0x50, 0xde, 0x1a, 0x16, 0x6c, 0xff, 0x11, 0xbe, + 0x17, 0xd6, 0xf7, 0x3c, 0x31, 0x04, 0xb4, 0xaf, 0x00, 0x94, 0xa3, 0xb5, 0xad, 0xd8, 0xae, 0xd1, + 0x57, 0x08, 0x98, 0xf8, 0x0a, 0xf9, 0x74, 0x62, 0x19, 0x3d, 0x73, 0x91, 0x32, 0x5a, 0xcf, 0x05, + 0x39, 0x46, 0xe4, 0x8d, 0xf1, 0x15, 0xb5, 0xf6, 0xed, 0x0c, 0x54, 0x05, 0xa2, 0xd3, 0xaf, 0xd8, + 0x96, 0xdd, 0x7e, 0x81, 0xe2, 0x98, 0x70, 0x0e, 0x73, 0xdc, 0x0d, 0x93, 0x3f, 0xba, 0xe1, 0x73, + 0x48, 0x42, 0xa9, 0xfc, 0xca, 0xed, 0xe9, 0x34, 0x05, 0xfe, 0x28, 0xd9, 0xeb, 0xf8, 0x9c, 0x9b, + 0xd5, 0xd6, 0xe2, 0x65, 0xbc, 0x1d, 0x49, 0x28, 0x13, 0xe3, 0x81, 0x80, 0xf6, 0x67, 0x0a, 0xde, + 0xe2, 0x45, 0x7f, 0xdd, 0xb1, 0x5e, 0x60, 0x61, 0x7f, 0xf9, 0xdd, 0x58, 0xfa, 0xf2, 0xba, 0x31, + 0xe9, 0x6c, 0x37, 0x36, 0x2a, 0x76, 0x33, 0xd1, 0x62, 0x77, 0x54, 0xc7, 0x66, 0xc7, 0xd4, 0xb1, + 0xb9, 0xe7, 0x78, 0xc1, 0xc2, 0xab, 0xad, 0x63, 0x4f, 0x7a, 0xc9, 0xfc, 0xa4, 0x5e, 0xb2, 0x30, + 0xa5, 0x97, 0x7c, 0xe9, 0x4c, 0x2f, 0xb9, 0x1e, 0xbf, 0xf9, 0xca, 0x27, 0xbd, 0xe4, 0xf4, 0x6d, + 0x85, 0x80, 0xfe, 0xf1, 0xe1, 0x53, 0x25, 0xf1, 0xe4, 0xa9, 0x92, 0x38, 0x18, 0x28, 0xe0, 0x70, + 0xa0, 0x80, 0xc7, 0x03, 0x05, 0xfc, 0x3a, 0x50, 0xc0, 0x17, 0x47, 0x4a, 0xe2, 0xf1, 0x91, 0x92, + 0x78, 0x72, 0xa4, 0x24, 0x3e, 0xb9, 0x13, 0x61, 0xbe, 0x4a, 0x59, 0xf7, 0xe1, 0xf0, 0xf3, 0x82, + 0x55, 0xdd, 0x13, 0x9f, 0x19, 0x38, 0xfb, 0xa6, 0xc4, 0xbf, 0x28, 0xbc, 0xfe, 0x77, 0x00, 0x00, + 0x00, 0xff, 0xff, 0x0f, 0x40, 0x90, 0x22, 0x08, 0x11, 0x00, 0x00, } func (this *StoreCodeProposal) Equal(that interface{}) bool { @@ -787,6 +920,7 @@ func (this *StoreCodeProposal) Equal(that interface{}) bool { } return true } + func (this *InstantiateContractProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -837,6 +971,7 @@ func (this *InstantiateContractProposal) Equal(that interface{}) bool { } return true } + func (this *InstantiateContract2Proposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -893,6 +1028,7 @@ func (this *InstantiateContract2Proposal) Equal(that interface{}) bool { } return true } + func (this *MigrateContractProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -929,6 +1065,7 @@ func (this *MigrateContractProposal) Equal(that interface{}) bool { } return true } + func (this *SudoContractProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -962,6 +1099,7 @@ func (this *SudoContractProposal) Equal(that interface{}) bool { } return true } + func (this *ExecuteContractProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1006,6 +1144,7 @@ func (this *ExecuteContractProposal) Equal(that interface{}) bool { } return true } + func (this *UpdateAdminProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1039,6 +1178,7 @@ func (this *UpdateAdminProposal) Equal(that interface{}) bool { } return true } + func (this *ClearAdminProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1069,6 +1209,7 @@ func (this *ClearAdminProposal) Equal(that interface{}) bool { } return true } + func (this *PinCodesProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1104,6 +1245,7 @@ func (this *PinCodesProposal) Equal(that interface{}) bool { } return true } + func (this *UnpinCodesProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1139,6 +1281,7 @@ func (this *UnpinCodesProposal) Equal(that interface{}) bool { } return true } + func (this *AccessConfigUpdate) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1166,6 +1309,7 @@ func (this *AccessConfigUpdate) Equal(that interface{}) bool { } return true } + func (this *UpdateInstantiateConfigProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1201,6 +1345,7 @@ func (this *UpdateInstantiateConfigProposal) Equal(that interface{}) bool { } return true } + func (this *StoreAndInstantiateContractProposal) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1266,6 +1411,7 @@ func (this *StoreAndInstantiateContractProposal) Equal(that interface{}) bool { } return true } + func (m *StoreCodeProposal) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -2158,6 +2304,7 @@ func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } + func (m *StoreCodeProposal) Size() (n int) { if m == nil { return 0 @@ -2577,9 +2724,11 @@ func (m *StoreAndInstantiateContractProposal) Size() (n int) { 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 @@ -2914,6 +3063,7 @@ func (m *StoreCodeProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *InstantiateContractProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3211,6 +3361,7 @@ func (m *InstantiateContractProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *InstantiateContract2Proposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3562,6 +3713,7 @@ func (m *InstantiateContract2Proposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *MigrateContractProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3761,6 +3913,7 @@ func (m *MigrateContractProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *SudoContractProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3941,6 +4094,7 @@ func (m *SudoContractProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *ExecuteContractProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4187,6 +4341,7 @@ func (m *ExecuteContractProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *UpdateAdminProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4365,6 +4520,7 @@ func (m *UpdateAdminProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *ClearAdminProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4511,6 +4667,7 @@ func (m *ClearAdminProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *PinCodesProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4701,6 +4858,7 @@ func (m *PinCodesProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *UnpinCodesProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4891,6 +5049,7 @@ func (m *UnpinCodesProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *AccessConfigUpdate) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4993,6 +5152,7 @@ func (m *AccessConfigUpdate) Unmarshal(dAtA []byte) error { } return nil } + func (m *UpdateInstantiateConfigProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -5141,6 +5301,7 @@ func (m *UpdateInstantiateConfigProposal) Unmarshal(dAtA []byte) error { } return nil } + func (m *StoreAndInstantiateContractProposal) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -5607,6 +5768,7 @@ func (m *StoreAndInstantiateContractProposal) Unmarshal(dAtA []byte) error { } return nil } + func skipProposal(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/wasm/types/proposal_test.go b/x/wasm/types/proposal_test.go index a558744..8952f8c 100644 --- a/x/wasm/types/proposal_test.go +++ b/x/wasm/types/proposal_test.go @@ -7,7 +7,7 @@ import ( "testing" sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/yaml.v2" @@ -48,7 +48,7 @@ func TestValidateProposalCommons(t *testing.T) { }, "prevent title exceeds max length ": { src: commonProposal{ - Title: strings.Repeat("a", govtypes.MaxTitleLength+1), + Title: strings.Repeat("a", v1beta1.MaxTitleLength+1), Description: "Bar", }, expErr: true, @@ -76,7 +76,7 @@ func TestValidateProposalCommons(t *testing.T) { "prevent descr exceeds max length ": { src: commonProposal{ Title: "Foo", - Description: strings.Repeat("a", govtypes.MaxDescriptionLength+1), + Description: strings.Repeat("a", v1beta1.MaxDescriptionLength+1), }, expErr: true, }, @@ -94,10 +94,7 @@ func TestValidateProposalCommons(t *testing.T) { } func TestValidateStoreCodeProposal(t *testing.T) { - var ( - anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, ContractAddrLen) - invalidAddress = "invalid address" - ) + var anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, ContractAddrLen) specs := map[string]struct { src *StoreCodeProposal @@ -187,8 +184,6 @@ func TestValidateStoreCodeProposal(t *testing.T) { } func TestValidateInstantiateContractProposal(t *testing.T) { - invalidAddress := "invalid address" - specs := map[string]struct { src *InstantiateContractProposal expErr bool @@ -280,8 +275,6 @@ func TestValidateInstantiateContractProposal(t *testing.T) { } func TestValidateInstantiateContract2Proposal(t *testing.T) { - invalidAddress := "invalid address" - specs := map[string]struct { src *InstantiateContract2Proposal expErr bool @@ -379,10 +372,7 @@ func TestValidateInstantiateContract2Proposal(t *testing.T) { } func TestValidateStoreAndInstantiateContractProposal(t *testing.T) { - var ( - anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, ContractAddrLen) - invalidAddress = "invalid address" - ) + var anyAddress sdk.AccAddress = bytes.Repeat([]byte{0x0}, ContractAddrLen) specs := map[string]struct { src *StoreAndInstantiateContractProposal @@ -577,8 +567,6 @@ func TestValidateMigrateContractProposal(t *testing.T) { } func TestValidateSudoContractProposal(t *testing.T) { - invalidAddress := "invalid address" - specs := map[string]struct { src *SudoContractProposal expErr bool @@ -630,8 +618,6 @@ func TestValidateSudoContractProposal(t *testing.T) { } func TestValidateExecuteContractProposal(t *testing.T) { - invalidAddress := "invalid address" - specs := map[string]struct { src *ExecuteContractProposal expErr bool @@ -689,8 +675,6 @@ func TestValidateExecuteContractProposal(t *testing.T) { } func TestValidateUpdateAdminProposal(t *testing.T) { - invalidAddress := "invalid address" - specs := map[string]struct { src *UpdateAdminProposal expErr bool @@ -742,8 +726,6 @@ func TestValidateUpdateAdminProposal(t *testing.T) { } func TestValidateClearAdminProposal(t *testing.T) { - invalidAddress := "invalid address" - specs := map[string]struct { src *ClearAdminProposal expErr bool @@ -784,7 +766,7 @@ func TestValidateClearAdminProposal(t *testing.T) { func TestProposalStrings(t *testing.T) { specs := map[string]struct { - src govtypes.Content + src v1beta1.Content exp string }{ "store code": { @@ -903,7 +885,7 @@ func TestProposalStrings(t *testing.T) { func TestProposalYaml(t *testing.T) { specs := map[string]struct { - src govtypes.Content + src v1beta1.Content exp string }{ "store code": { @@ -1051,8 +1033,8 @@ func TestConvertToProposals(t *testing.T) { func TestUnmarshalContentFromJson(t *testing.T) { specs := map[string]struct { src string - got govtypes.Content - exp govtypes.Content + got v1beta1.Content + exp v1beta1.Content }{ "instantiate ": { src: ` @@ -1109,7 +1091,7 @@ func TestUnmarshalContentFromJson(t *testing.T) { func TestProposalJsonSignBytes(t *testing.T) { const myInnerMsg = `{"foo":"bar"}` specs := map[string]struct { - src govtypes.Content + src v1beta1.Content exp string }{ "instantiate contract": { @@ -1131,11 +1113,11 @@ func TestProposalJsonSignBytes(t *testing.T) { } for name, spec := range specs { t.Run(name, func(t *testing.T) { - msg, err := govtypes.NewMsgSubmitProposal(spec.src, sdk.NewCoins(), []byte{}) + msg, err := v1beta1.NewMsgSubmitProposal(spec.src, sdk.NewCoins(), []byte{}) require.NoError(t, err) bz := msg.GetSignBytes() - assert.JSONEq(t, spec.exp, string(bz), "raw: %s", string(bz)) + 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 index 7deb0f8..653f1a9 100644 --- a/x/wasm/types/query.pb.go +++ b/x/wasm/types/query.pb.go @@ -7,24 +7,28 @@ 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/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" - github_com_tendermint_tendermint_libs_bytes "github.com/tendermint/tendermint/libs/bytes" + 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 +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. @@ -45,9 +49,11 @@ 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) @@ -60,12 +66,15 @@ func (m *QueryContractInfoRequest) XXX_Marshal(b []byte, deterministic bool) ([] 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) } @@ -86,9 +95,11 @@ 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) @@ -101,12 +112,15 @@ func (m *QueryContractInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([ 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) } @@ -128,9 +142,11 @@ 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) @@ -143,12 +159,15 @@ func (m *QueryContractHistoryRequest) XXX_Marshal(b []byte, deterministic bool) 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) } @@ -169,9 +188,11 @@ 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) @@ -184,12 +205,15 @@ func (m *QueryContractHistoryResponse) XXX_Marshal(b []byte, deterministic bool) 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) } @@ -210,9 +234,11 @@ 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) @@ -225,12 +251,15 @@ func (m *QueryContractsByCodeRequest) XXX_Marshal(b []byte, deterministic bool) 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) } @@ -252,9 +281,11 @@ 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) @@ -267,12 +298,15 @@ func (m *QueryContractsByCodeResponse) XXX_Marshal(b []byte, deterministic bool) 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) } @@ -294,9 +328,11 @@ 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) @@ -309,12 +345,15 @@ func (m *QueryAllContractStateRequest) XXX_Marshal(b []byte, deterministic bool) 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) } @@ -335,9 +374,11 @@ 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) @@ -350,12 +391,15 @@ func (m *QueryAllContractStateResponse) XXX_Marshal(b []byte, deterministic bool 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) } @@ -376,9 +420,11 @@ 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) @@ -391,12 +437,15 @@ func (m *QueryRawContractStateRequest) XXX_Marshal(b []byte, deterministic bool) 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) } @@ -416,9 +465,11 @@ 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) @@ -431,12 +482,15 @@ func (m *QueryRawContractStateResponse) XXX_Marshal(b []byte, deterministic bool 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) } @@ -458,9 +512,11 @@ 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) @@ -473,12 +529,15 @@ func (m *QuerySmartContractStateRequest) XXX_Marshal(b []byte, deterministic boo 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) } @@ -498,9 +557,11 @@ 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) @@ -513,12 +574,15 @@ func (m *QuerySmartContractStateResponse) XXX_Marshal(b []byte, deterministic bo 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) } @@ -536,9 +600,11 @@ 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) @@ -551,12 +617,15 @@ func (m *QueryCodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, er 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) } @@ -565,10 +634,10 @@ 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_tendermint_tendermint_libs_bytes.HexBytes `protobuf:"bytes,3,opt,name=data_hash,json=dataHash,proto3,casttype=github.com/tendermint/tendermint/libs/bytes.HexBytes" json:"data_hash,omitempty"` - InstantiatePermission AccessConfig `protobuf:"bytes,6,opt,name=instantiate_permission,json=instantiatePermission,proto3" json:"instantiate_permission"` + 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{} } @@ -577,9 +646,11 @@ 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) @@ -592,12 +663,15 @@ func (m *CodeInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, er 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) } @@ -616,9 +690,11 @@ 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) @@ -631,12 +707,15 @@ func (m *QueryCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, e 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) } @@ -655,9 +734,11 @@ 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) @@ -670,12 +751,15 @@ func (m *QueryCodesRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, e 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) } @@ -695,9 +779,11 @@ 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) @@ -710,12 +796,15 @@ func (m *QueryCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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) } @@ -735,9 +824,11 @@ 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) @@ -750,12 +841,15 @@ func (m *QueryPinnedCodesRequest) XXX_Marshal(b []byte, deterministic bool) ([]b 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) } @@ -776,9 +870,11 @@ 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) @@ -791,12 +887,15 @@ func (m *QueryPinnedCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([] 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) } @@ -804,8 +903,7 @@ func (m *QueryPinnedCodesResponse) XXX_DiscardUnknown() { var xxx_messageInfo_QueryPinnedCodesResponse proto.InternalMessageInfo // 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) } @@ -813,9 +911,11 @@ 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) @@ -828,12 +928,15 @@ 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) } @@ -852,9 +955,11 @@ 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) @@ -867,12 +972,15 @@ 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) } @@ -894,9 +1002,11 @@ 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) @@ -909,12 +1019,15 @@ func (m *QueryContractsByCreatorRequest) XXX_Marshal(b []byte, deterministic boo 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) } @@ -936,9 +1049,11 @@ 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) @@ -951,12 +1066,15 @@ func (m *QueryContractsByCreatorResponse) XXX_Marshal(b []byte, deterministic bo 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) } @@ -992,91 +1110,92 @@ func init() { func init() { proto.RegisterFile("cosmwasm/wasm/v1/query.proto", fileDescriptor_9677c207036b9f2b) } var fileDescriptor_9677c207036b9f2b = []byte{ - // 1336 bytes of a gzipped FileDescriptorProto + // 1346 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x98, 0xcf, 0x6f, 0x1b, 0x45, - 0x14, 0xc7, 0x3d, 0xa9, 0xe3, 0x1f, 0xd3, 0x94, 0xba, 0x43, 0x69, 0x8d, 0x49, 0xd7, 0xd1, 0x52, - 0xda, 0x34, 0x4d, 0x76, 0x49, 0x9a, 0x50, 0x40, 0x42, 0x28, 0x4e, 0xa1, 0x49, 0xa4, 0x88, 0x74, - 0x2b, 0x84, 0x44, 0x0f, 0xd6, 0xd8, 0x3b, 0x71, 0x56, 0xc4, 0x3b, 0xce, 0xce, 0x24, 0xa9, 0x15, - 0x05, 0x50, 0x25, 0x6e, 0x88, 0x1f, 0x42, 0x1c, 0x38, 0x20, 0x38, 0xa0, 0xc2, 0x19, 0x2e, 0x88, - 0x2b, 0x97, 0x1c, 0x23, 0x71, 0xe1, 0x64, 0x81, 0xc3, 0x01, 0xe5, 0x4f, 0xe8, 0x09, 0xed, 0xec, - 0xac, 0xb3, 0x6b, 0x7b, 0x63, 0xa7, 0xb2, 0xb8, 0x58, 0xbb, 0x3b, 0x6f, 0xe6, 0x7d, 0xde, 0x77, - 0xde, 0xcc, 0x7b, 0x32, 0x1c, 0x2d, 0x53, 0x56, 0xdd, 0xc1, 0xac, 0xaa, 0x8b, 0x9f, 0xed, 0x69, - 0x7d, 0x73, 0x8b, 0x38, 0x75, 0xad, 0xe6, 0x50, 0x4e, 0x51, 0xc6, 0x1f, 0xd5, 0xc4, 0xcf, 0xf6, - 0x74, 0xee, 0x62, 0x85, 0x56, 0xa8, 0x18, 0xd4, 0xdd, 0x27, 0xcf, 0x2e, 0xd7, 0xb9, 0x0a, 0xaf, - 0xd7, 0x08, 0xf3, 0x47, 0x2b, 0x94, 0x56, 0x36, 0x88, 0x8e, 0x6b, 0x96, 0x8e, 0x6d, 0x9b, 0x72, - 0xcc, 0x2d, 0x6a, 0xfb, 0xa3, 0x13, 0xee, 0x5c, 0xca, 0xf4, 0x12, 0x66, 0xc4, 0x73, 0xae, 0x6f, - 0x4f, 0x97, 0x08, 0xc7, 0xd3, 0x7a, 0x0d, 0x57, 0x2c, 0x5b, 0x18, 0x7b, 0xb6, 0xea, 0x2c, 0xcc, - 0xde, 0x73, 0x2d, 0x16, 0xa8, 0xcd, 0x1d, 0x5c, 0xe6, 0x4b, 0xf6, 0x1a, 0x35, 0xc8, 0xe6, 0x16, - 0x61, 0x1c, 0x65, 0x61, 0x12, 0x9b, 0xa6, 0x43, 0x18, 0xcb, 0x82, 0x31, 0x30, 0x9e, 0x36, 0xfc, - 0x57, 0xf5, 0x33, 0x00, 0x9f, 0xef, 0x32, 0x8d, 0xd5, 0xa8, 0xcd, 0x48, 0xf4, 0x3c, 0x74, 0x0f, - 0x9e, 0x2b, 0xcb, 0x19, 0x45, 0xcb, 0x5e, 0xa3, 0xd9, 0xa1, 0x31, 0x30, 0x7e, 0x76, 0x46, 0xd1, - 0xda, 0x55, 0xd1, 0x82, 0x0b, 0x17, 0x46, 0xf6, 0x1b, 0xf9, 0xd8, 0x41, 0x23, 0x0f, 0x8e, 0x1a, - 0xf9, 0x98, 0x31, 0x52, 0x0e, 0x8c, 0xbd, 0x1e, 0xff, 0xf7, 0xfb, 0x3c, 0x50, 0x3f, 0x82, 0x2f, - 0x84, 0x78, 0x16, 0x2d, 0xc6, 0xa9, 0x53, 0xef, 0x19, 0x09, 0x7a, 0x1b, 0xc2, 0x63, 0x4d, 0x24, - 0xce, 0x35, 0xcd, 0x13, 0x50, 0x73, 0x05, 0xd4, 0xbc, 0xdd, 0x93, 0x02, 0x6a, 0xab, 0xb8, 0x42, - 0xe4, 0xaa, 0x46, 0x60, 0xa6, 0xfa, 0x0b, 0x80, 0xa3, 0xdd, 0x09, 0xa4, 0x28, 0xcb, 0x30, 0x49, - 0x6c, 0xee, 0x58, 0xc4, 0x45, 0x38, 0x33, 0x7e, 0x76, 0x66, 0x22, 0x3a, 0xe8, 0x05, 0x6a, 0x12, - 0x39, 0xff, 0x2d, 0x9b, 0x3b, 0xf5, 0x42, 0xdc, 0x15, 0xc0, 0xf0, 0x17, 0x40, 0x77, 0xbb, 0x40, - 0x5f, 0xef, 0x09, 0xed, 0x81, 0x84, 0xa8, 0x3f, 0x6c, 0x93, 0x8d, 0x15, 0xea, 0xae, 0x6f, 0x5f, - 0xb6, 0xcb, 0x30, 0x59, 0xa6, 0x26, 0x29, 0x5a, 0xa6, 0x90, 0x2d, 0x6e, 0x24, 0xdc, 0xd7, 0x25, - 0x73, 0x60, 0xaa, 0x7d, 0xd2, 0xae, 0x5a, 0x0b, 0x40, 0xaa, 0x36, 0x0a, 0xd3, 0xfe, 0x6e, 0x7b, - 0xba, 0xa5, 0x8d, 0xe3, 0x0f, 0x83, 0xd3, 0xe1, 0x63, 0x9f, 0x63, 0x7e, 0x63, 0xc3, 0x47, 0xb9, - 0xcf, 0x31, 0x27, 0xff, 0x5f, 0x02, 0x7d, 0x07, 0xe0, 0x95, 0x08, 0x04, 0xa9, 0xc5, 0x1c, 0x4c, - 0x54, 0xa9, 0x49, 0x36, 0xfc, 0x04, 0xba, 0xdc, 0x99, 0x40, 0x2b, 0xee, 0xb8, 0xcc, 0x16, 0x69, - 0x3c, 0x38, 0x91, 0xde, 0x93, 0x1a, 0x19, 0x78, 0xe7, 0x94, 0x1a, 0x5d, 0x81, 0x50, 0xf8, 0x28, - 0x9a, 0x98, 0x63, 0x81, 0x30, 0x62, 0xa4, 0xc5, 0x97, 0x3b, 0x98, 0x63, 0xf5, 0x96, 0x8c, 0xbc, - 0x73, 0x61, 0x19, 0x39, 0x82, 0x71, 0x31, 0x13, 0x88, 0x99, 0xe2, 0x59, 0xdd, 0x84, 0x8a, 0x98, - 0x74, 0xbf, 0x8a, 0x1d, 0x7e, 0x4a, 0x9e, 0xb9, 0x4e, 0x9e, 0xc2, 0xa5, 0x27, 0x8d, 0x3c, 0x0a, - 0x10, 0xac, 0x10, 0xc6, 0x5c, 0x25, 0x02, 0x9c, 0x2b, 0x30, 0x1f, 0xe9, 0x52, 0x92, 0x4e, 0x04, - 0x49, 0x23, 0xd7, 0xf4, 0x22, 0xb8, 0x09, 0x33, 0x32, 0xf7, 0x7b, 0x9f, 0x38, 0xf5, 0xdb, 0x21, - 0x98, 0x71, 0x0d, 0x43, 0x17, 0xed, 0x8d, 0x36, 0xeb, 0x42, 0xa6, 0xd9, 0xc8, 0x27, 0x84, 0xd9, - 0x9d, 0xa3, 0x46, 0x7e, 0xc8, 0x32, 0x5b, 0x27, 0x36, 0x0b, 0x93, 0x65, 0x87, 0x60, 0x4e, 0x1d, - 0x11, 0x6f, 0xda, 0xf0, 0x5f, 0xd1, 0xbb, 0x30, 0xed, 0xe2, 0x14, 0xd7, 0x31, 0x5b, 0xcf, 0x9e, - 0x11, 0xdc, 0xaf, 0x3e, 0x69, 0xe4, 0x67, 0x2b, 0x16, 0x5f, 0xdf, 0x2a, 0x69, 0x65, 0x5a, 0xd5, - 0x39, 0xb1, 0x4d, 0xe2, 0x54, 0x2d, 0x9b, 0x07, 0x1f, 0x37, 0xac, 0x12, 0xd3, 0x4b, 0x75, 0x4e, - 0x98, 0xb6, 0x48, 0x1e, 0x16, 0xdc, 0x07, 0x23, 0xe5, 0x2e, 0xb5, 0x88, 0xd9, 0x3a, 0x7a, 0x00, - 0x2f, 0x59, 0x36, 0xe3, 0xd8, 0xe6, 0x16, 0xe6, 0xa4, 0x58, 0x73, 0x27, 0x31, 0xe6, 0xa6, 0x60, - 0x22, 0xea, 0xce, 0x9f, 0x2f, 0x97, 0x09, 0x63, 0x0b, 0xd4, 0x5e, 0xb3, 0x2a, 0x32, 0x89, 0x9f, - 0x0b, 0xac, 0xb1, 0xda, 0x5a, 0xc2, 0xbb, 0xf4, 0x97, 0xe3, 0xa9, 0x78, 0x66, 0x78, 0x39, 0x9e, - 0x1a, 0xce, 0x24, 0xd4, 0x47, 0x00, 0x5e, 0x08, 0xa8, 0x29, 0x05, 0x5a, 0x72, 0xaf, 0x0f, 0x57, - 0x20, 0xb7, 0xd6, 0x00, 0xe1, 0x57, 0xed, 0x76, 0xed, 0x86, 0x75, 0x2d, 0xa4, 0x5a, 0xb5, 0x26, - 0x55, 0x96, 0x63, 0x68, 0x54, 0xee, 0xac, 0x97, 0x2d, 0xa9, 0xa3, 0x46, 0x5e, 0xbc, 0x7b, 0x7b, - 0x29, 0xab, 0xd0, 0x83, 0x00, 0x03, 0xf3, 0xb7, 0x34, 0x7c, 0x41, 0x80, 0xa7, 0xbe, 0x20, 0x1e, - 0x03, 0x88, 0x82, 0xab, 0xcb, 0x10, 0xef, 0x42, 0xd8, 0x0a, 0xd1, 0xbf, 0x19, 0xfa, 0x89, 0xd1, - 0xd3, 0x37, 0xed, 0xc7, 0x37, 0xc0, 0x7b, 0x02, 0xc3, 0xcb, 0x82, 0x73, 0xd5, 0xb2, 0x6d, 0x62, - 0x9e, 0xa0, 0xc5, 0xd3, 0x5f, 0x96, 0x9f, 0x03, 0xd9, 0xb6, 0x84, 0x7c, 0xb4, 0xce, 0x60, 0x4a, - 0x9e, 0x0a, 0x4f, 0x8f, 0x78, 0xe1, 0xbc, 0x1b, 0x6b, 0xb3, 0x91, 0x4f, 0x7a, 0x47, 0x83, 0x19, - 0x49, 0xef, 0x54, 0x0c, 0x30, 0xe8, 0x8b, 0x72, 0x73, 0x56, 0xb1, 0x83, 0xab, 0x7e, 0xbc, 0xea, - 0x0a, 0x7c, 0x36, 0xf4, 0x55, 0x12, 0xbe, 0x02, 0x13, 0x35, 0xf1, 0x45, 0xa6, 0x43, 0xb6, 0x73, - 0xbf, 0xbc, 0x19, 0xfe, 0x55, 0xee, 0x59, 0xab, 0x5f, 0x02, 0x79, 0xe9, 0x05, 0xcb, 0xa5, 0x77, - 0x8c, 0x7d, 0x85, 0xaf, 0xc3, 0xf3, 0xf2, 0x60, 0x17, 0xc3, 0x97, 0xdf, 0x33, 0xf2, 0xf3, 0xfc, - 0x80, 0xeb, 0xd6, 0x37, 0x40, 0xde, 0x8a, 0xdd, 0x98, 0x64, 0xbc, 0x53, 0x10, 0xb5, 0xda, 0x3e, - 0x49, 0x45, 0xfc, 0x72, 0x7e, 0xc1, 0x1f, 0x99, 0xf7, 0x07, 0x06, 0xb6, 0x29, 0x33, 0xbf, 0x9f, - 0x83, 0xc3, 0x82, 0x0d, 0x7d, 0x0d, 0xe0, 0x48, 0xb0, 0xa5, 0x44, 0x5d, 0xba, 0xaf, 0xa8, 0x3e, - 0x38, 0x77, 0xb3, 0x2f, 0x5b, 0xcf, 0xbf, 0x3a, 0xf9, 0xe8, 0x8f, 0x7f, 0xbe, 0x1a, 0xba, 0x86, - 0xae, 0xea, 0x1d, 0x1d, 0xbc, 0x1f, 0xa9, 0xbe, 0x2b, 0x45, 0xd8, 0x43, 0x8f, 0x01, 0x3c, 0xdf, - 0xd6, 0x31, 0xa2, 0xa9, 0x1e, 0xee, 0xc2, 0xbd, 0x6d, 0x4e, 0xeb, 0xd7, 0x5c, 0x02, 0xce, 0x0a, - 0x40, 0x0d, 0x4d, 0xf6, 0x03, 0xa8, 0xaf, 0x4b, 0xa8, 0x1f, 0x02, 0xa0, 0xb2, 0x49, 0xeb, 0x09, - 0x1a, 0xee, 0x26, 0x7b, 0x82, 0xb6, 0xf5, 0x7e, 0xea, 0x8c, 0x00, 0x9d, 0x44, 0x13, 0xdd, 0x40, - 0x4d, 0xa2, 0xef, 0xca, 0x53, 0xbe, 0xa7, 0x1f, 0x77, 0x84, 0x3f, 0x02, 0x98, 0x69, 0x6f, 0xa0, - 0x50, 0x94, 0xe3, 0x88, 0x66, 0x2f, 0xa7, 0xf7, 0x6d, 0xdf, 0x0f, 0x69, 0x87, 0xa4, 0x4c, 0x40, - 0xfd, 0x0c, 0x60, 0xa6, 0xbd, 0xe1, 0x89, 0x24, 0x8d, 0x68, 0xb9, 0x22, 0x49, 0xa3, 0x3a, 0x29, - 0xf5, 0x0d, 0x41, 0x7a, 0x1b, 0xcd, 0xf5, 0x45, 0xea, 0xe0, 0x1d, 0x7d, 0xf7, 0xb8, 0x53, 0xda, - 0x43, 0xbf, 0x01, 0x88, 0x3a, 0xbb, 0x1f, 0xf4, 0x72, 0x04, 0x46, 0x64, 0x6f, 0x96, 0x9b, 0x3e, - 0xc5, 0x0c, 0x89, 0xfe, 0xa6, 0x40, 0x7f, 0x0d, 0xdd, 0xee, 0x4f, 0x64, 0x77, 0xa1, 0x30, 0x7c, - 0x1d, 0xc6, 0x45, 0xda, 0xaa, 0x91, 0x79, 0x78, 0x9c, 0xab, 0x2f, 0x9e, 0x68, 0x23, 0x89, 0xc6, - 0x05, 0x91, 0x8a, 0xc6, 0x7a, 0x25, 0x28, 0x72, 0xe0, 0xb0, 0xa8, 0x51, 0xe8, 0xa4, 0x75, 0xfd, - 0xaa, 0x91, 0xbb, 0x7a, 0xb2, 0x91, 0xf4, 0xae, 0x08, 0xef, 0x59, 0x74, 0xa9, 0xbb, 0x77, 0xf4, - 0x29, 0x80, 0x67, 0x03, 0xe5, 0x11, 0xdd, 0x88, 0x58, 0xb5, 0xb3, 0x4c, 0xe7, 0x26, 0xfa, 0x31, - 0x95, 0x18, 0xd7, 0x04, 0xc6, 0x18, 0x52, 0xba, 0x63, 0x30, 0xbd, 0x26, 0x26, 0xa1, 0x3d, 0x98, - 0xf0, 0x6a, 0x1a, 0x8a, 0x0a, 0x2f, 0x54, 0x3a, 0x73, 0x2f, 0xf5, 0xb0, 0xea, 0xdb, 0xbd, 0xe7, - 0xf4, 0x57, 0x00, 0x51, 0x67, 0x85, 0x8a, 0xcc, 0xdc, 0xc8, 0x02, 0x1b, 0x99, 0xb9, 0xd1, 0xe5, - 0xaf, 0x9f, 0x43, 0xc7, 0x74, 0x59, 0x9e, 0xf5, 0xdd, 0xb6, 0xf2, 0xbd, 0x57, 0x78, 0x67, 0xff, - 0x6f, 0x25, 0xf6, 0x53, 0x53, 0x89, 0xed, 0x37, 0x15, 0x70, 0xd0, 0x54, 0xc0, 0x5f, 0x4d, 0x05, - 0x7c, 0x71, 0xa8, 0xc4, 0x0e, 0x0e, 0x95, 0xd8, 0x9f, 0x87, 0x4a, 0xec, 0xfd, 0xa9, 0x50, 0xaf, - 0xee, 0xd4, 0x6c, 0xc2, 0x77, 0xa8, 0xf3, 0x81, 0x78, 0x9e, 0x2a, 0x53, 0x87, 0xe8, 0x0f, 0x3d, - 0x8f, 0xe2, 0x3f, 0xa4, 0x52, 0x42, 0xfc, 0xf5, 0x73, 0xeb, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, - 0x2b, 0xcd, 0x90, 0xa7, 0xaa, 0x12, 0x00, 0x00, + 0x14, 0xc7, 0x3d, 0xa9, 0xe3, 0x1f, 0x93, 0x96, 0x3a, 0x43, 0x69, 0x8d, 0x49, 0xd7, 0xd1, 0x52, + 0xd2, 0xd4, 0x6d, 0x77, 0x9b, 0xb4, 0x55, 0x45, 0x11, 0x42, 0x71, 0x0a, 0xa4, 0x15, 0x15, 0xe9, + 0x56, 0xa2, 0x12, 0x1c, 0xcc, 0xd8, 0x3b, 0x71, 0x56, 0x8a, 0x77, 0xdc, 0x9d, 0x49, 0x52, 0x2b, + 0x0a, 0xa0, 0x4a, 0x9c, 0xe0, 0x00, 0xaa, 0x38, 0x70, 0x41, 0x1c, 0x2a, 0xa8, 0xc4, 0x05, 0x71, + 0xaa, 0xb8, 0x72, 0xc9, 0x31, 0x12, 0x17, 0x4e, 0x16, 0x38, 0x48, 0xa0, 0xfc, 0x09, 0x3d, 0xa1, + 0x9d, 0x9d, 0xb5, 0x77, 0x6d, 0x6f, 0xec, 0x54, 0x16, 0x17, 0x6b, 0x77, 0x67, 0xde, 0xbc, 0xcf, + 0xfb, 0xce, 0xcc, 0x7b, 0x4f, 0x86, 0x53, 0x15, 0xca, 0x6a, 0x9b, 0x98, 0xd5, 0x74, 0xf1, 0xb3, + 0x31, 0xa7, 0xdf, 0x5f, 0x27, 0x4e, 0x43, 0xab, 0x3b, 0x94, 0x53, 0x94, 0xf1, 0x47, 0x35, 0xf1, + 0xb3, 0x31, 0x97, 0x3b, 0x51, 0xa5, 0x55, 0x2a, 0x06, 0x75, 0xf7, 0xc9, 0x9b, 0x97, 0xeb, 0x5d, + 0x85, 0x37, 0xea, 0x84, 0xf9, 0xa3, 0x55, 0x4a, 0xab, 0x6b, 0x44, 0xc7, 0x75, 0x4b, 0xc7, 0xb6, + 0x4d, 0x39, 0xe6, 0x16, 0xb5, 0xfd, 0xd1, 0x82, 0x6b, 0x4b, 0x99, 0x5e, 0xc6, 0x8c, 0x78, 0xce, + 0xf5, 0x8d, 0xb9, 0x32, 0xe1, 0x78, 0x4e, 0xaf, 0xe3, 0xaa, 0x65, 0x8b, 0xc9, 0x72, 0xee, 0x24, + 0xae, 0x59, 0x36, 0xd5, 0xc5, 0xaf, 0xf7, 0x49, 0xbd, 0x02, 0xb3, 0x77, 0x5c, 0xa3, 0x45, 0x6a, + 0x73, 0x07, 0x57, 0xf8, 0x4d, 0x7b, 0x85, 0x1a, 0xe4, 0xfe, 0x3a, 0x61, 0x1c, 0x65, 0x61, 0x12, + 0x9b, 0xa6, 0x43, 0x18, 0xcb, 0x82, 0x69, 0x30, 0x9b, 0x36, 0xfc, 0x57, 0xf5, 0x11, 0x80, 0x2f, + 0xf7, 0x31, 0x63, 0x75, 0x6a, 0x33, 0x12, 0x6d, 0x87, 0x3e, 0x80, 0xc7, 0x2a, 0xd2, 0xa2, 0x64, + 0xd9, 0x2b, 0x34, 0x3b, 0x36, 0x0d, 0x66, 0x27, 0xe6, 0x15, 0xad, 0x5b, 0x28, 0x2d, 0xb8, 0x70, + 0x71, 0x72, 0xa7, 0x99, 0x8f, 0xed, 0x36, 0xf3, 0x60, 0xbf, 0x99, 0x8f, 0x3d, 0xf9, 0xe7, 0xe7, + 0x02, 0x30, 0x8e, 0x56, 0x02, 0x13, 0xae, 0xc7, 0xff, 0xfd, 0x3e, 0x0f, 0xd4, 0x4f, 0xe1, 0x2b, + 0x21, 0xa8, 0x25, 0x8b, 0x71, 0xea, 0x34, 0x06, 0x86, 0x83, 0xde, 0x81, 0xb0, 0xa3, 0x95, 0x64, + 0x9a, 0xd1, 0x3c, 0x61, 0x35, 0x57, 0x58, 0xcd, 0xdb, 0x55, 0x29, 0xac, 0xb6, 0x8c, 0xab, 0x44, + 0xae, 0x6a, 0x04, 0x2c, 0xd5, 0xa7, 0x00, 0x4e, 0xf5, 0x27, 0x90, 0xca, 0xbc, 0x0f, 0x93, 0xc4, + 0xe6, 0x8e, 0x45, 0x5c, 0x84, 0x23, 0xb3, 0x13, 0xf3, 0x85, 0xe8, 0xc8, 0x17, 0xa9, 0x49, 0xa4, + 0xfd, 0xdb, 0x36, 0x77, 0x1a, 0xc5, 0xf4, 0x4e, 0x3b, 0x7a, 0x7f, 0x15, 0xf4, 0x6e, 0x1f, 0xf2, + 0xb3, 0x03, 0xc9, 0x3d, 0x9a, 0x10, 0xfa, 0x27, 0x5d, 0xda, 0xb1, 0x62, 0xc3, 0x05, 0xf0, 0xb5, + 0x3b, 0x05, 0x93, 0x15, 0x6a, 0x92, 0x92, 0x65, 0x0a, 0xed, 0xe2, 0x46, 0xc2, 0x7d, 0xbd, 0x69, + 0x8e, 0x4c, 0xba, 0xcf, 0xbb, 0xa5, 0x6b, 0x03, 0x48, 0xe9, 0xa6, 0x60, 0xda, 0xdf, 0x72, 0x4f, + 0xbc, 0xb4, 0xd1, 0xf9, 0x30, 0x3a, 0x1d, 0x3e, 0xf3, 0x39, 0x16, 0xd6, 0xd6, 0x7c, 0x94, 0xbb, + 0x1c, 0x73, 0xf2, 0xff, 0x9d, 0xa2, 0xc7, 0x00, 0x9e, 0x8e, 0x40, 0x90, 0x5a, 0x5c, 0x87, 0x89, + 0x1a, 0x35, 0xc9, 0x9a, 0x7f, 0x8a, 0x4e, 0xf5, 0x9e, 0xa2, 0xdb, 0xee, 0x78, 0xf0, 0xc8, 0x48, + 0x8b, 0xd1, 0x29, 0x75, 0x4f, 0x0a, 0x65, 0xe0, 0xcd, 0x43, 0x0a, 0x75, 0x1a, 0x42, 0xe1, 0xa3, + 0x64, 0x62, 0x8e, 0x05, 0xc2, 0x51, 0x23, 0x2d, 0xbe, 0xdc, 0xc0, 0x1c, 0xab, 0x97, 0x65, 0xf8, + 0xbd, 0x0b, 0xcb, 0xf0, 0x11, 0x8c, 0x0b, 0x4b, 0x20, 0x2c, 0xc5, 0xb3, 0x7a, 0x1f, 0x2a, 0xc2, + 0xe8, 0x6e, 0x0d, 0x3b, 0xfc, 0x90, 0x3c, 0x57, 0x7b, 0x79, 0x8a, 0x27, 0x9f, 0x35, 0xf3, 0x28, + 0x40, 0x70, 0x9b, 0x30, 0xe6, 0x2a, 0x11, 0xe0, 0xbc, 0x0d, 0xf3, 0x91, 0x2e, 0x25, 0x69, 0x21, + 0x48, 0x1a, 0xb9, 0xa6, 0x17, 0xc1, 0x79, 0x98, 0x91, 0x17, 0x60, 0xf0, 0xb5, 0x53, 0xbf, 0x1b, + 0x83, 0x19, 0x77, 0x62, 0x28, 0xef, 0x9e, 0xeb, 0x9a, 0x5d, 0xcc, 0xb4, 0x9a, 0xf9, 0x84, 0x98, + 0x76, 0x63, 0xbf, 0x99, 0x1f, 0xb3, 0xcc, 0xf6, 0xb5, 0xcd, 0xc2, 0x64, 0xc5, 0x21, 0x98, 0x53, + 0x47, 0xc4, 0x9b, 0x36, 0xfc, 0x57, 0x74, 0x07, 0xa6, 0x5d, 0x9c, 0xd2, 0x2a, 0x66, 0xab, 0xd9, + 0x23, 0x82, 0xfb, 0xca, 0xb3, 0x66, 0xfe, 0x52, 0xd5, 0xe2, 0xab, 0xeb, 0x65, 0xad, 0x42, 0x6b, + 0x7a, 0x85, 0xd6, 0x08, 0x2f, 0xaf, 0xf0, 0xce, 0xc3, 0x9a, 0x55, 0x66, 0x7a, 0xb9, 0xc1, 0x09, + 0xd3, 0x96, 0xc8, 0x83, 0xa2, 0xfb, 0x60, 0xa4, 0xdc, 0x65, 0x96, 0x30, 0x5b, 0x45, 0x1f, 0xc3, + 0x93, 0x96, 0xcd, 0x38, 0xb6, 0xb9, 0x85, 0x39, 0x29, 0xd5, 0x89, 0x53, 0xb3, 0x18, 0x73, 0x8f, + 0x5f, 0x22, 0x2a, 0xfd, 0x2f, 0x54, 0x2a, 0x84, 0xb1, 0x45, 0x6a, 0xaf, 0x58, 0xd5, 0xe0, 0x29, + 0x7e, 0x29, 0xb0, 0xd0, 0x72, 0x7b, 0x1d, 0x2f, 0xff, 0xdf, 0x8a, 0xa7, 0xe2, 0x99, 0xf1, 0x5b, + 0xf1, 0xd4, 0x78, 0x26, 0xa1, 0x3e, 0x04, 0x70, 0x32, 0x20, 0xa7, 0x54, 0xe8, 0xa6, 0x9b, 0x44, + 0x5c, 0x85, 0xdc, 0xda, 0x03, 0x84, 0x73, 0xb5, 0x5f, 0x06, 0x0e, 0x0b, 0x5b, 0x4c, 0xf9, 0xb5, + 0xc7, 0x48, 0x55, 0xe4, 0x18, 0x9a, 0x92, 0x5b, 0xeb, 0x1d, 0x97, 0xd4, 0x7e, 0x33, 0x2f, 0xde, + 0xbd, 0xcd, 0x94, 0x05, 0xe9, 0xa3, 0x00, 0x03, 0xf3, 0xf7, 0x34, 0x9c, 0x26, 0xc0, 0x73, 0xa7, + 0x89, 0x9f, 0x00, 0x44, 0xc1, 0xd5, 0x65, 0x88, 0xef, 0x41, 0xd8, 0x0e, 0xd1, 0xcf, 0x0f, 0xc3, + 0xc4, 0x18, 0x10, 0x39, 0xed, 0x07, 0x39, 0xc2, 0x6c, 0x81, 0xe1, 0x29, 0x01, 0xbb, 0x6c, 0xd9, + 0x36, 0x31, 0x0f, 0x10, 0xe4, 0xf9, 0xf3, 0xe6, 0x17, 0x40, 0xf6, 0x32, 0x21, 0x1f, 0x52, 0x96, + 0x19, 0x98, 0x92, 0x77, 0xc3, 0x13, 0x25, 0x5e, 0x9c, 0x68, 0x35, 0xf3, 0x49, 0xef, 0x72, 0x30, + 0x23, 0xe9, 0xdd, 0x8b, 0x11, 0x06, 0x7c, 0x42, 0xee, 0xce, 0x32, 0x76, 0x70, 0xcd, 0x8f, 0x55, + 0x35, 0xe0, 0x8b, 0xa1, 0xaf, 0x92, 0xee, 0x0d, 0x98, 0xa8, 0x8b, 0x2f, 0xf2, 0x3c, 0x64, 0x7b, + 0x37, 0xcc, 0xb3, 0x08, 0x65, 0x74, 0xcf, 0x44, 0xfd, 0x1a, 0xc8, 0xdc, 0x17, 0x2c, 0x9d, 0xde, + 0x6d, 0xf6, 0x25, 0x3e, 0x0b, 0x8f, 0xcb, 0xfb, 0x5d, 0x0a, 0xe7, 0xc0, 0x17, 0xe4, 0xe7, 0x85, + 0x11, 0xd7, 0xb0, 0x6f, 0x81, 0x4c, 0x8e, 0xfd, 0x98, 0x64, 0xd0, 0x17, 0x21, 0x6a, 0x37, 0x83, + 0x92, 0x8a, 0xf8, 0xa5, 0x7d, 0xd2, 0x1f, 0x59, 0xf0, 0x07, 0x46, 0xb6, 0x33, 0xf3, 0xbf, 0x1d, + 0x83, 0xe3, 0x82, 0x0d, 0x7d, 0x03, 0xe0, 0xd1, 0x60, 0xa3, 0x89, 0xfa, 0xb4, 0x63, 0x51, 0xdd, + 0x71, 0xee, 0xfc, 0x50, 0x73, 0x3d, 0xff, 0xea, 0x85, 0x87, 0xbf, 0xff, 0xfd, 0x68, 0x6c, 0x06, + 0x9d, 0xd1, 0x7b, 0x5a, 0x7d, 0x3f, 0x52, 0x7d, 0x4b, 0x8a, 0xb0, 0x8d, 0x7e, 0x00, 0xf0, 0x78, + 0x57, 0x0b, 0x89, 0x2e, 0x0e, 0x70, 0x17, 0x6e, 0x76, 0x73, 0xda, 0xb0, 0xd3, 0x25, 0xe0, 0x15, + 0x01, 0xa8, 0xa1, 0x0b, 0xc3, 0x00, 0xea, 0xab, 0x12, 0xea, 0x71, 0x00, 0x54, 0x36, 0x6c, 0x03, + 0x41, 0xc3, 0x9d, 0xe5, 0x40, 0xd0, 0xae, 0x3e, 0x50, 0x9d, 0x17, 0xa0, 0x17, 0x50, 0xa1, 0x1f, + 0xa8, 0x49, 0xf4, 0x2d, 0x79, 0xcd, 0xb7, 0xf5, 0x4e, 0x77, 0xf8, 0x23, 0x80, 0x99, 0xee, 0x66, + 0x0a, 0x45, 0x39, 0x8e, 0x68, 0xfc, 0x72, 0xfa, 0xd0, 0xf3, 0x87, 0x21, 0xed, 0x91, 0x94, 0x09, + 0xa8, 0x5f, 0x00, 0xcc, 0x74, 0xf7, 0x3d, 0x91, 0xa4, 0x11, 0x9d, 0x57, 0x24, 0x69, 0x54, 0x43, + 0xa5, 0xbe, 0x29, 0x48, 0xaf, 0xa1, 0xab, 0x43, 0x91, 0x3a, 0x78, 0x53, 0xdf, 0xea, 0x34, 0x4c, + 0xdb, 0xe8, 0x57, 0x00, 0x51, 0x6f, 0x13, 0x84, 0x2e, 0x45, 0x60, 0x44, 0xb6, 0x68, 0xb9, 0xb9, + 0x43, 0x58, 0x48, 0xf4, 0xb7, 0x04, 0xfa, 0xeb, 0xe8, 0xda, 0x70, 0x22, 0xbb, 0x0b, 0x85, 0xe1, + 0x1b, 0x30, 0x2e, 0x8e, 0xad, 0x1a, 0x79, 0x0e, 0x3b, 0x67, 0xf5, 0xd5, 0x03, 0xe7, 0x48, 0xa2, + 0x59, 0x41, 0xa4, 0xa2, 0xe9, 0x41, 0x07, 0x14, 0x39, 0x70, 0x5c, 0x14, 0x29, 0x74, 0xd0, 0xba, + 0x7e, 0xe9, 0xc8, 0x9d, 0x39, 0x78, 0x92, 0xf4, 0xae, 0x08, 0xef, 0x59, 0x74, 0xb2, 0xbf, 0x77, + 0xf4, 0x25, 0x80, 0x13, 0x81, 0xfa, 0x88, 0xce, 0x45, 0xac, 0xda, 0x5b, 0xa7, 0x73, 0x85, 0x61, + 0xa6, 0x4a, 0x8c, 0x19, 0x81, 0x31, 0x8d, 0x94, 0xfe, 0x18, 0x4c, 0xaf, 0x0b, 0x23, 0xb4, 0x0d, + 0x13, 0x5e, 0x61, 0x43, 0x51, 0xe1, 0x85, 0xea, 0x67, 0xee, 0xb5, 0x01, 0xb3, 0x86, 0x76, 0xef, + 0x39, 0x7d, 0x0a, 0x20, 0xea, 0xad, 0x50, 0x91, 0x27, 0x37, 0xb2, 0xc0, 0x46, 0x9e, 0xdc, 0xe8, + 0xf2, 0x37, 0xcc, 0xa5, 0x63, 0xba, 0x2c, 0xcf, 0xfa, 0x56, 0x57, 0xf9, 0xde, 0x2e, 0x2e, 0xed, + 0xfc, 0xa5, 0xc4, 0x9e, 0xb4, 0x94, 0xd8, 0x4e, 0x4b, 0x01, 0xbb, 0x2d, 0x05, 0xfc, 0xd9, 0x52, + 0xc0, 0x57, 0x7b, 0x4a, 0x6c, 0x77, 0x4f, 0x89, 0xfd, 0xb1, 0xa7, 0xc4, 0x3e, 0x9c, 0x09, 0xb4, + 0xec, 0x8b, 0x94, 0xd5, 0xee, 0xf9, 0x2e, 0x4c, 0xfd, 0x81, 0xe7, 0x4a, 0xfc, 0xcb, 0x54, 0x4e, + 0x88, 0x7f, 0x82, 0x2e, 0xff, 0x17, 0x00, 0x00, 0xff, 0xff, 0xc0, 0x05, 0x38, 0x11, 0xcc, 0x12, + 0x00, 0x00, } func (this *QueryContractInfoResponse) Equal(that interface{}) bool { @@ -1106,6 +1225,7 @@ func (this *QueryContractInfoResponse) Equal(that interface{}) bool { } return true } + func (this *CodeInfoResponse) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1139,6 +1259,7 @@ func (this *CodeInfoResponse) Equal(that interface{}) bool { } return true } + func (this *QueryCodeResponse) Equal(that interface{}) bool { if that == nil { return this == nil @@ -1168,8 +1289,10 @@ func (this *QueryCodeResponse) Equal(that interface{}) bool { } // Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn +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. @@ -1337,39 +1460,48 @@ type QueryServer interface { } // UnimplementedQueryServer can be embedded to have forward compatible implementations. -type UnimplementedQueryServer struct { -} +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") } @@ -2546,6 +2678,7 @@ func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } + func (m *QueryContractInfoRequest) Size() (n int) { if m == nil { return 0 @@ -2916,9 +3049,11 @@ func (m *QueryContractsByCreatorResponse) 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 *QueryContractInfoRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3001,6 +3136,7 @@ func (m *QueryContractInfoRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryContractInfoResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3116,6 +3252,7 @@ func (m *QueryContractInfoResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryContractHistoryRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3234,6 +3371,7 @@ func (m *QueryContractHistoryRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryContractHistoryResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3354,6 +3492,7 @@ func (m *QueryContractHistoryResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryContractsByCodeRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3459,6 +3598,7 @@ func (m *QueryContractsByCodeRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryContractsByCodeResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3577,6 +3717,7 @@ func (m *QueryContractsByCodeResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryAllContractStateRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3695,6 +3836,7 @@ func (m *QueryAllContractStateRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryAllContractStateResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3815,6 +3957,7 @@ func (m *QueryAllContractStateResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryRawContractStateRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -3931,6 +4074,7 @@ func (m *QueryRawContractStateRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryRawContractStateResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4015,6 +4159,7 @@ func (m *QueryRawContractStateResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QuerySmartContractStateRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4131,6 +4276,7 @@ func (m *QuerySmartContractStateRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QuerySmartContractStateResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4215,6 +4361,7 @@ func (m *QuerySmartContractStateResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryCodeRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4284,6 +4431,7 @@ func (m *QueryCodeRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *CodeInfoResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4452,6 +4600,7 @@ func (m *CodeInfoResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryCodeResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4572,6 +4721,7 @@ func (m *QueryCodeResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryCodesRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4658,6 +4808,7 @@ func (m *QueryCodesRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryCodesResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4778,6 +4929,7 @@ func (m *QueryCodesResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryPinnedCodesRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -4864,6 +5016,7 @@ func (m *QueryPinnedCodesRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryPinnedCodesResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -5026,6 +5179,7 @@ func (m *QueryPinnedCodesResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -5076,6 +5230,7 @@ func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -5159,6 +5314,7 @@ func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryContractsByCreatorRequest) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -5277,6 +5433,7 @@ func (m *QueryContractsByCreatorRequest) Unmarshal(dAtA []byte) error { } return nil } + func (m *QueryContractsByCreatorResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -5395,6 +5552,7 @@ func (m *QueryContractsByCreatorResponse) Unmarshal(dAtA []byte) error { } return nil } + func skipQuery(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/wasm/types/query.pb.gw.go b/x/wasm/types/query.pb.gw.go index 696252a..32f3fd2 100644 --- a/x/wasm/types/query.pb.gw.go +++ b/x/wasm/types/query.pb.gw.go @@ -25,13 +25,15 @@ import ( ) // 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 ( + _ 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 @@ -57,7 +59,6 @@ func request_Query_ContractInfo_0(ctx context.Context, marshaler runtime.Marshal 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) { @@ -84,12 +85,9 @@ func local_request_Query_ContractInfo_0(ctx context.Context, marshaler runtime.M 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}} -) +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 @@ -122,7 +120,6 @@ func request_Query_ContractHistory_0(ctx context.Context, marshaler runtime.Mars 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) { @@ -156,12 +153,9 @@ func local_request_Query_ContractHistory_0(ctx context.Context, marshaler runtim 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}} -) +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 @@ -194,7 +188,6 @@ func request_Query_ContractsByCode_0(ctx context.Context, marshaler runtime.Mars 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) { @@ -228,12 +221,9 @@ func local_request_Query_ContractsByCode_0(ctx context.Context, marshaler runtim 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}} -) +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 @@ -266,7 +256,6 @@ func request_Query_AllContractState_0(ctx context.Context, marshaler runtime.Mar 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) { @@ -300,7 +289,6 @@ func local_request_Query_AllContractState_0(ctx context.Context, marshaler runti 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) { @@ -338,7 +326,6 @@ func request_Query_RawContractState_0(ctx context.Context, marshaler runtime.Mar 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) { @@ -376,7 +363,6 @@ func local_request_Query_RawContractState_0(ctx context.Context, marshaler runti 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) { @@ -414,7 +400,6 @@ func request_Query_SmartContractState_0(ctx context.Context, marshaler runtime.M 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) { @@ -452,7 +437,6 @@ func local_request_Query_SmartContractState_0(ctx context.Context, marshaler run 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) { @@ -479,7 +463,6 @@ func request_Query_Code_0(ctx context.Context, marshaler runtime.Marshaler, clie 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) { @@ -506,12 +489,9 @@ func local_request_Query_Code_0(ctx context.Context, marshaler runtime.Marshaler 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)} -) +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 @@ -526,7 +506,6 @@ func request_Query_Codes_0(ctx context.Context, marshaler runtime.Marshaler, cli 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) { @@ -542,12 +521,9 @@ func local_request_Query_Codes_0(ctx context.Context, marshaler runtime.Marshale 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)} -) +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 @@ -562,7 +538,6 @@ func request_Query_PinnedCodes_0(ctx context.Context, marshaler runtime.Marshale 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) { @@ -578,7 +553,6 @@ func local_request_Query_PinnedCodes_0(ctx context.Context, marshaler runtime.Ma 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) { @@ -587,7 +561,6 @@ 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) { @@ -596,12 +569,9 @@ func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshal 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}} -) +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 @@ -634,7 +604,6 @@ func request_Query_ContractsByCreator_0(ctx context.Context, marshaler runtime.M 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) { @@ -668,7 +637,6 @@ func local_request_Query_ContractsByCreator_0(ctx context.Context, marshaler run msg, err := server.ContractsByCreator(ctx, &protoReq) return msg, metadata, err - } // RegisterQueryHandlerServer registers the http handlers for service Query to "mux". @@ -676,7 +644,6 @@ func local_request_Query_ContractsByCreator_0(ctx context.Context, marshaler run // 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() @@ -697,7 +664,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } 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) { @@ -720,7 +686,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } 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) { @@ -743,7 +708,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } 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) { @@ -766,7 +730,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } 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) { @@ -789,7 +752,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } 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) { @@ -812,7 +774,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } 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) { @@ -835,7 +796,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } 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) { @@ -858,7 +818,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } 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) { @@ -881,7 +840,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } 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) { @@ -904,7 +862,6 @@ 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_ContractsByCreator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -927,7 +884,6 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv } forward_Query_ContractsByCreator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) return nil @@ -970,7 +926,6 @@ 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_ContractInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -988,7 +943,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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) { @@ -1008,7 +962,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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) { @@ -1028,7 +981,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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) { @@ -1048,7 +1000,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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) { @@ -1068,7 +1019,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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) { @@ -1088,7 +1038,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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) { @@ -1108,7 +1057,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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) { @@ -1128,7 +1076,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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) { @@ -1148,7 +1095,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } 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) { @@ -1168,7 +1114,6 @@ 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_ContractsByCreator_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { @@ -1188,7 +1133,6 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } forward_Query_ContractsByCreator_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) - }) return nil diff --git a/x/wasm/types/test_fixtures.go b/x/wasm/types/test_fixtures.go index e84b61f..fb93367 100644 --- a/x/wasm/types/test_fixtures.go +++ b/x/wasm/types/test_fixtures.go @@ -45,7 +45,7 @@ func GenesisFixture(mutators ...func(*GenesisState)) GenesisState { func randBytes(n int) []byte { r := make([]byte, n) - rand.Read(r) + rand.Read(r) //nolint:staticcheck return r } diff --git a/x/wasm/types/tx.go b/x/wasm/types/tx.go index 6742224..30c9c41 100644 --- a/x/wasm/types/tx.go +++ b/x/wasm/types/tx.go @@ -6,6 +6,7 @@ import ( "errors" "strings" + errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -61,12 +62,17 @@ func (msg MsgStoreCode) ValidateBasic() error { } if err := validateWasmCode(msg.WASMByteCode, MaxWasmSize); err != nil { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) + return errorsmod.Wrapf(sdkerrors.ErrInvalidRequest, "code bytes %s", err.Error()) } if msg.InstantiatePermission != nil { if err := msg.InstantiatePermission.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "instantiate permission") + 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 @@ -94,15 +100,15 @@ func (msg MsgInstantiateContract) Type() string { func (msg MsgInstantiateContract) ValidateBasic() error { if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return sdkerrors.Wrap(err, "sender") + return errorsmod.Wrap(err, "sender") } if msg.CodeID == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") } if err := ValidateLabel(msg.Label); err != nil { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "label is required") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "label is required") } if !msg.Funds.IsValid() { @@ -111,11 +117,11 @@ func (msg MsgInstantiateContract) ValidateBasic() error { if len(msg.Admin) != 0 { if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { - return sdkerrors.Wrap(err, "admin") + return errorsmod.Wrap(err, "admin") } } if err := msg.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } return nil } @@ -142,17 +148,17 @@ func (msg MsgExecuteContract) Type() string { func (msg MsgExecuteContract) ValidateBasic() error { if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return sdkerrors.Wrap(err, "sender") + return errorsmod.Wrap(err, "sender") } if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } if !msg.Funds.IsValid() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "sentFunds") + return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "sentFunds") } if err := msg.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } return nil } @@ -194,17 +200,17 @@ func (msg MsgMigrateContract) Type() string { func (msg MsgMigrateContract) ValidateBasic() error { if msg.CodeID == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") } if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return sdkerrors.Wrap(err, "sender") + return errorsmod.Wrap(err, "sender") } if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } if err := msg.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } return nil @@ -247,16 +253,16 @@ func (msg MsgUpdateAdmin) Type() string { func (msg MsgUpdateAdmin) ValidateBasic() error { if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return sdkerrors.Wrap(err, "sender") + return errorsmod.Wrap(err, "sender") } if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } if _, err := sdk.AccAddressFromBech32(msg.NewAdmin); err != nil { - return sdkerrors.Wrap(err, "new admin") + return errorsmod.Wrap(err, "new admin") } if strings.EqualFold(msg.Sender, msg.NewAdmin) { - return sdkerrors.Wrap(ErrInvalidMsg, "new admin is the same as the old") + return errorsmod.Wrap(ErrInvalidMsg, "new admin is the same as the old") } return nil } @@ -283,10 +289,10 @@ func (msg MsgClearAdmin) Type() string { func (msg MsgClearAdmin) ValidateBasic() error { if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return sdkerrors.Wrap(err, "sender") + return errorsmod.Wrap(err, "sender") } if _, err := sdk.AccAddressFromBech32(msg.Contract); err != nil { - return sdkerrors.Wrap(err, "contract") + return errorsmod.Wrap(err, "contract") } return nil } @@ -355,15 +361,15 @@ func (msg MsgInstantiateContract2) Type() string { func (msg MsgInstantiateContract2) ValidateBasic() error { if _, err := sdk.AccAddressFromBech32(msg.Sender); err != nil { - return sdkerrors.Wrap(err, "sender") + return errorsmod.Wrap(err, "sender") } if msg.CodeID == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "code id is required") } if err := ValidateLabel(msg.Label); err != nil { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "label is required") + return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, "label is required") } if !msg.Funds.IsValid() { @@ -372,14 +378,14 @@ func (msg MsgInstantiateContract2) ValidateBasic() error { if len(msg.Admin) != 0 { if _, err := sdk.AccAddressFromBech32(msg.Admin); err != nil { - return sdkerrors.Wrap(err, "admin") + return errorsmod.Wrap(err, "admin") } } if err := msg.Msg.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "payload msg") + return errorsmod.Wrap(err, "payload msg") } if err := ValidateSalt(msg.Salt); err != nil { - return sdkerrors.Wrap(err, "salt") + return errorsmod.Wrap(err, "salt") } return nil } @@ -395,3 +401,237 @@ func (msg MsgInstantiateContract2) GetSigners() []sdk.AccAddress { } 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 index b2c0180..4d4ad49 100644 --- a/x/wasm/types/tx.pb.go +++ b/x/wasm/types/tx.pb.go @@ -6,23 +6,29 @@ 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/gogo/protobuf/grpc" - proto "github.com/gogo/protobuf/proto" + 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 +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. @@ -32,7 +38,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // MsgStoreCode submit Wasm code to the system type MsgStoreCode struct { - // Sender is the that actor that signed the messages + // 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"` @@ -47,9 +53,11 @@ 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) @@ -62,12 +70,15 @@ func (m *MsgStoreCode) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) 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) } @@ -88,9 +99,11 @@ 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) @@ -103,12 +116,15 @@ func (m *MsgStoreCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte 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) } @@ -138,9 +154,11 @@ 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) @@ -153,18 +171,67 @@ func (m *MsgInstantiateContract) XXX_Marshal(b []byte, deterministic bool) ([]by 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 { @@ -191,11 +258,13 @@ 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{3} + 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) @@ -208,59 +277,21 @@ func (m *MsgInstantiateContract2) XXX_Marshal(b []byte, deterministic bool) ([]b 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 -// 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{4} -} -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 - // MsgInstantiateContract2Response return instantiation result data type MsgInstantiateContract2Response struct { // Address is the bech32 address of the new contract instance. @@ -275,9 +306,11 @@ 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) @@ -290,12 +323,15 @@ func (m *MsgInstantiateContract2Response) XXX_Marshal(b []byte, deterministic bo 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) } @@ -320,9 +356,11 @@ 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) @@ -335,12 +373,15 @@ func (m *MsgExecuteContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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) } @@ -359,9 +400,11 @@ 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) @@ -374,12 +417,15 @@ func (m *MsgExecuteContractResponse) XXX_Marshal(b []byte, deterministic bool) ( 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) } @@ -404,9 +450,11 @@ 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) @@ -419,12 +467,15 @@ func (m *MsgMigrateContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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) } @@ -444,9 +495,11 @@ 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) @@ -459,12 +512,15 @@ func (m *MsgMigrateContractResponse) XXX_Marshal(b []byte, deterministic bool) ( 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) } @@ -487,9 +543,11 @@ 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) @@ -502,12 +560,15 @@ func (m *MsgUpdateAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, erro 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) } @@ -515,8 +576,7 @@ func (m *MsgUpdateAdmin) XXX_DiscardUnknown() { var xxx_messageInfo_MsgUpdateAdmin proto.InternalMessageInfo // MsgUpdateAdminResponse returns empty data -type MsgUpdateAdminResponse struct { -} +type MsgUpdateAdminResponse struct{} func (m *MsgUpdateAdminResponse) Reset() { *m = MsgUpdateAdminResponse{} } func (m *MsgUpdateAdminResponse) String() string { return proto.CompactTextString(m) } @@ -524,9 +584,11 @@ 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) @@ -539,12 +601,15 @@ func (m *MsgUpdateAdminResponse) XXX_Marshal(b []byte, deterministic bool) ([]by 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) } @@ -553,7 +618,7 @@ var xxx_messageInfo_MsgUpdateAdminResponse proto.InternalMessageInfo // MsgClearAdmin removes any admin stored for a smart contract type MsgClearAdmin struct { - // Sender is the that actor that signed the messages + // 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"` @@ -565,9 +630,11 @@ 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) @@ -580,12 +647,15 @@ func (m *MsgClearAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error 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) } @@ -593,8 +663,7 @@ func (m *MsgClearAdmin) XXX_DiscardUnknown() { var xxx_messageInfo_MsgClearAdmin proto.InternalMessageInfo // MsgClearAdminResponse returns empty data -type MsgClearAdminResponse struct { -} +type MsgClearAdminResponse struct{} func (m *MsgClearAdminResponse) Reset() { *m = MsgClearAdminResponse{} } func (m *MsgClearAdminResponse) String() string { return proto.CompactTextString(m) } @@ -602,9 +671,11 @@ 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) @@ -617,1314 +688,4842 @@ func (m *MsgClearAdminResponse) XXX_Marshal(b []byte, deterministic bool) ([]byt 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 -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((*MsgInstantiateContract2)(nil), "cosmwasm.wasm.v1.MsgInstantiateContract2") - proto.RegisterType((*MsgInstantiateContractResponse)(nil), "cosmwasm.wasm.v1.MsgInstantiateContractResponse") - 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") +// 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 init() { proto.RegisterFile("cosmwasm/wasm/v1/tx.proto", fileDescriptor_4f74d82755520264) } +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} +} -var fileDescriptor_4f74d82755520264 = []byte{ - // 847 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe4, 0x56, 0x4d, 0x6f, 0xe3, 0x44, - 0x18, 0x8e, 0x1b, 0x27, 0x4d, 0xdf, 0x86, 0xa5, 0x32, 0xd9, 0xd4, 0x6b, 0x90, 0x13, 0x19, 0x04, - 0x46, 0xa2, 0x76, 0x13, 0x24, 0xee, 0x4d, 0xe0, 0xd0, 0x45, 0x06, 0xe4, 0x6a, 0x59, 0xc1, 0x25, - 0x9a, 0xd8, 0x13, 0xaf, 0xd5, 0xc4, 0x13, 0x3c, 0x93, 0x26, 0xfd, 0x13, 0x88, 0x1b, 0xff, 0x81, - 0xdf, 0xc0, 0x05, 0x89, 0x43, 0x8f, 0x7b, 0x41, 0xe2, 0x14, 0x20, 0xfd, 0x17, 0x9c, 0x90, 0xc7, - 0x1f, 0xf5, 0xa6, 0x4e, 0x1a, 0x40, 0x9c, 0xb8, 0x24, 0xf3, 0x7a, 0x9e, 0xf7, 0xeb, 0x99, 0xe7, - 0x1d, 0x1b, 0x9e, 0x38, 0x84, 0x4e, 0xe6, 0x88, 0x4e, 0x4c, 0xfe, 0x73, 0xd5, 0x31, 0xd9, 0xc2, - 0x98, 0x86, 0x84, 0x11, 0xe9, 0x28, 0xdd, 0x32, 0xf8, 0xcf, 0x55, 0x47, 0x51, 0xa3, 0x27, 0x84, - 0x9a, 0x43, 0x44, 0xb1, 0x79, 0xd5, 0x19, 0x62, 0x86, 0x3a, 0xa6, 0x43, 0xfc, 0x20, 0xf6, 0x50, - 0x1a, 0x1e, 0xf1, 0x08, 0x5f, 0x9a, 0xd1, 0x2a, 0x79, 0xfa, 0xd6, 0xfd, 0x14, 0xd7, 0x53, 0x4c, - 0xe3, 0x5d, 0xed, 0x27, 0x01, 0xea, 0x16, 0xf5, 0x2e, 0x18, 0x09, 0x71, 0x9f, 0xb8, 0x58, 0x6a, - 0x42, 0x95, 0xe2, 0xc0, 0xc5, 0xa1, 0x2c, 0xb4, 0x05, 0xfd, 0xc0, 0x4e, 0x2c, 0xe9, 0x23, 0x78, - 0x14, 0xf9, 0x0f, 0x86, 0xd7, 0x0c, 0x0f, 0x1c, 0xe2, 0x62, 0x79, 0xaf, 0x2d, 0xe8, 0xf5, 0xde, - 0xd1, 0x6a, 0xd9, 0xaa, 0x3f, 0x3f, 0xbb, 0xb0, 0x7a, 0xd7, 0x8c, 0x47, 0xb0, 0xeb, 0x11, 0x2e, - 0xb5, 0xa4, 0x67, 0xd0, 0xf4, 0x03, 0xca, 0x50, 0xc0, 0x7c, 0xc4, 0xf0, 0x60, 0x8a, 0xc3, 0x89, - 0x4f, 0xa9, 0x4f, 0x02, 0xb9, 0xd2, 0x16, 0xf4, 0xc3, 0xae, 0x6a, 0xac, 0xf7, 0x69, 0x9c, 0x39, - 0x0e, 0xa6, 0xb4, 0x4f, 0x82, 0x91, 0xef, 0xd9, 0x8f, 0x73, 0xde, 0x5f, 0x64, 0xce, 0x4f, 0xc5, - 0x5a, 0xf9, 0x48, 0x7c, 0x2a, 0xd6, 0xc4, 0xa3, 0x8a, 0xf6, 0x1c, 0x1a, 0xf9, 0x16, 0x6c, 0x4c, - 0xa7, 0x24, 0xa0, 0x58, 0x7a, 0x1b, 0xf6, 0xa3, 0x42, 0x07, 0xbe, 0xcb, 0x7b, 0x11, 0x7b, 0xb0, - 0x5a, 0xb6, 0xaa, 0x11, 0xe4, 0xfc, 0x63, 0xbb, 0x1a, 0x6d, 0x9d, 0xbb, 0x92, 0x02, 0x35, 0xe7, - 0x05, 0x76, 0x2e, 0xe9, 0x6c, 0x12, 0x77, 0x64, 0x67, 0xb6, 0xf6, 0xed, 0x1e, 0x34, 0x2d, 0xea, - 0x9d, 0xdf, 0x55, 0xd0, 0x27, 0x01, 0x0b, 0x91, 0xc3, 0x36, 0xd2, 0xd4, 0x80, 0x0a, 0x72, 0x27, - 0x7e, 0xc0, 0x63, 0x1d, 0xd8, 0xb1, 0x91, 0xaf, 0xa4, 0xbc, 0xb1, 0x92, 0x06, 0x54, 0xc6, 0x68, - 0x88, 0xc7, 0xb2, 0x18, 0xbb, 0x72, 0x43, 0xd2, 0xa1, 0x3c, 0xa1, 0x1e, 0x27, 0xab, 0xde, 0x6b, - 0xfe, 0xb9, 0x6c, 0x49, 0x36, 0x9a, 0xa7, 0x65, 0x58, 0x98, 0x52, 0xe4, 0x61, 0x3b, 0x82, 0x48, - 0x08, 0x2a, 0xa3, 0x59, 0xe0, 0x52, 0xb9, 0xda, 0x2e, 0xeb, 0x87, 0xdd, 0x27, 0x46, 0x2c, 0x17, - 0x23, 0x92, 0x8b, 0x91, 0xc8, 0xc5, 0xe8, 0x13, 0x3f, 0xe8, 0x9d, 0xde, 0x2c, 0x5b, 0xa5, 0x1f, - 0x7e, 0x6b, 0xe9, 0x9e, 0xcf, 0x5e, 0xcc, 0x86, 0x86, 0x43, 0x26, 0x66, 0xa2, 0xad, 0xf8, 0xef, - 0x84, 0xba, 0x97, 0x89, 0x4c, 0x22, 0x07, 0x6a, 0xc7, 0x91, 0xb5, 0x1f, 0xf7, 0xe0, 0xb8, 0x98, - 0x90, 0xee, 0xff, 0x93, 0x11, 0x49, 0x02, 0x91, 0xa2, 0x31, 0x93, 0xf7, 0xb9, 0x74, 0xf8, 0x5a, - 0x3a, 0x86, 0xfd, 0x91, 0xbf, 0x18, 0x44, 0x45, 0xd6, 0xda, 0x82, 0x5e, 0xb3, 0xab, 0x23, 0x7f, - 0x61, 0x51, 0x4f, 0xfb, 0x0c, 0xd4, 0x62, 0xf6, 0x32, 0xc9, 0xca, 0xb0, 0x8f, 0x5c, 0x37, 0xc4, - 0x94, 0x26, 0x2c, 0xa6, 0x66, 0x94, 0xc8, 0x45, 0x0c, 0x25, 0x1a, 0xe5, 0x6b, 0xed, 0x73, 0x68, - 0x6d, 0x38, 0x8d, 0x7f, 0x18, 0xf0, 0x17, 0x01, 0x24, 0x8b, 0x7a, 0x9f, 0x2c, 0xb0, 0x33, 0xdb, - 0x41, 0xec, 0xd1, 0xec, 0x24, 0x98, 0xe4, 0x74, 0x33, 0x3b, 0x3d, 0xa5, 0xf2, 0xdf, 0x38, 0xa5, - 0xca, 0x7f, 0xa6, 0xdb, 0x53, 0x50, 0xee, 0xb7, 0x95, 0x71, 0x94, 0x32, 0x21, 0xe4, 0x98, 0xf8, - 0x3e, 0x66, 0xc2, 0xf2, 0xbd, 0x10, 0xfd, 0x4b, 0x26, 0x76, 0x92, 0x7a, 0x42, 0x97, 0xf8, 0x20, - 0x5d, 0x49, 0x2f, 0x6b, 0x85, 0x6d, 0xed, 0x05, 0xc1, 0x23, 0x8b, 0x7a, 0xcf, 0xa6, 0x2e, 0x62, - 0xf8, 0x8c, 0x4f, 0xdf, 0xa6, 0x36, 0xde, 0x84, 0x83, 0x00, 0xcf, 0x07, 0xf9, 0x79, 0xad, 0x05, - 0x78, 0x1e, 0x3b, 0xe5, 0x7b, 0x2c, 0xbf, 0xda, 0xa3, 0x26, 0xf3, 0x8b, 0x32, 0x97, 0x22, 0x2d, - 0x48, 0xeb, 0xc3, 0x6b, 0x16, 0xf5, 0xfa, 0x63, 0x8c, 0xc2, 0xed, 0xb9, 0xb7, 0x85, 0x3f, 0x86, - 0xc7, 0xaf, 0x04, 0x49, 0xa3, 0x77, 0x7f, 0xae, 0x40, 0xd9, 0xa2, 0x9e, 0x74, 0x01, 0x07, 0x77, - 0xaf, 0xb0, 0x82, 0x57, 0x4a, 0xfe, 0xfd, 0xa0, 0xbc, 0xbb, 0x7d, 0x3f, 0xe3, 0xf2, 0x1b, 0x78, - 0xa3, 0xe8, 0xea, 0xd7, 0x0b, 0xdd, 0x0b, 0x90, 0xca, 0xe9, 0xae, 0xc8, 0x2c, 0x25, 0x83, 0x46, - 0xe1, 0xe5, 0xfa, 0xfe, 0xae, 0x91, 0xba, 0x4a, 0x67, 0x67, 0x68, 0x96, 0x15, 0xc3, 0xeb, 0xeb, - 0x23, 0xff, 0x4e, 0x61, 0x94, 0x35, 0x94, 0xf2, 0xc1, 0x2e, 0xa8, 0x7c, 0x9a, 0xf5, 0x79, 0x2a, - 0x4e, 0xb3, 0x86, 0xda, 0x90, 0x66, 0xd3, 0x08, 0x7c, 0x05, 0x87, 0x79, 0xad, 0xb7, 0x0b, 0x9d, - 0x73, 0x08, 0x45, 0x7f, 0x08, 0x91, 0x85, 0xfe, 0x12, 0x20, 0xa7, 0xe4, 0x56, 0xa1, 0xdf, 0x1d, - 0x40, 0x79, 0xef, 0x01, 0x40, 0x1a, 0xb7, 0xf7, 0xe9, 0xcd, 0x1f, 0x6a, 0xe9, 0x66, 0xa5, 0x0a, - 0x2f, 0x57, 0xaa, 0xf0, 0xfb, 0x4a, 0x15, 0xbe, 0xbb, 0x55, 0x4b, 0x2f, 0x6f, 0xd5, 0xd2, 0xaf, - 0xb7, 0x6a, 0xe9, 0xeb, 0x93, 0xdc, 0x75, 0xc7, 0x70, 0x38, 0x0d, 0x30, 0x9b, 0x93, 0xf0, 0x92, - 0xaf, 0x4f, 0x1c, 0x12, 0x62, 0x73, 0x11, 0x7f, 0xdb, 0xf1, 0x9b, 0x6f, 0x58, 0xe5, 0x5f, 0x76, - 0x1f, 0xfe, 0x15, 0x00, 0x00, 0xff, 0xff, 0xea, 0x0f, 0xa3, 0x9d, 0x5c, 0x0a, 0x00, 0x00, +func (m *MsgUpdateInstantiateConfig) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) } -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn +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 + } +} -// 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 +func (m *MsgUpdateInstantiateConfig) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateInstantiateConfig.Merge(m, src) +} -// 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) +func (m *MsgUpdateInstantiateConfig) XXX_Size() int { + return m.Size() } -type msgClient struct { - cc grpc1.ClientConn +func (m *MsgUpdateInstantiateConfig) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateInstantiateConfig.DiscardUnknown(m) } -func NewMsgClient(cc grpc1.ClientConn) MsgClient { - return &msgClient{cc} +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 (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 (m *MsgUpdateInstantiateConfigResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) } -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 +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 } - 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 (m *MsgUpdateInstantiateConfigResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateInstantiateConfigResponse.Merge(m, src) } -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 (m *MsgUpdateInstantiateConfigResponse) XXX_Size() int { + return m.Size() } -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 (m *MsgUpdateInstantiateConfigResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateInstantiateConfigResponse.DiscardUnknown(m) } -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 +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 (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 +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 } - 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) +func (m *MsgUpdateParams) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParams.Merge(m, src) } -// UnimplementedMsgServer can be embedded to have forward compatible implementations. -type UnimplementedMsgServer struct { +func (m *MsgUpdateParams) XXX_Size() int { + return m.Size() } -func (*UnimplementedMsgServer) StoreCode(ctx context.Context, req *MsgStoreCode) (*MsgStoreCodeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method StoreCode not implemented") +func (m *MsgUpdateParams) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParams.DiscardUnknown(m) } -func (*UnimplementedMsgServer) InstantiateContract(ctx context.Context, req *MsgInstantiateContract) (*MsgInstantiateContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method InstantiateContract not implemented") + +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 (*UnimplementedMsgServer) InstantiateContract2(ctx context.Context, req *MsgInstantiateContract2) (*MsgInstantiateContract2Response, error) { - return nil, status.Errorf(codes.Unimplemented, "method InstantiateContract2 not implemented") + +func (m *MsgUpdateParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) } -func (*UnimplementedMsgServer) ExecuteContract(ctx context.Context, req *MsgExecuteContract) (*MsgExecuteContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ExecuteContract not implemented") + +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 (*UnimplementedMsgServer) MigrateContract(ctx context.Context, req *MsgMigrateContract) (*MsgMigrateContractResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method MigrateContract not implemented") + +func (m *MsgUpdateParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateParamsResponse.Merge(m, src) } -func (*UnimplementedMsgServer) UpdateAdmin(ctx context.Context, req *MsgUpdateAdmin) (*MsgUpdateAdminResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateAdmin not implemented") + +func (m *MsgUpdateParamsResponse) XXX_Size() int { + return m.Size() } -func (*UnimplementedMsgServer) ClearAdmin(ctx context.Context, req *MsgClearAdmin) (*MsgClearAdminResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ClearAdmin not implemented") + +func (m *MsgUpdateParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateParamsResponse.DiscardUnknown(m) } -func RegisterMsgServer(s grpc1.Server, srv MsgServer) { - s.RegisterService(&_Msg_serviceDesc, srv) +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 _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 (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 _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 (m *MsgSudoContract) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) } -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)) +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 } - 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 (m *MsgSudoContract) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSudoContract.Merge(m, src) } -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 (m *MsgSudoContract) XXX_Size() int { + return m.Size() } -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 (m *MsgSudoContract) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSudoContract.DiscardUnknown(m) } -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)) +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 } - 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, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmwasm/wasm/v1/tx.proto", +func (m *MsgSudoContractResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgSudoContractResponse.Merge(m, src) } -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 *MsgSudoContractResponse) XXX_Size() int { + return m.Size() } -func (m *MsgStoreCode) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +func (m *MsgSudoContractResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgSudoContractResponse.DiscardUnknown(m) } -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)) +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 } - 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 b[:n], nil } - 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 *MsgPinCodes) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgPinCodes.Merge(m, src) } -func (m *MsgStoreCodeResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +func (m *MsgPinCodes) XXX_Size() int { + return m.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 *MsgPinCodes) XXX_DiscardUnknown() { + xxx_messageInfo_MsgPinCodes.DiscardUnknown(m) } -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 +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 *MsgInstantiateContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +func (m *MsgPinCodesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) } -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 +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 } - 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 *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 +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 } - return dAtA[:n], nil } -func (m *MsgInstantiateContract2) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +func (m *MsgUnpinCodes) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUnpinCodes.Merge(m, src) } -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 +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 } - i-- - dAtA[i] = 0x40 + return b[:n], nil } - 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 *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 *MsgUnpinCodesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUnpinCodesResponse.Merge(m, src) } -func (m *MsgInstantiateContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +func (m *MsgUnpinCodesResponse) XXX_Size() int { + return m.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 *MsgUnpinCodesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUnpinCodesResponse.DiscardUnknown(m) } -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 +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 } - return dAtA[:n], nil } -func (m *MsgInstantiateContract2Response) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +func (m *MsgStoreAndInstantiateContract) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgStoreAndInstantiateContract.Merge(m, src) } -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 *MsgStoreAndInstantiateContract) XXX_Size() int { + return m.Size() } -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 *MsgStoreAndInstantiateContract) XXX_DiscardUnknown() { + xxx_messageInfo_MsgStoreAndInstantiateContract.DiscardUnknown(m) } -func (m *MsgExecuteContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +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 *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 +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 } - 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 *MsgStoreAndInstantiateContractResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgStoreAndInstantiateContractResponse.Merge(m, src) } -func (m *MsgExecuteContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +func (m *MsgStoreAndInstantiateContractResponse) XXX_Size() int { + return m.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 *MsgStoreAndInstantiateContractResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgStoreAndInstantiateContractResponse.DiscardUnknown(m) } -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 +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 (m *MsgMigrateContract) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +func init() { proto.RegisterFile("cosmwasm/wasm/v1/tx.proto", fileDescriptor_4f74d82755520264) } + +var fileDescriptor_4f74d82755520264 = []byte{ + // 1441 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, 0xb6, 0x76, 0x63, 0xa0, 0x82, 0x70, 0x8a, 0x53, 0x24, 0x52, 0xc9, 0x10, 0x6d, 0xd4, + 0x56, 0xa0, 0x4a, 0xd6, 0xda, 0x3b, 0xd9, 0xac, 0x9a, 0xdd, 0x35, 0x9e, 0x75, 0x93, 0x1c, 0xb8, + 0x80, 0x84, 0x04, 0x27, 0xfe, 0x09, 0x24, 0xe0, 0x42, 0x0f, 0x20, 0x71, 0xec, 0xb1, 0x12, 0x97, + 0x8a, 0x13, 0xa7, 0x00, 0x2e, 0x52, 0xb9, 0x21, 0x71, 0xe4, 0x84, 0x66, 0x66, 0x77, 0x3d, 0x5e, + 0xef, 0x3a, 0x4e, 0x4a, 0xc5, 0x81, 0x4b, 0xb2, 0x33, 0xef, 0xc7, 0xbc, 0xcf, 0xe7, 0xbd, 0x99, + 0x79, 0x63, 0x58, 0x68, 0x3b, 0xd8, 0xda, 0xd1, 0xb0, 0x55, 0xa5, 0x7f, 0x1e, 0x2e, 0x55, 0xdd, + 0xdd, 0x4a, 0xa7, 0xeb, 0xb8, 0x8e, 0x38, 0xeb, 0x8b, 0x2a, 0xf4, 0xcf, 0xc3, 0x25, 0xb9, 0x48, + 0x66, 0x1c, 0x5c, 0x6d, 0x69, 0x18, 0x55, 0x1f, 0x2e, 0xb5, 0x90, 0xab, 0x2d, 0x55, 0xdb, 0x8e, + 0x69, 0x33, 0x0b, 0x79, 0xde, 0x93, 0x5b, 0xd8, 0x20, 0x9e, 0x2c, 0x6c, 0x78, 0x82, 0x82, 0xe1, + 0x18, 0x0e, 0xfd, 0xac, 0x92, 0x2f, 0x6f, 0xf6, 0xcc, 0xe8, 0xda, 0x7b, 0x1d, 0x84, 0x3d, 0xe9, + 0x02, 0x73, 0xd6, 0x64, 0x66, 0x6c, 0xe0, 0x89, 0x4e, 0x68, 0x96, 0x69, 0x3b, 0x55, 0xfa, 0x97, + 0x4d, 0x29, 0xbf, 0x09, 0x90, 0x6f, 0x60, 0x63, 0xc3, 0x75, 0xba, 0x68, 0xd5, 0xd1, 0x91, 0x38, + 0x07, 0x69, 0x8c, 0x6c, 0x1d, 0x75, 0x25, 0x61, 0x51, 0x28, 0xe7, 0x54, 0x6f, 0x24, 0xde, 0x84, + 0x63, 0x64, 0xb5, 0x66, 0x6b, 0xcf, 0x45, 0xcd, 0xb6, 0xa3, 0x23, 0x69, 0x7a, 0x51, 0x28, 0xe7, + 0xeb, 0xb3, 0xfd, 0xfd, 0x52, 0xfe, 0xde, 0xca, 0x46, 0xa3, 0xbe, 0xe7, 0x52, 0x0f, 0x6a, 0x9e, + 0xe8, 0xf9, 0x23, 0xf1, 0x0e, 0xcc, 0x99, 0x36, 0x76, 0x35, 0xdb, 0x35, 0x35, 0x17, 0x35, 0x3b, + 0xa8, 0x6b, 0x99, 0x18, 0x9b, 0x8e, 0x2d, 0xa5, 0x16, 0x85, 0xf2, 0x4c, 0xad, 0x58, 0x09, 0xd3, + 0x55, 0x59, 0x69, 0xb7, 0x11, 0xc6, 0xab, 0x8e, 0xbd, 0x69, 0x1a, 0xea, 0x29, 0xce, 0x7a, 0x3d, + 0x30, 0x5e, 0x3e, 0xf7, 0xd1, 0xf3, 0x47, 0x57, 0xbd, 0xd8, 0x3e, 0x7b, 0xfe, 0xe8, 0xea, 0x09, + 0x4a, 0x05, 0x8f, 0xe4, 0x76, 0x32, 0x9b, 0x98, 0x4d, 0xde, 0x4e, 0x66, 0x93, 0xb3, 0x29, 0xe5, + 0x1e, 0x14, 0x78, 0x99, 0x8a, 0x70, 0xc7, 0xb1, 0x31, 0x12, 0xcf, 0x43, 0x86, 0x60, 0x69, 0x9a, + 0x3a, 0x85, 0x9b, 0xac, 0x43, 0x7f, 0xbf, 0x94, 0x26, 0x2a, 0x6b, 0xb7, 0xd4, 0x34, 0x11, 0xad, + 0xe9, 0xa2, 0x0c, 0xd9, 0xf6, 0x16, 0x6a, 0x3f, 0xc0, 0x3d, 0x8b, 0x81, 0x56, 0x83, 0xb1, 0xf2, + 0x78, 0x1a, 0xe6, 0x1a, 0xd8, 0x58, 0x1b, 0x04, 0xb9, 0xea, 0xd8, 0x6e, 0x57, 0x6b, 0xbb, 0xb1, + 0x4c, 0x16, 0x20, 0xa5, 0xe9, 0x96, 0x69, 0x53, 0x5f, 0x39, 0x95, 0x0d, 0xf8, 0x48, 0x12, 0xb1, + 0x91, 0x14, 0x20, 0xb5, 0xad, 0xb5, 0xd0, 0xb6, 0x94, 0x64, 0xa6, 0x74, 0x20, 0x96, 0x21, 0x61, + 0x61, 0x83, 0xf2, 0x99, 0xaf, 0xcf, 0xfd, 0xb5, 0x5f, 0x12, 0x55, 0x6d, 0xc7, 0x0f, 0xa3, 0x81, + 0x30, 0xd6, 0x0c, 0xa4, 0x12, 0x15, 0x71, 0x13, 0x52, 0x9b, 0x3d, 0x5b, 0xc7, 0x52, 0x7a, 0x31, + 0x51, 0x9e, 0xa9, 0x2d, 0x54, 0xbc, 0xf2, 0x20, 0x85, 0x59, 0xf1, 0x0a, 0xb3, 0xb2, 0xea, 0x98, + 0x76, 0xfd, 0xb5, 0x27, 0xfb, 0xa5, 0xa9, 0xaf, 0x7f, 0x2e, 0x95, 0x0d, 0xd3, 0xdd, 0xea, 0xb5, + 0x2a, 0x6d, 0xc7, 0xf2, 0x6a, 0xc9, 0xfb, 0x77, 0x1d, 0xeb, 0x0f, 0xbc, 0xba, 0x23, 0x06, 0xf8, + 0xcb, 0xe7, 0x8f, 0xae, 0x0a, 0x2a, 0x73, 0xbf, 0xfc, 0xff, 0x50, 0x76, 0x4e, 0xfb, 0xd9, 0x89, + 0xe0, 0x49, 0x79, 0x07, 0x8a, 0xd1, 0x92, 0x20, 0x4b, 0x12, 0x64, 0x34, 0x5d, 0xef, 0x22, 0x8c, + 0x3d, 0x2a, 0xfd, 0xa1, 0x28, 0x42, 0x52, 0xd7, 0x5c, 0xcd, 0x4b, 0x0b, 0xfd, 0x56, 0xfe, 0x98, + 0x86, 0xf9, 0x68, 0x87, 0xb5, 0xff, 0x70, 0x4e, 0x08, 0x55, 0x58, 0xdb, 0x76, 0xa5, 0x0c, 0xa3, + 0x8a, 0x7c, 0x8b, 0xf3, 0x90, 0xd9, 0x34, 0x77, 0x9b, 0x24, 0xd2, 0xec, 0xa2, 0x50, 0xce, 0xaa, + 0xe9, 0x4d, 0x73, 0xb7, 0x81, 0x8d, 0xe5, 0x6b, 0xa1, 0x04, 0x9e, 0x19, 0x93, 0xc0, 0x9a, 0xf2, + 0x2e, 0x94, 0x62, 0x44, 0x47, 0x4c, 0xe1, 0xc7, 0xd3, 0x20, 0x36, 0xb0, 0xf1, 0xd6, 0x2e, 0x6a, + 0xf7, 0x26, 0xd8, 0x51, 0x64, 0x83, 0x7a, 0x3a, 0x5e, 0x02, 0x83, 0xb1, 0x9f, 0x88, 0xc4, 0x21, + 0x12, 0x91, 0x7a, 0xb9, 0x9b, 0xe3, 0x72, 0x88, 0xdb, 0x79, 0x9f, 0xdb, 0x10, 0x5c, 0xe5, 0x06, + 0xc8, 0xa3, 0xb3, 0x01, 0xa3, 0x3e, 0x6f, 0x02, 0xc7, 0xdb, 0x63, 0x81, 0xf2, 0xd6, 0x30, 0x8d, + 0xae, 0xf6, 0x82, 0xbc, 0x4d, 0x54, 0xfb, 0x1e, 0xb9, 0xc9, 0x03, 0xc9, 0x8d, 0x07, 0x1d, 0x8a, + 0xd5, 0x03, 0x1d, 0x9a, 0x1d, 0x0b, 0xfa, 0x13, 0x01, 0x8e, 0x35, 0xb0, 0x71, 0xa7, 0xa3, 0x6b, + 0x2e, 0x5a, 0xa1, 0x1b, 0x37, 0x0e, 0xf0, 0x69, 0xc8, 0xd9, 0x68, 0xa7, 0xc9, 0x6f, 0xf5, 0xac, + 0x8d, 0x76, 0x98, 0x11, 0xcf, 0x46, 0x62, 0x98, 0x8d, 0xe5, 0xf3, 0xa1, 0xf0, 0x4f, 0xfa, 0xe1, + 0x73, 0xab, 0x2a, 0x12, 0xbd, 0x0a, 0xb8, 0x19, 0x3f, 0x6c, 0xc5, 0x80, 0xff, 0x35, 0xb0, 0xb1, + 0xba, 0x8d, 0xb4, 0xee, 0xf8, 0x00, 0xc7, 0xc5, 0xa0, 0x84, 0x62, 0x10, 0xfd, 0x18, 0x06, 0x7e, + 0x95, 0x79, 0x38, 0x35, 0x34, 0x11, 0x44, 0xf0, 0xbb, 0x40, 0x79, 0x65, 0xc1, 0x0d, 0xef, 0xd4, + 0x4d, 0xd3, 0x88, 0x8d, 0x87, 0xab, 0x82, 0xe9, 0xd8, 0x2a, 0xb8, 0x0f, 0x32, 0x61, 0x35, 0xe6, + 0x9a, 0x4f, 0x4c, 0x74, 0xcd, 0x4b, 0x36, 0xda, 0x59, 0x8b, 0xbc, 0xe9, 0xab, 0x21, 0xd8, 0xa5, + 0x61, 0xea, 0x47, 0xb0, 0x28, 0x17, 0x40, 0x89, 0x97, 0x06, 0x84, 0x7c, 0x23, 0xc0, 0xf1, 0x40, + 0x6d, 0x5d, 0xeb, 0x6a, 0x16, 0x16, 0x6f, 0x42, 0x4e, 0xeb, 0xb9, 0x5b, 0x4e, 0xd7, 0x74, 0xf7, + 0x18, 0x11, 0x75, 0xe9, 0xc7, 0x6f, 0xaf, 0x17, 0xbc, 0x83, 0x60, 0x85, 0x9d, 0x58, 0x1b, 0x6e, + 0xd7, 0xb4, 0x0d, 0x75, 0xa0, 0x2a, 0xbe, 0x09, 0xe9, 0x0e, 0xf5, 0x40, 0x49, 0x9a, 0xa9, 0x49, + 0xa3, 0x60, 0xd9, 0x0a, 0xf5, 0x1c, 0x39, 0x39, 0xd8, 0x69, 0xe0, 0x99, 0xb0, 0x9d, 0x31, 0x70, + 0x46, 0x20, 0x16, 0x86, 0x21, 0x32, 0x5b, 0x65, 0x81, 0x5e, 0x6b, 0xfc, 0x54, 0x00, 0xe6, 0x7b, + 0x06, 0x66, 0xa3, 0xa7, 0x3b, 0xc1, 0xa6, 0x3f, 0x2a, 0x98, 0x7f, 0xe4, 0x30, 0x1d, 0x8b, 0x8a, + 0x0f, 0x53, 0xb9, 0x4e, 0x51, 0xf1, 0x53, 0x63, 0x37, 0xfb, 0x17, 0x02, 0xcc, 0x34, 0xb0, 0xb1, + 0x6e, 0xda, 0xa4, 0x08, 0x8f, 0x9e, 0xb2, 0x37, 0x08, 0x4a, 0x5a, 0xd8, 0x24, 0x69, 0x89, 0x72, + 0xb2, 0x5e, 0xec, 0xef, 0x97, 0x32, 0xac, 0xb2, 0xf1, 0x9f, 0xfb, 0xa5, 0xe3, 0x7b, 0x9a, 0xb5, + 0xbd, 0xac, 0xf8, 0x4a, 0x8a, 0x9a, 0x61, 0xd5, 0x8e, 0xd9, 0x59, 0x30, 0x0c, 0x6d, 0xd6, 0x87, + 0xe6, 0xc7, 0xa5, 0x9c, 0x82, 0x93, 0xdc, 0x30, 0x48, 0xd4, 0x57, 0x02, 0x3d, 0x09, 0xee, 0xd8, + 0x9d, 0x7f, 0x11, 0xc0, 0xc5, 0x51, 0x00, 0xc1, 0x59, 0x32, 0x88, 0xcc, 0x3b, 0x4b, 0x06, 0x13, + 0x01, 0x88, 0x1f, 0x92, 0xb4, 0x63, 0xa3, 0xdd, 0xf4, 0x8a, 0xad, 0x47, 0xf5, 0xbe, 0x47, 0x45, + 0x35, 0xfa, 0xca, 0x48, 0xbc, 0xe0, 0x2b, 0x23, 0xf9, 0x02, 0xaf, 0x0c, 0xf1, 0x2c, 0x40, 0x8f, + 0xe0, 0x67, 0xa1, 0xa4, 0x68, 0x8b, 0x94, 0xeb, 0xf9, 0x8c, 0x0c, 0xba, 0xc6, 0x34, 0xdf, 0x35, + 0x06, 0x0d, 0x61, 0x26, 0xa2, 0x21, 0xcc, 0x1e, 0xa2, 0x0f, 0xc9, 0xbd, 0xdc, 0x86, 0x90, 0x9c, + 0xf9, 0x4e, 0xaf, 0xdb, 0x46, 0x12, 0x78, 0x67, 0x3e, 0x1d, 0x91, 0x56, 0xad, 0xd5, 0x33, 0xb7, + 0xc9, 0x65, 0x30, 0xc3, 0x5a, 0x35, 0x6f, 0x48, 0xae, 0x4f, 0x5a, 0x4e, 0x5b, 0x1a, 0xde, 0x92, + 0xf2, 0xde, 0x4b, 0xc8, 0xd1, 0xd1, 0xdb, 0x1a, 0xde, 0x5a, 0xbe, 0x39, 0x5a, 0x55, 0xe7, 0x87, + 0x1e, 0x65, 0xd1, 0xa5, 0xa2, 0xdc, 0x85, 0x4b, 0xe3, 0x35, 0x8e, 0xd6, 0x43, 0xd6, 0xbe, 0x03, + 0x48, 0x34, 0xb0, 0x21, 0x6e, 0x40, 0x6e, 0xf0, 0xba, 0x8d, 0xa8, 0x03, 0xfe, 0x5d, 0x28, 0x5f, + 0x1a, 0x2f, 0x0f, 0x42, 0xf9, 0x00, 0x4e, 0x46, 0x95, 0x7d, 0x39, 0xd2, 0x3c, 0x42, 0x53, 0xbe, + 0x31, 0xa9, 0x66, 0xb0, 0xa4, 0x0b, 0x85, 0xc8, 0x27, 0xcd, 0x95, 0x49, 0x3d, 0xd5, 0xe4, 0xa5, + 0x89, 0x55, 0x83, 0x55, 0x11, 0x1c, 0x0f, 0x77, 0xe1, 0x17, 0x22, 0xbd, 0x84, 0xb4, 0xe4, 0x6b, + 0x93, 0x68, 0xf1, 0xcb, 0x84, 0x9b, 0xd6, 0xe8, 0x65, 0x42, 0x5a, 0x31, 0xcb, 0xc4, 0xb5, 0x8f, + 0xef, 0xc1, 0x0c, 0xdf, 0x26, 0x2e, 0x46, 0x1a, 0x73, 0x1a, 0x72, 0xf9, 0x20, 0x8d, 0xc0, 0xf5, + 0x5d, 0x00, 0xae, 0xbf, 0x2b, 0x45, 0xda, 0x0d, 0x14, 0xe4, 0xcb, 0x07, 0x28, 0x04, 0x7e, 0x3f, + 0x84, 0xf9, 0xb8, 0xa6, 0xed, 0xda, 0x98, 0xe0, 0x46, 0xb4, 0xe5, 0x57, 0x0f, 0xa3, 0x1d, 0x2c, + 0x7f, 0x1f, 0xf2, 0x43, 0x2d, 0xd2, 0xb9, 0x31, 0x5e, 0x98, 0x8a, 0x7c, 0xe5, 0x40, 0x15, 0xde, + 0xfb, 0x50, 0xcf, 0x12, 0xed, 0x9d, 0x57, 0x89, 0xf1, 0x1e, 0xd9, 0x3f, 0xac, 0x43, 0x36, 0xe8, + 0x13, 0xce, 0x46, 0x9a, 0xf9, 0x62, 0xf9, 0xe2, 0x58, 0x31, 0x9f, 0x64, 0xee, 0xea, 0x8e, 0x4e, + 0xf2, 0x40, 0x21, 0x26, 0xc9, 0xa3, 0x37, 0xaa, 0xf8, 0xa9, 0x00, 0xa7, 0xc7, 0x5d, 0xa7, 0x37, + 0xe2, 0x8f, 0xa5, 0x68, 0x0b, 0xf9, 0xf5, 0xc3, 0x5a, 0xf8, 0xb1, 0xd4, 0x6f, 0x3d, 0xf9, 0xb5, + 0x38, 0xf5, 0xa4, 0x5f, 0x14, 0x9e, 0xf6, 0x8b, 0xc2, 0x2f, 0xfd, 0xa2, 0xf0, 0xf9, 0xb3, 0xe2, + 0xd4, 0xd3, 0x67, 0xc5, 0xa9, 0x9f, 0x9e, 0x15, 0xa7, 0xde, 0xbf, 0xc4, 0x5d, 0x35, 0xab, 0x0e, + 0xb6, 0xee, 0xf9, 0x3f, 0x43, 0xea, 0xd5, 0x5d, 0xf6, 0x73, 0x24, 0xbd, 0x6e, 0x5a, 0x69, 0xfa, + 0xf3, 0xe2, 0x2b, 0x7f, 0x07, 0x00, 0x00, 0xff, 0xff, 0xe9, 0x52, 0x18, 0xa3, 0x28, 0x15, 0x00, + 0x00, } -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 +// 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) } -func (m *MsgMigrateContractResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) +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 dAtA[:n], nil + return out, nil } -func (m *MsgMigrateContractResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +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 (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 +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 len(dAtA) - i, nil + return out, nil } -func (m *MsgUpdateAdmin) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) +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 dAtA[:n], nil + return out, nil } -func (m *MsgUpdateAdmin) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +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 (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 +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 len(dAtA) - i, nil + return out, nil } -func (m *MsgUpdateAdminResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) +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 dAtA[:n], nil + return out, nil } -func (m *MsgUpdateAdminResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +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 (m *MsgUpdateAdminResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, 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 (m *MsgClearAdmin) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) +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 dAtA[:n], nil + return out, nil } -func (m *MsgClearAdmin) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +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 (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 +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 len(dAtA) - i, nil + return out, nil } -func (m *MsgClearAdminResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) +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 dAtA[:n], nil + return out, nil } -func (m *MsgClearAdminResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) +// 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) } -func (m *MsgClearAdminResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - return len(dAtA) - i, nil +// 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 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 (*UnimplementedMsgServer) InstantiateContract(ctx context.Context, req *MsgInstantiateContract) (*MsgInstantiateContractResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method InstantiateContract not implemented") } -func (m *MsgStoreCode) Size() (n int) { - if m == nil { - return 0 + +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 } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if interceptor == nil { + return srv.(MsgServer).StoreCode(ctx, in) } - l = len(m.WASMByteCode) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.wasm.v1.Msg/StoreCode", } - if m.InstantiatePermission != nil { - l = m.InstantiatePermission.Size() - n += 1 + l + sovTx(uint64(l)) + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).StoreCode(ctx, req.(*MsgStoreCode)) } - return n + return interceptor(ctx, in, info, handler) } -func (m *MsgStoreCodeResponse) Size() (n int) { - if m == nil { - return 0 +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 } - var l int - _ = l - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) + if interceptor == nil { + return srv.(MsgServer).InstantiateContract(ctx, in) } - l = len(m.Checksum) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.wasm.v1.Msg/InstantiateContract", } - return n + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).InstantiateContract(ctx, req.(*MsgInstantiateContract)) + } + return interceptor(ctx, in, info, handler) } -func (m *MsgInstantiateContract) Size() (n int) { - if m == nil { - return 0 +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 } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if interceptor == nil { + return srv.(MsgServer).InstantiateContract2(ctx, in) } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.wasm.v1.Msg/InstantiateContract2", } - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).InstantiateContract2(ctx, req.(*MsgInstantiateContract2)) } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + 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 } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if interceptor == nil { + return srv.(MsgServer).ExecuteContract(ctx, in) } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.wasm.v1.Msg/ExecuteContract", } - return n + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).ExecuteContract(ctx, req.(*MsgExecuteContract)) + } + return interceptor(ctx, in, info, handler) } -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)) +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 } - l = len(m.Admin) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if interceptor == nil { + return srv.(MsgServer).MigrateContract(ctx, in) } - if m.CodeID != 0 { - n += 1 + sovTx(uint64(m.CodeID)) + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.wasm.v1.Msg/MigrateContract", } - l = len(m.Label) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).MigrateContract(ctx, req.(*MsgMigrateContract)) } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + 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 len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } + if interceptor == nil { + return srv.(MsgServer).UpdateAdmin(ctx, in) } - l = len(m.Salt) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.wasm.v1.Msg/UpdateAdmin", } - if m.FixMsg { - n += 2 + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateAdmin(ctx, req.(*MsgUpdateAdmin)) } - return n + return interceptor(ctx, in, info, handler) } -func (m *MsgInstantiateContractResponse) Size() (n int) { - if m == nil { - return 0 +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 } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if interceptor == nil { + return srv.(MsgServer).ClearAdmin(ctx, in) } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.wasm.v1.Msg/ClearAdmin", } - return n + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).ClearAdmin(ctx, req.(*MsgClearAdmin)) + } + return interceptor(ctx, in, info, handler) } -func (m *MsgInstantiateContract2Response) Size() (n int) { - if m == nil { - return 0 +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 } - var l int - _ = l - l = len(m.Address) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if interceptor == nil { + return srv.(MsgServer).UpdateInstantiateConfig(ctx, in) } - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.wasm.v1.Msg/UpdateInstantiateConfig", } - return n + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateInstantiateConfig(ctx, req.(*MsgUpdateInstantiateConfig)) + } + return interceptor(ctx, in, info, handler) } -func (m *MsgExecuteContract) Size() (n int) { - if m == nil { - return 0 +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 } - var l int - _ = l - l = len(m.Sender) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + if interceptor == nil { + return srv.(MsgServer).UpdateParams(ctx, in) } - l = len(m.Contract) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmwasm.wasm.v1.Msg/UpdateParams", } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).UpdateParams(ctx, req.(*MsgUpdateParams)) } - if len(m.Funds) > 0 { - for _, e := range m.Funds { - l = e.Size() - n += 1 + l + sovTx(uint64(l)) - } + 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 } - return n + 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 (m *MsgExecuteContractResponse) Size() (n int) { - if m == nil { - return 0 +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 - l = len(m.Data) - if l > 0 { - n += 1 + l + sovTx(uint64(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 } - return n + 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 *MsgMigrateContract) Size() (n int) { - if m == nil { - return 0 +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 - 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 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 { - n += 1 + sovTx(uint64(m.CodeID)) + i = encodeVarintTx(dAtA, i, uint64(m.CodeID)) + i-- + dAtA[i] = 0x8 } - l = len(m.Msg) - if l > 0 { - n += 1 + l + sovTx(uint64(l)) + 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 + } } - 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)) + if iNdEx > l { + return io.ErrUnexpectedEOF } - return n + return nil } -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)) +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 + } } - return n -} -func (m *MsgUpdateAdminResponse) Size() (n int) { - if m == nil { - return 0 + if iNdEx > l { + return io.ErrUnexpectedEOF } - var l int - _ = l - return n + return nil } -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)) +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 + } } - return n -} -func (m *MsgClearAdminResponse) Size() (n int) { - if m == nil { - return 0 + if iNdEx > l { + return io.ErrUnexpectedEOF } - var l int - _ = l - return n + return nil } -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 { +func (m *MsgUpdateInstantiateConfig) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -1947,10 +5546,10 @@ func (m *MsgStoreCode) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgStoreCode: wiretype end group for non-group") + return fmt.Errorf("proto: MsgUpdateInstantiateConfig: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreCode: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgUpdateInstantiateConfig: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -1986,10 +5585,10 @@ func (m *MsgStoreCode) Unmarshal(dAtA []byte) error { m.Sender = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) } - var byteLen int + m.CodeID = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -1999,29 +5598,14 @@ func (m *MsgStoreCode) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= int(b&0x7F) << shift + m.CodeID |= uint64(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: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field NewInstantiatePermission", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -2048,10 +5632,10 @@ func (m *MsgStoreCode) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - if m.InstantiatePermission == nil { - m.InstantiatePermission = &AccessConfig{} + if m.NewInstantiatePermission == nil { + m.NewInstantiatePermission = &AccessConfig{} } - if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + if err := m.NewInstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -2076,7 +5660,8 @@ func (m *MsgStoreCode) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgStoreCodeResponse) Unmarshal(dAtA []byte) error { + +func (m *MsgUpdateInstantiateConfigResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2099,65 +5684,12 @@ func (m *MsgStoreCodeResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgStoreCodeResponse: wiretype end group for non-group") + return fmt.Errorf("proto: MsgUpdateInstantiateConfigResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgStoreCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgUpdateInstantiateConfigResponse: 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:]) @@ -2179,7 +5711,8 @@ func (m *MsgStoreCodeResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgInstantiateContract) Unmarshal(dAtA []byte) error { + +func (m *MsgUpdateParams) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2202,15 +5735,15 @@ func (m *MsgInstantiateContract) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgInstantiateContract: wiretype end group for non-group") + return fmt.Errorf("proto: MsgUpdateParams: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContract: illegal tag %d (wire type %d)", fieldNum, wire) + 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 Sender", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2238,128 +5771,11 @@ func (m *MsgInstantiateContract) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Sender = string(dAtA[iNdEx:postIndex]) + m.Authority = 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) + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) } var msglen int for shift := uint(0); ; shift += 7 { @@ -2386,8 +5802,7 @@ func (m *MsgInstantiateContract) Unmarshal(dAtA []byte) error { 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 { + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { return err } iNdEx = postIndex @@ -2412,7 +5827,8 @@ func (m *MsgInstantiateContract) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgInstantiateContract2) Unmarshal(dAtA []byte) error { + +func (m *MsgUpdateParamsResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2435,47 +5851,66 @@ func (m *MsgInstantiateContract2) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgInstantiateContract2: wiretype end group for non-group") + return fmt.Errorf("proto: MsgUpdateParamsResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContract2: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgUpdateParamsResponse: 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 - } + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err } - intStringLen := int(stringLen) - if intStringLen < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen - if postIndex < 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 postIndex > l { + if iNdEx >= l { return io.ErrUnexpectedEOF } - m.Sender = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: + 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 Admin", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2503,30 +5938,11 @@ func (m *MsgInstantiateContract2) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Admin = string(dAtA[iNdEx:postIndex]) + m.Authority = 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: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2554,9 +5970,9 @@ func (m *MsgInstantiateContract2) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Label = string(dAtA[iNdEx:postIndex]) + m.Contract = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 5: + case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) } @@ -2590,94 +6006,6 @@ func (m *MsgInstantiateContract2) Unmarshal(dAtA []byte) error { 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:]) @@ -2699,7 +6027,8 @@ func (m *MsgInstantiateContract2) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgInstantiateContractResponse) Unmarshal(dAtA []byte) error { + +func (m *MsgSudoContractResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2722,45 +6051,13 @@ func (m *MsgInstantiateContractResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgInstantiateContractResponse: wiretype end group for non-group") + return fmt.Errorf("proto: MsgSudoContractResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) + 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 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) } @@ -2815,7 +6112,8 @@ func (m *MsgInstantiateContractResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgInstantiateContract2Response) Unmarshal(dAtA []byte) error { + +func (m *MsgPinCodes) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2838,15 +6136,15 @@ func (m *MsgInstantiateContract2Response) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgInstantiateContract2Response: wiretype end group for non-group") + return fmt.Errorf("proto: MsgPinCodes: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgInstantiateContract2Response: illegal tag %d (wire type %d)", fieldNum, wire) + 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 Address", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2874,42 +6172,135 @@ func (m *MsgInstantiateContract2Response) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Address = string(dAtA[iNdEx:postIndex]) + m.Authority = 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 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 + } } - if iNdEx >= l { + 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 } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break + 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) } - if byteLen < 0 { - return ErrInvalidLengthTx + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err } - postIndex := iNdEx + byteLen - if postIndex < 0 { + if (skippy < 0) || (iNdEx+skippy) < 0 { return ErrInvalidLengthTx } - if postIndex > l { + if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} + 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 } - iNdEx = postIndex + 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:]) @@ -2931,7 +6322,8 @@ func (m *MsgInstantiateContract2Response) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgExecuteContract) Unmarshal(dAtA []byte) error { + +func (m *MsgUnpinCodes) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2954,15 +6346,15 @@ func (m *MsgExecuteContract) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgExecuteContract: wiretype end group for non-group") + return fmt.Errorf("proto: MsgUnpinCodes: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgExecuteContract: illegal tag %d (wire type %d)", fieldNum, wire) + 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 Sender", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -2990,108 +6382,84 @@ func (m *MsgExecuteContract) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Sender = string(dAtA[iNdEx:postIndex]) + 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 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 + } } - if iNdEx >= l { - return io.ErrUnexpectedEOF + 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 + } } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break + if packedLen < 0 { + return ErrInvalidLengthTx } - } - 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 + postIndex := iNdEx + packedLen + if postIndex < 0 { + return ErrInvalidLengthTx } - if iNdEx >= l { + if postIndex > 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 + var elementCount int + var count int + for _, integer := range dAtA[iNdEx:postIndex] { + if integer < 128 { + count++ + } } - if iNdEx >= l { - return io.ErrUnexpectedEOF + elementCount = count + if elementCount != 0 && len(m.CodeIDs) == 0 { + m.CodeIDs = make([]uint64, 0, elementCount) } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break + 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) } - 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:]) @@ -3113,7 +6481,8 @@ func (m *MsgExecuteContract) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgExecuteContractResponse) Unmarshal(dAtA []byte) error { + +func (m *MsgUnpinCodesResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3136,46 +6505,12 @@ func (m *MsgExecuteContractResponse) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgExecuteContractResponse: wiretype end group for non-group") + return fmt.Errorf("proto: MsgUnpinCodesResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgExecuteContractResponse: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MsgUnpinCodesResponse: 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:]) @@ -3197,7 +6532,8 @@ func (m *MsgExecuteContractResponse) Unmarshal(dAtA []byte) error { } return nil } -func (m *MsgMigrateContract) Unmarshal(dAtA []byte) error { + +func (m *MsgStoreAndInstantiateContract) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3220,15 +6556,15 @@ func (m *MsgMigrateContract) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgMigrateContract: wiretype end group for non-group") + return fmt.Errorf("proto: MsgStoreAndInstantiateContract: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgMigrateContract: illegal tag %d (wire type %d)", fieldNum, wire) + 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 Sender", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Authority", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3256,13 +6592,13 @@ func (m *MsgMigrateContract) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Sender = string(dAtA[iNdEx:postIndex]) + m.Authority = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 2: + case 3: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) } - var stringLen uint64 + var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -3272,29 +6608,67 @@ func (m *MsgMigrateContract) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if byteLen < 0 { return ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - m.Contract = string(dAtA[iNdEx:postIndex]) + m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) + if m.WASMByteCode == nil { + m.WASMByteCode = []byte{} + } iNdEx = postIndex - case 3: + 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 CodeID", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field UnpinCode", wireType) } - m.CodeID = 0 + var v int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -3304,16 +6678,17 @@ func (m *MsgMigrateContract) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.CodeID |= uint64(b&0x7F) << shift + v |= int(b&0x7F) << shift if b < 0x80 { break } } - case 4: + m.UnpinCode = bool(v != 0) + case 6: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) } - var byteLen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -3323,79 +6698,59 @@ func (m *MsgMigrateContract) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if byteLen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthTx } - postIndex := iNdEx + byteLen + postIndex := iNdEx + intStringLen 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{} - } + m.Admin = 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 + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) } - 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 + 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 + } } - if iNdEx >= l { - return io.ErrUnexpectedEOF + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx } - } - 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 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 Data", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) } var byteLen int for shift := uint(0); ; shift += 7 { @@ -3422,64 +6777,48 @@ func (m *MsgMigrateContractResponse) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} + 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 + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Funds", wireType) } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthTx + 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 (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF + if msglen < 0 { + return ErrInvalidLengthTx } - 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 + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx } - if iNdEx >= l { + if postIndex > l { return io.ErrUnexpectedEOF } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break + m.Funds = append(m.Funds, types.Coin{}) + if err := m.Funds[len(m.Funds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err } - } - 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: + iNdEx = postIndex + case 10: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3507,11 +6846,11 @@ func (m *MsgUpdateAdmin) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Sender = string(dAtA[iNdEx:postIndex]) + m.Source = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 2: + case 11: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field NewAdmin", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3539,13 +6878,13 @@ func (m *MsgUpdateAdmin) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.NewAdmin = string(dAtA[iNdEx:postIndex]) + m.Builder = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: + case 12: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) } - var stringLen uint64 + var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -3555,23 +6894,25 @@ func (m *MsgUpdateAdmin) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if byteLen < 0 { return ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - m.Contract = string(dAtA[iNdEx:postIndex]) + m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) + if m.CodeHash == nil { + m.CodeHash = []byte{} + } iNdEx = postIndex default: iNdEx = preIndex @@ -3594,57 +6935,8 @@ func (m *MsgUpdateAdmin) Unmarshal(dAtA []byte) error { } 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 { +func (m *MsgStoreAndInstantiateContractResponse) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3667,15 +6959,15 @@ func (m *MsgClearAdmin) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MsgClearAdmin: wiretype end group for non-group") + return fmt.Errorf("proto: MsgStoreAndInstantiateContractResponse: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MsgClearAdmin: illegal tag %d (wire type %d)", fieldNum, wire) + 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 Sender", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3703,13 +6995,13 @@ func (m *MsgClearAdmin) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.Sender = string(dAtA[iNdEx:postIndex]) + m.Address = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 3: + case 2: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) } - var stringLen uint64 + var byteLen int for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -3719,23 +7011,25 @@ func (m *MsgClearAdmin) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - stringLen |= uint64(b&0x7F) << shift + byteLen |= int(b&0x7F) << shift if b < 0x80 { break } } - intStringLen := int(stringLen) - if intStringLen < 0 { + if byteLen < 0 { return ErrInvalidLengthTx } - postIndex := iNdEx + intStringLen + postIndex := iNdEx + byteLen if postIndex < 0 { return ErrInvalidLengthTx } if postIndex > l { return io.ErrUnexpectedEOF } - m.Contract = string(dAtA[iNdEx:postIndex]) + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } iNdEx = postIndex default: iNdEx = preIndex @@ -3758,56 +7052,7 @@ func (m *MsgClearAdmin) Unmarshal(dAtA []byte) error { } 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 skipTx(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/wasm/types/tx_test.go b/x/wasm/types/tx_test.go index a3c29b4..355beae 100644 --- a/x/wasm/types/tx_test.go +++ b/x/wasm/types/tx_test.go @@ -5,9 +5,8 @@ import ( "strings" "testing" - "github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx" - 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" ) @@ -15,7 +14,7 @@ import ( const firstCodeID = 1 func TestStoreCodeValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHex("012345") + bad, err := sdk.AccAddressFromHexUnsafe("012345") require.NoError(t, err) badAddress := bad.String() // proper address size @@ -79,7 +78,7 @@ func TestStoreCodeValidation(t *testing.T) { } func TestInstantiateContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHex("012345") + bad, err := sdk.AccAddressFromHexUnsafe("012345") require.NoError(t, err) badAddress := bad.String() // proper address size @@ -187,7 +186,7 @@ func TestInstantiateContractValidation(t *testing.T) { } func TestInstantiateContract2Validation(t *testing.T) { - bad, err := sdk.AccAddressFromHex("012345") + bad, err := sdk.AccAddressFromHexUnsafe("012345") require.NoError(t, err) badAddress := bad.String() // proper address size @@ -323,7 +322,7 @@ func TestInstantiateContract2Validation(t *testing.T) { } func TestExecuteContractValidation(t *testing.T) { - bad, err := sdk.AccAddressFromHex("012345") + bad, err := sdk.AccAddressFromHexUnsafe("012345") require.NoError(t, err) badAddress := bad.String() // proper address size @@ -432,7 +431,7 @@ func TestExecuteContractValidation(t *testing.T) { } func TestMsgUpdateAdministrator(t *testing.T) { - bad, err := sdk.AccAddressFromHex("012345") + bad, err := sdk.AccAddressFromHexUnsafe("012345") require.NoError(t, err) badAddress := bad.String() // proper address size @@ -504,7 +503,7 @@ func TestMsgUpdateAdministrator(t *testing.T) { } func TestMsgClearAdministrator(t *testing.T) { - bad, err := sdk.AccAddressFromHex("012345") + bad, err := sdk.AccAddressFromHexUnsafe("012345") require.NoError(t, err) badAddress := bad.String() // proper address size @@ -555,7 +554,7 @@ func TestMsgClearAdministrator(t *testing.T) { } func TestMsgMigrateContract(t *testing.T) { - bad, err := sdk.AccAddressFromHex("012345") + bad, err := sdk.AccAddressFromHexUnsafe("012345") require.NoError(t, err) badAddress := bad.String() // proper address size @@ -679,3 +678,462 @@ func TestMsgJsonSignBytes(t *testing.T) { }) } } + +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 index 4a0e198..ffec304 100644 --- a/x/wasm/types/types.go +++ b/x/wasm/types/types.go @@ -4,11 +4,12 @@ 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/gogo/protobuf/proto" + "github.com/cosmos/gogoproto/proto" ) const ( @@ -24,20 +25,20 @@ const ( func (m Model) ValidateBasic() error { if len(m.Key) == 0 { - return sdkerrors.Wrap(ErrEmpty, "key") + return errorsmod.Wrap(ErrEmpty, "key") } return nil } func (c CodeInfo) ValidateBasic() error { if len(c.CodeHash) == 0 { - return sdkerrors.Wrap(ErrEmpty, "code hash") + return errorsmod.Wrap(ErrEmpty, "code hash") } if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { - return sdkerrors.Wrap(err, "creator") + return errorsmod.Wrap(err, "creator") } if err := c.InstantiateConfig.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "instantiate config") + return errorsmod.Wrap(err, "instantiate config") } return nil } @@ -78,18 +79,18 @@ type validatable interface { // but also in the genesis import process. func (c *ContractInfo) ValidateBasic() error { if c.CodeID == 0 { - return sdkerrors.Wrap(ErrEmpty, "code id") + return errorsmod.Wrap(ErrEmpty, "code id") } if _, err := sdk.AccAddressFromBech32(c.Creator); err != nil { - return sdkerrors.Wrap(err, "creator") + return errorsmod.Wrap(err, "creator") } if len(c.Admin) != 0 { if _, err := sdk.AccAddressFromBech32(c.Admin); err != nil { - return sdkerrors.Wrap(err, "admin") + return errorsmod.Wrap(err, "admin") } } if err := ValidateLabel(c.Label); err != nil { - return sdkerrors.Wrap(err, "label") + return errorsmod.Wrap(err, "label") } if c.Extension == nil { return nil @@ -100,7 +101,7 @@ func (c *ContractInfo) ValidateBasic() error { return nil } if err := e.ValidateBasic(); err != nil { - return sdkerrors.Wrap(err, "extension") + return errorsmod.Wrap(err, "extension") } return nil } @@ -117,12 +118,12 @@ func (c *ContractInfo) SetExtension(ext ContractInfoExtension) error { return err } } - any, err := codectypes.NewAnyWithValue(ext) + codecAny, err := codectypes.NewAnyWithValue(ext) if err != nil { - return sdkerrors.Wrap(sdkerrors.ErrPackAny, err.Error()) + return errorsmod.Wrap(sdkerrors.ErrPackAny, err.Error()) } - c.Extension = any + c.Extension = codecAny return nil } @@ -131,12 +132,12 @@ func (c *ContractInfo) SetExtension(ext ContractInfoExtension) error { // // var d MyContractDetails // if err := info.ReadExtension(&d); err != nil { -// return nil, sdkerrors.Wrap(err, "extension") +// 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 sdkerrors.Wrap(sdkerrors.ErrInvalidType, "not a pointer") + return errorsmod.Wrap(sdkerrors.ErrInvalidType, "not a pointer") } if c.Extension == nil { return nil @@ -145,7 +146,7 @@ func (c *ContractInfo) ReadExtension(e ContractInfoExtension) error { cached := c.Extension.GetCachedValue() elem := reflect.ValueOf(cached).Elem() if !elem.Type().AssignableTo(rv.Elem().Type()) { - return sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "extension is of type %s but argument of %s", elem.Type(), 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 @@ -261,7 +262,7 @@ func (c ContractCodeHistoryEntry) ValidateBasic() error { if c.Updated == nil { return ErrEmpty.Wrap("updated") } - return sdkerrors.Wrap(c.Msg.ValidateBasic(), "msg") + return errorsmod.Wrap(c.Msg.ValidateBasic(), "msg") } // NewEnv initializes the environment for a contract instance @@ -315,11 +316,11 @@ func NewWasmCoins(cosmosCoins sdk.Coins) (wasmCoins []wasmvmtypes.Coin) { 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 - // SimulationGasLimit is the max gas to be used in a smart query contract call - SmartQueryGasLimit uint64 + 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 + MemoryCacheSize uint32 `mapstructure:"memory_cache_size"` // ContractDebugMode log what contract print ContractDebugMode bool } @@ -333,6 +334,33 @@ func DefaultWasmConfig() WasmConfig { } } +// 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 { @@ -396,3 +424,14 @@ func isSubset(super, sub []string) bool { } 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 index 6b6bf90..37ebd05 100644 --- a/x/wasm/types/types.pb.go +++ b/x/wasm/types/types.pb.go @@ -6,20 +6,24 @@ package types import ( bytes "bytes" fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - types "github.com/cosmos/cosmos-sdk/codec/types" - _ "github.com/cosmos/gogoproto/gogoproto" - proto "github.com/gogo/protobuf/proto" - github_com_tendermint_tendermint_libs_bytes "github.com/tendermint/tendermint/libs/bytes" 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 -var _ = fmt.Errorf -var _ = math.Inf +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. @@ -111,9 +115,11 @@ 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) @@ -126,12 +132,15 @@ func (m *AccessTypeParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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) } @@ -153,9 +162,11 @@ 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) @@ -168,12 +179,15 @@ func (m *AccessConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) 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) } @@ -191,9 +205,11 @@ 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) @@ -206,12 +222,15 @@ 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) } @@ -234,9 +253,11 @@ 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) @@ -249,12 +270,15 @@ func (m *CodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 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) } @@ -285,9 +309,11 @@ 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) @@ -300,12 +326,15 @@ func (m *ContractInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) 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) } @@ -328,9 +357,11 @@ 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) @@ -343,12 +374,15 @@ func (m *ContractCodeHistoryEntry) XXX_Marshal(b []byte, deterministic bool) ([] 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) } @@ -371,9 +405,11 @@ 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) @@ -386,12 +422,15 @@ func (m *AbsoluteTxPosition) XXX_Marshal(b []byte, deterministic bool) ([]byte, 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) } @@ -401,7 +440,7 @@ 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_tendermint_tendermint_libs_bytes.HexBytes `protobuf:"bytes,1,opt,name=key,proto3,casttype=github.com/tendermint/tendermint/libs/bytes.HexBytes" json:"key,omitempty"` + 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"` } @@ -412,9 +451,11 @@ 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) @@ -427,12 +468,15 @@ func (m *Model) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 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) } @@ -455,81 +499,83 @@ func init() { func init() { proto.RegisterFile("cosmwasm/wasm/v1/types.proto", fileDescriptor_e6155d98fa173e02) } var fileDescriptor_e6155d98fa173e02 = []byte{ - // 1181 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, 0x5d, 0x9a, 0x0d, 0xab, 0x24, 0x35, 0x45, - 0x6c, 0x3f, 0x36, 0xa1, 0x0b, 0x02, 0xd4, 0x43, 0xa5, 0x38, 0x71, 0xbb, 0xae, 0xd8, 0x38, 0x9a, - 0xa4, 0xa0, 0x45, 0xaa, 0x2c, 0xc7, 0x9e, 0xcd, 0x5a, 0x75, 0x3c, 0x91, 0x67, 0xb2, 0x8d, 0xff, - 0x03, 0x14, 0x09, 0xc1, 0x91, 0x4b, 0x24, 0x04, 0x08, 0x95, 0x3b, 0x57, 0xee, 0x15, 0x5c, 0x7a, - 0xe4, 0x14, 0xc1, 0xf6, 0xc2, 0x39, 0xc7, 0x72, 0x41, 0x9e, 0x49, 0x1a, 0xf7, 0x73, 0xc3, 0xc5, - 0x9a, 0x79, 0xef, 0xfd, 0x7e, 0xef, 0xbd, 0xdf, 0xcc, 0x1b, 0x19, 0x6c, 0xd9, 0x84, 0x76, 0xef, - 0x5b, 0xb4, 0x5b, 0xe6, 0x9f, 0xe3, 0x6b, 0x65, 0x16, 0xf6, 0x30, 0x2d, 0xf5, 0x02, 0xc2, 0x08, - 0x94, 0x67, 0xde, 0x12, 0xff, 0x1c, 0x5f, 0xcb, 0x6d, 0x46, 0x16, 0x42, 0x4d, 0xee, 0x2f, 0x8b, - 0x8d, 0x08, 0xce, 0xad, 0x77, 0x48, 0x87, 0x08, 0x7b, 0xb4, 0x9a, 0x5a, 0x37, 0x3b, 0x84, 0x74, - 0x3c, 0x5c, 0xe6, 0xbb, 0x76, 0xff, 0xb0, 0x6c, 0xf9, 0xa1, 0x70, 0x29, 0x77, 0xc1, 0x9b, 0x15, - 0xdb, 0xc6, 0x94, 0xb6, 0xc2, 0x1e, 0x6e, 0x58, 0x81, 0xd5, 0x85, 0x35, 0xb0, 0x74, 0x6c, 0x79, - 0x7d, 0x9c, 0x95, 0x8a, 0xd2, 0xf6, 0xd9, 0xdd, 0xad, 0xd2, 0xf3, 0x05, 0x94, 0xe6, 0x08, 0x55, - 0x9e, 0x8c, 0x0b, 0x6b, 0xa1, 0xd5, 0xf5, 0xae, 0x2b, 0x1c, 0xa4, 0x20, 0x01, 0xbe, 0x9e, 0xfe, - 0xee, 0xfb, 0x82, 0xa4, 0xfc, 0x21, 0x81, 0x35, 0x11, 0x5d, 0x25, 0xfe, 0xa1, 0xdb, 0x81, 0x4d, - 0x00, 0x7a, 0x38, 0xe8, 0xba, 0x94, 0xba, 0xc4, 0x5f, 0x28, 0xc3, 0xc6, 0x64, 0x5c, 0x38, 0x27, - 0x32, 0xcc, 0x91, 0x0a, 0x8a, 0xd1, 0xc0, 0xab, 0x60, 0xc5, 0x72, 0x9c, 0x00, 0x53, 0x9a, 0x4d, - 0x16, 0xa5, 0xed, 0x8c, 0x0a, 0x27, 0xe3, 0xc2, 0x59, 0x81, 0x99, 0x3a, 0x14, 0x34, 0x0b, 0x81, - 0xbb, 0x20, 0x33, 0x5d, 0x62, 0x9a, 0x4d, 0x15, 0x53, 0xdb, 0x19, 0x75, 0x7d, 0x32, 0x2e, 0xc8, - 0xcf, 0xc4, 0x63, 0xaa, 0xa0, 0x79, 0xd8, 0xb4, 0x9b, 0x6f, 0x92, 0x60, 0x99, 0x6b, 0x44, 0x21, - 0x01, 0xd0, 0x26, 0x0e, 0x36, 0xfb, 0x3d, 0x8f, 0x58, 0x8e, 0x69, 0xf1, 0x7a, 0x79, 0x3f, 0x67, - 0x76, 0xf3, 0xaf, 0xea, 0x47, 0x68, 0xa0, 0x5e, 0x78, 0x38, 0x2e, 0x24, 0x26, 0xe3, 0xc2, 0xa6, - 0xc8, 0xf8, 0x22, 0x8f, 0x82, 0xe4, 0xc8, 0x78, 0x87, 0xdb, 0x04, 0x14, 0x7e, 0x2d, 0x81, 0xbc, - 0xeb, 0x53, 0x66, 0xf9, 0xcc, 0xb5, 0x18, 0x36, 0x1d, 0x7c, 0x68, 0xf5, 0x3d, 0x66, 0xc6, 0xd4, - 0x4c, 0x2e, 0xa0, 0xe6, 0xa5, 0xc9, 0xb8, 0xf0, 0x9e, 0xc8, 0xfb, 0x7a, 0x36, 0x05, 0x6d, 0xc5, - 0x02, 0x6a, 0xc2, 0xdf, 0x78, 0xea, 0xe6, 0x8a, 0x24, 0x94, 0x1f, 0x24, 0xb0, 0x5a, 0x25, 0x0e, - 0xd6, 0xfd, 0x43, 0x02, 0xdf, 0x01, 0x19, 0xde, 0xcb, 0x91, 0x45, 0x8f, 0xb8, 0x14, 0x6b, 0x68, - 0x35, 0x32, 0xec, 0x59, 0xf4, 0x08, 0x66, 0xc1, 0x8a, 0x1d, 0x60, 0x8b, 0x91, 0x40, 0x9c, 0x11, - 0x9a, 0x6d, 0x61, 0x13, 0xc0, 0x78, 0x29, 0x36, 0x17, 0x29, 0xbb, 0xb4, 0x90, 0x94, 0xe9, 0x48, - 0x4a, 0x74, 0x2e, 0x86, 0x17, 0x8e, 0xdb, 0xe9, 0xd5, 0x94, 0x9c, 0xbe, 0x9d, 0x5e, 0x4d, 0xcb, - 0x4b, 0xca, 0x6f, 0x49, 0xb0, 0x56, 0x25, 0x3e, 0x0b, 0x2c, 0x9b, 0xf1, 0x42, 0xdf, 0x05, 0x2b, - 0xbc, 0x50, 0xd7, 0xe1, 0x65, 0xa6, 0x55, 0x70, 0x32, 0x2e, 0x2c, 0xf3, 0x3e, 0x6a, 0x68, 0x39, - 0x72, 0xe9, 0xce, 0x6b, 0x0a, 0x5e, 0x07, 0x4b, 0x96, 0xd3, 0x75, 0xfd, 0x6c, 0x8a, 0xdb, 0xc5, - 0x26, 0xb2, 0x7a, 0x56, 0x1b, 0x7b, 0xd9, 0xb4, 0xb0, 0xf2, 0x0d, 0xbc, 0x31, 0x65, 0xc1, 0xce, - 0xb4, 0xa3, 0x8b, 0x2f, 0xe9, 0xa8, 0x4d, 0x89, 0xd7, 0x67, 0xb8, 0x35, 0x68, 0x10, 0xea, 0x32, - 0x97, 0xf8, 0x68, 0x06, 0x82, 0x3b, 0xe0, 0x8c, 0xdb, 0xb6, 0xcd, 0x1e, 0x09, 0x58, 0x54, 0xee, - 0x32, 0xbf, 0xde, 0x6f, 0x9c, 0x8c, 0x0b, 0x19, 0x5d, 0xad, 0x36, 0x48, 0xc0, 0xf4, 0x1a, 0xca, - 0xb8, 0x6d, 0x9b, 0x2f, 0x1d, 0xb8, 0x0f, 0x32, 0x78, 0xc0, 0xb0, 0xcf, 0xef, 0xc3, 0x0a, 0x4f, - 0xb8, 0x5e, 0x12, 0xd3, 0x5f, 0x9a, 0x4d, 0x7f, 0xa9, 0xe2, 0x87, 0xea, 0xe6, 0xef, 0xbf, 0xee, - 0x6c, 0xc4, 0x45, 0xd1, 0x66, 0x30, 0x34, 0x67, 0xb8, 0x9e, 0xfe, 0x27, 0xba, 0xf6, 0xff, 0x4a, - 0x20, 0x3b, 0x0b, 0x8d, 0x44, 0xda, 0x73, 0x29, 0x23, 0x41, 0xa8, 0xf9, 0x2c, 0x08, 0x61, 0x03, - 0x64, 0x48, 0x0f, 0x07, 0x16, 0x9b, 0xcf, 0xf3, 0xee, 0x8b, 0x2d, 0xbe, 0x04, 0x6e, 0xcc, 0x50, - 0xd1, 0xbd, 0x44, 0x73, 0x92, 0xf8, 0xe9, 0x24, 0x5f, 0x79, 0x3a, 0x37, 0xc0, 0x4a, 0xbf, 0xe7, - 0x70, 0x5d, 0x53, 0xff, 0x47, 0xd7, 0x29, 0x08, 0x6e, 0x83, 0x54, 0x97, 0x76, 0xf8, 0x59, 0xad, - 0xa9, 0x6f, 0x3f, 0x19, 0x17, 0x20, 0xb2, 0xee, 0xcf, 0xaa, 0xdc, 0xc7, 0x94, 0x5a, 0x1d, 0x8c, - 0xa2, 0x10, 0x05, 0x01, 0xf8, 0x22, 0x11, 0xbc, 0x00, 0xd6, 0xda, 0x1e, 0xb1, 0xef, 0x99, 0x47, - 0xd8, 0xed, 0x1c, 0x31, 0x71, 0x8f, 0xd0, 0x19, 0x6e, 0xdb, 0xe3, 0x26, 0xb8, 0x09, 0x56, 0xd9, - 0xc0, 0x74, 0x7d, 0x07, 0x0f, 0x44, 0x23, 0x68, 0x85, 0x0d, 0xf4, 0x68, 0xab, 0xb8, 0x60, 0x69, - 0x9f, 0x38, 0xd8, 0x83, 0xb7, 0x41, 0xea, 0x1e, 0x0e, 0xc5, 0xb0, 0xa8, 0x9f, 0x3e, 0x19, 0x17, - 0x3e, 0xea, 0xb8, 0xec, 0xa8, 0xdf, 0x2e, 0xd9, 0xa4, 0x5b, 0x66, 0xd8, 0x77, 0xa2, 0x81, 0xf3, - 0x59, 0x7c, 0xe9, 0xb9, 0x6d, 0x5a, 0x6e, 0x87, 0x0c, 0xd3, 0xd2, 0x1e, 0x1e, 0xa8, 0xd1, 0x02, - 0x45, 0x24, 0xd1, 0x05, 0x14, 0xef, 0x76, 0x92, 0x8f, 0x9e, 0xd8, 0x5c, 0xfe, 0x25, 0x09, 0xc0, - 0x7c, 0xfe, 0xe1, 0xc7, 0xe0, 0x7c, 0xa5, 0x5a, 0xd5, 0x9a, 0x4d, 0xb3, 0x75, 0xd0, 0xd0, 0xcc, - 0x3b, 0xf5, 0x66, 0x43, 0xab, 0xea, 0x37, 0x75, 0xad, 0x26, 0x27, 0x72, 0x9b, 0xc3, 0x51, 0x71, - 0x63, 0x1e, 0x7c, 0xc7, 0xa7, 0x3d, 0x6c, 0xbb, 0x87, 0x2e, 0x76, 0xe0, 0x55, 0x00, 0xe3, 0xb8, - 0xba, 0xa1, 0x1a, 0xb5, 0x03, 0x59, 0xca, 0xad, 0x0f, 0x47, 0x45, 0x79, 0x0e, 0xa9, 0x93, 0x36, - 0x71, 0x42, 0xf8, 0x09, 0xc8, 0xc6, 0xa3, 0x8d, 0xfa, 0x67, 0x07, 0x66, 0xa5, 0x56, 0x43, 0x5a, - 0xb3, 0x29, 0x27, 0x9f, 0x4f, 0x63, 0xf8, 0x5e, 0x58, 0x79, 0xfa, 0x36, 0x6f, 0xc4, 0x81, 0xda, - 0xe7, 0x1a, 0x3a, 0xe0, 0x99, 0x52, 0xb9, 0xf3, 0xc3, 0x51, 0xf1, 0xad, 0x39, 0x4a, 0x3b, 0xc6, - 0x41, 0xc8, 0x93, 0xdd, 0x00, 0x5b, 0x71, 0x4c, 0xa5, 0x7e, 0x60, 0x1a, 0x37, 0x67, 0xe9, 0xb4, - 0xa6, 0x9c, 0xce, 0x6d, 0x0d, 0x47, 0xc5, 0xec, 0x1c, 0x5a, 0xf1, 0x43, 0xe3, 0xb0, 0x32, 0x7b, - 0xdb, 0x73, 0xab, 0x5f, 0xfd, 0x98, 0x4f, 0x3c, 0xf8, 0x29, 0x9f, 0xb8, 0xfc, 0x73, 0x0a, 0x14, - 0x4f, 0xbb, 0xa9, 0x10, 0x83, 0x0f, 0xaa, 0x46, 0xbd, 0x85, 0x2a, 0xd5, 0x96, 0x59, 0x35, 0x6a, - 0x9a, 0xb9, 0xa7, 0x37, 0x5b, 0x06, 0x3a, 0x30, 0x8d, 0x86, 0x86, 0x2a, 0x2d, 0xdd, 0xa8, 0xbf, - 0x4c, 0xda, 0xf2, 0x70, 0x54, 0xbc, 0x72, 0x1a, 0x77, 0x5c, 0xf0, 0x2f, 0xc0, 0xa5, 0x85, 0xd2, - 0xe8, 0x75, 0xbd, 0x25, 0x4b, 0xb9, 0xed, 0xe1, 0xa8, 0x78, 0xf1, 0x34, 0x7e, 0xdd, 0x77, 0x19, - 0xbc, 0x0b, 0xae, 0x2e, 0x44, 0xbc, 0xaf, 0xdf, 0x42, 0x95, 0x96, 0x26, 0x27, 0x73, 0x57, 0x86, - 0xa3, 0xe2, 0xfb, 0xa7, 0x71, 0xef, 0xbb, 0x9d, 0xc0, 0x62, 0x78, 0x61, 0xfa, 0x5b, 0x5a, 0x5d, - 0x6b, 0xea, 0x4d, 0x39, 0xb5, 0x18, 0xfd, 0x2d, 0xec, 0x63, 0xea, 0xd2, 0x5c, 0x3a, 0x3a, 0x2c, - 0xd5, 0x78, 0xf8, 0x77, 0x3e, 0xf1, 0xe0, 0x24, 0x2f, 0x3d, 0x3c, 0xc9, 0x4b, 0x8f, 0x4e, 0xf2, - 0xd2, 0x5f, 0x27, 0x79, 0xe9, 0xdb, 0xc7, 0xf9, 0xc4, 0xa3, 0xc7, 0xf9, 0xc4, 0x9f, 0x8f, 0xf3, - 0x89, 0x2f, 0x77, 0x9e, 0x99, 0xa3, 0xa0, 0xe7, 0x63, 0x76, 0x9f, 0x04, 0xf7, 0xf8, 0x7a, 0xc7, - 0x26, 0x01, 0x2e, 0x0f, 0xc4, 0xdf, 0x16, 0xff, 0xd5, 0x6a, 0x2f, 0xf3, 0xc7, 0xf1, 0xc3, 0xff, - 0x02, 0x00, 0x00, 0xff, 0xff, 0xf0, 0xa0, 0xa0, 0x8e, 0x8b, 0x09, 0x00, 0x00, + // 1201 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x56, 0xcf, 0x8f, 0xdb, 0xc4, + 0x17, 0x8f, 0x93, 0xec, 0x8f, 0x4c, 0xf7, 0xdb, 0xaf, 0x3b, 0x6c, 0x69, 0x36, 0xac, 0x92, 0x60, + 0x4a, 0xd9, 0x6e, 0xdb, 0xa4, 0x5d, 0x10, 0x48, 0x3d, 0x54, 0xca, 0x0f, 0xb7, 0xeb, 0x8a, 0x4d, + 0xa2, 0x49, 0x4a, 0x59, 0xa4, 0x62, 0x39, 0xf6, 0x24, 0x6b, 0x35, 0xf1, 0x44, 0x9e, 0xc9, 0x36, + 0xfe, 0x0f, 0x50, 0x24, 0x24, 0x0e, 0x1c, 0xb8, 0x44, 0x42, 0x02, 0x41, 0xb9, 0x71, 0xe0, 0x8f, + 0xa8, 0x40, 0x42, 0x3d, 0x72, 0x8a, 0x60, 0x7b, 0x80, 0x73, 0x8e, 0xe5, 0x82, 0x3c, 0x13, 0xd7, + 0xa6, 0xed, 0x76, 0xc3, 0xc5, 0x9a, 0x79, 0xef, 0x7d, 0x3e, 0xef, 0xbd, 0xcf, 0xcc, 0x3c, 0x19, + 0x6c, 0x9a, 0x84, 0xf6, 0x1f, 0x18, 0xb4, 0x5f, 0xe4, 0x9f, 0xc3, 0x6b, 0x45, 0xe6, 0x0d, 0x30, + 0x2d, 0x0c, 0x5c, 0xc2, 0x08, 0x94, 0x03, 0x6f, 0x81, 0x7f, 0x0e, 0xaf, 0x65, 0x36, 0x7c, 0x0b, + 0xa1, 0x3a, 0xf7, 0x17, 0xc5, 0x46, 0x04, 0x67, 0xd6, 0xbb, 0xa4, 0x4b, 0x84, 0xdd, 0x5f, 0xcd, + 0xad, 0x1b, 0x5d, 0x42, 0xba, 0x3d, 0x5c, 0xe4, 0xbb, 0xf6, 0xb0, 0x53, 0x34, 0x1c, 0x6f, 0xee, + 0x3a, 0x63, 0xf4, 0x6d, 0x87, 0x14, 0xf9, 0x57, 0x98, 0x94, 0x7b, 0xe0, 0xff, 0x25, 0xd3, 0xc4, + 0x94, 0xb6, 0xbc, 0x01, 0x6e, 0x18, 0xae, 0xd1, 0x87, 0x55, 0xb0, 0x74, 0x68, 0xf4, 0x86, 0x38, + 0x2d, 0xe5, 0xa5, 0xad, 0xd3, 0x3b, 0x9b, 0x85, 0xe7, 0x6b, 0x2a, 0x84, 0x88, 0xb2, 0x3c, 0x9b, + 0xe6, 0xd6, 0x3c, 0xa3, 0xdf, 0xbb, 0xae, 0x70, 0x90, 0x82, 0x04, 0xf8, 0x7a, 0xf2, 0xab, 0xaf, + 0x73, 0x92, 0xf2, 0x8b, 0x04, 0xd6, 0x44, 0x74, 0x85, 0x38, 0x1d, 0xbb, 0x0b, 0x9b, 0x00, 0x0c, + 0xb0, 0xdb, 0xb7, 0x29, 0xb5, 0x89, 0xb3, 0x50, 0x86, 0xb3, 0xb3, 0x69, 0xee, 0x8c, 0xc8, 0x10, + 0x22, 0x15, 0x14, 0xa1, 0x81, 0x97, 0xc1, 0x8a, 0x61, 0x59, 0x2e, 0xa6, 0x34, 0x1d, 0xcf, 0x4b, + 0x5b, 0xa9, 0x32, 0x9c, 0x4d, 0x73, 0xa7, 0x05, 0x66, 0xee, 0x50, 0x50, 0x10, 0x02, 0x77, 0x40, + 0x6a, 0xbe, 0xc4, 0x34, 0x9d, 0xc8, 0x27, 0xb6, 0x52, 0xe5, 0xf5, 0xd9, 0x34, 0x27, 0xff, 0x2b, + 0x1e, 0x53, 0x05, 0x85, 0x61, 0xf3, 0x6e, 0xbe, 0x8c, 0x83, 0x65, 0xae, 0x11, 0x85, 0x0c, 0x40, + 0x93, 0x58, 0x58, 0x1f, 0x0e, 0x7a, 0xc4, 0xb0, 0x74, 0x83, 0xd7, 0xcb, 0xfb, 0x39, 0xb5, 0x93, + 0x3d, 0xae, 0x1f, 0xa1, 0x41, 0xf9, 0xc2, 0xa3, 0x69, 0x2e, 0x36, 0x9b, 0xe6, 0x36, 0x44, 0xc6, + 0x17, 0x79, 0x94, 0x87, 0x7f, 0xfe, 0xb8, 0x2d, 0x21, 0xd9, 0xf7, 0xdc, 0xe1, 0x0e, 0x81, 0x87, + 0x9f, 0x4b, 0x20, 0x6b, 0x3b, 0x94, 0x19, 0x0e, 0xb3, 0x0d, 0x86, 0x75, 0x0b, 0x77, 0x8c, 0x61, + 0x8f, 0xe9, 0x11, 0x49, 0xe3, 0x0b, 0x48, 0x7a, 0x71, 0x36, 0xcd, 0xbd, 0x2d, 0x92, 0xbf, 0x9a, + 0x4d, 0x41, 0x9b, 0x91, 0x80, 0xaa, 0xf0, 0x37, 0x9e, 0xb9, 0xb9, 0x2c, 0x31, 0xe5, 0x7b, 0x09, + 0xac, 0x56, 0x88, 0x85, 0x35, 0xa7, 0x43, 0xe0, 0x1b, 0x20, 0xc5, 0x1b, 0x3a, 0x30, 0xe8, 0x01, + 0xd7, 0x63, 0x0d, 0xad, 0xfa, 0x86, 0x5d, 0x83, 0x1e, 0xc0, 0x34, 0x58, 0x31, 0x5d, 0x6c, 0x30, + 0xe2, 0x8a, 0x83, 0x42, 0xc1, 0x16, 0x7e, 0x0c, 0x60, 0xb4, 0x14, 0x93, 0x2b, 0x95, 0x5e, 0x5a, + 0x48, 0xcf, 0x94, 0xaf, 0xa7, 0x90, 0xec, 0x4c, 0x84, 0x44, 0x78, 0x6f, 0x27, 0x57, 0x13, 0x72, + 0xf2, 0x76, 0x72, 0x35, 0x29, 0x2f, 0x29, 0xbf, 0xc6, 0xc1, 0x5a, 0x85, 0x38, 0xcc, 0x35, 0x4c, + 0xc6, 0xab, 0x7d, 0x0b, 0xac, 0xf0, 0x6a, 0x6d, 0x8b, 0xd7, 0x9a, 0x2c, 0x83, 0xa3, 0x69, 0x6e, + 0x99, 0x37, 0x53, 0x45, 0xcb, 0xbe, 0x4b, 0xb3, 0x5e, 0x51, 0xf5, 0x3a, 0x58, 0x32, 0xac, 0xbe, + 0xed, 0xa4, 0x13, 0xdc, 0x2e, 0x36, 0xbe, 0xb5, 0x67, 0xb4, 0x71, 0x2f, 0x9d, 0x14, 0x56, 0xbe, + 0x81, 0x37, 0xe6, 0x2c, 0xd8, 0x9a, 0xb7, 0x75, 0xfe, 0x25, 0x6d, 0xb5, 0x29, 0xe9, 0x0d, 0x19, + 0x6e, 0x8d, 0x1a, 0x84, 0xda, 0xcc, 0x26, 0x0e, 0x0a, 0x40, 0xf0, 0x0a, 0x38, 0x65, 0xb7, 0x4d, + 0x7d, 0x40, 0x5c, 0xe6, 0x97, 0xbb, 0xcc, 0x2f, 0xfa, 0xff, 0x8e, 0xa6, 0xb9, 0x94, 0x56, 0xae, + 0x34, 0x88, 0xcb, 0xb4, 0x2a, 0x4a, 0xd9, 0x6d, 0x93, 0x2f, 0x2d, 0xf8, 0x29, 0x48, 0xe1, 0x11, + 0xc3, 0x0e, 0xbf, 0x14, 0x2b, 0x3c, 0xe1, 0x7a, 0x41, 0x8c, 0x86, 0x42, 0x30, 0x1a, 0x0a, 0x25, + 0xc7, 0x2b, 0x6f, 0xff, 0xfc, 0xd3, 0x95, 0x0b, 0x2f, 0x54, 0x12, 0x55, 0x49, 0x0d, 0x78, 0x50, + 0x48, 0x79, 0x3d, 0xf9, 0x97, 0xff, 0x22, 0xfe, 0x96, 0x40, 0x3a, 0x08, 0xf5, 0x55, 0xdb, 0xb5, + 0x29, 0x23, 0xae, 0xa7, 0x3a, 0xcc, 0xf5, 0x60, 0x03, 0xa4, 0xc8, 0x00, 0xbb, 0x06, 0x0b, 0x9f, + 0xfa, 0x4e, 0xe1, 0xd8, 0x4c, 0x11, 0x78, 0x3d, 0x40, 0xf9, 0xb7, 0x15, 0x85, 0x24, 0xd1, 0xe3, + 0x8a, 0x1f, 0x7b, 0x5c, 0x37, 0xc0, 0xca, 0x70, 0x60, 0x71, 0xa1, 0x13, 0xff, 0x45, 0xe8, 0x39, + 0x08, 0x6e, 0x81, 0x44, 0x9f, 0x76, 0xf9, 0xe1, 0xad, 0x95, 0x5f, 0x7f, 0x3a, 0xcd, 0x41, 0x64, + 0x3c, 0x08, 0xaa, 0xdc, 0xc3, 0x94, 0x1a, 0x5d, 0x8c, 0xfc, 0x10, 0x05, 0x01, 0xf8, 0x22, 0x11, + 0x7c, 0x13, 0xac, 0xb5, 0x7b, 0xc4, 0xbc, 0xaf, 0x1f, 0x60, 0xbb, 0x7b, 0xc0, 0xc4, 0xc5, 0x42, + 0xa7, 0xb8, 0x6d, 0x97, 0x9b, 0xe0, 0x06, 0x58, 0x65, 0x23, 0xdd, 0x76, 0x2c, 0x3c, 0x12, 0x8d, + 0xa0, 0x15, 0x36, 0xd2, 0xfc, 0xad, 0x82, 0xc1, 0xd2, 0x1e, 0xb1, 0x70, 0x0f, 0xde, 0x04, 0x89, + 0xfb, 0xd8, 0x13, 0x4f, 0xa8, 0xfc, 0xde, 0xd3, 0x69, 0xee, 0x6a, 0xd7, 0x66, 0x07, 0xc3, 0x76, + 0xc1, 0x24, 0xfd, 0xa2, 0x49, 0xfa, 0x98, 0xb5, 0x3b, 0x2c, 0x5c, 0xf4, 0xec, 0x36, 0x2d, 0xb6, + 0x3d, 0x86, 0x69, 0x61, 0x17, 0x8f, 0xca, 0xfe, 0x02, 0xf9, 0x04, 0xfe, 0x6d, 0x14, 0xe3, 0x3c, + 0xce, 0x1f, 0xa3, 0xd8, 0x6c, 0xff, 0x10, 0x07, 0x20, 0x9c, 0x08, 0xf0, 0x7d, 0x70, 0xae, 0x54, + 0xa9, 0xa8, 0xcd, 0xa6, 0xde, 0xda, 0x6f, 0xa8, 0xfa, 0x9d, 0x5a, 0xb3, 0xa1, 0x56, 0xb4, 0x9b, + 0x9a, 0x5a, 0x95, 0x63, 0x99, 0x8d, 0xf1, 0x24, 0x7f, 0x36, 0x0c, 0xbe, 0xe3, 0xd0, 0x01, 0x36, + 0xed, 0x8e, 0x8d, 0x2d, 0x78, 0x19, 0xc0, 0x28, 0xae, 0x56, 0x2f, 0xd7, 0xab, 0xfb, 0xb2, 0x94, + 0x59, 0x1f, 0x4f, 0xf2, 0x72, 0x08, 0xa9, 0x91, 0x36, 0xb1, 0x3c, 0xf8, 0x01, 0x48, 0x47, 0xa3, + 0xeb, 0xb5, 0x0f, 0xf7, 0xf5, 0x52, 0xb5, 0x8a, 0xd4, 0x66, 0x53, 0x8e, 0x3f, 0x9f, 0xa6, 0xee, + 0xf4, 0xbc, 0xd2, 0xb3, 0x91, 0x7d, 0x36, 0x0a, 0x54, 0x3f, 0x52, 0xd1, 0x3e, 0xcf, 0x94, 0xc8, + 0x9c, 0x1b, 0x4f, 0xf2, 0xaf, 0x85, 0x28, 0xf5, 0x10, 0xbb, 0x1e, 0x4f, 0x76, 0x03, 0x6c, 0x46, + 0x31, 0xa5, 0xda, 0xbe, 0x5e, 0xbf, 0x19, 0xa4, 0x53, 0x9b, 0x72, 0x32, 0xb3, 0x39, 0x9e, 0xe4, + 0xd3, 0x21, 0xb4, 0xe4, 0x78, 0xf5, 0x4e, 0x29, 0x18, 0xf9, 0x99, 0xd5, 0xcf, 0xbe, 0xc9, 0xc6, + 0x1e, 0x7e, 0x9b, 0x8d, 0x6d, 0x7f, 0x97, 0x00, 0xf9, 0x93, 0x6e, 0x29, 0xc4, 0xe0, 0x6a, 0xa5, + 0x5e, 0x6b, 0xa1, 0x52, 0xa5, 0xa5, 0x57, 0xea, 0x55, 0x55, 0xdf, 0xd5, 0x9a, 0xad, 0x3a, 0xda, + 0xd7, 0xeb, 0x0d, 0x15, 0x95, 0x5a, 0x5a, 0xbd, 0xf6, 0x32, 0x69, 0x8b, 0xe3, 0x49, 0xfe, 0xd2, + 0x49, 0xdc, 0x51, 0xc1, 0xef, 0x82, 0x8b, 0x0b, 0xa5, 0xd1, 0x6a, 0x5a, 0x4b, 0x96, 0x32, 0x5b, + 0xe3, 0x49, 0xfe, 0xfc, 0x49, 0xfc, 0x9a, 0x63, 0x33, 0x78, 0x0f, 0x5c, 0x5e, 0x88, 0x78, 0x4f, + 0xbb, 0x85, 0x4a, 0x2d, 0x55, 0x8e, 0x67, 0x2e, 0x8d, 0x27, 0xf9, 0x77, 0x4e, 0xe2, 0xde, 0xb3, + 0xbb, 0xae, 0xc1, 0xf0, 0xc2, 0xf4, 0xb7, 0xd4, 0x9a, 0xda, 0xd4, 0x9a, 0x72, 0x62, 0x31, 0xfa, + 0x5b, 0xd8, 0xc1, 0xd4, 0xa6, 0x99, 0xa4, 0x7f, 0x58, 0xe5, 0xdd, 0x47, 0x7f, 0x64, 0x63, 0x0f, + 0x8f, 0xb2, 0xd2, 0xa3, 0xa3, 0xac, 0xf4, 0xf8, 0x28, 0x2b, 0xfd, 0x7e, 0x94, 0x95, 0xbe, 0x78, + 0x92, 0x8d, 0x3d, 0x7e, 0x92, 0x8d, 0xfd, 0xf6, 0x24, 0x1b, 0xfb, 0xe4, 0x42, 0xe4, 0x0d, 0x55, + 0x08, 0xed, 0xdf, 0x0d, 0x7e, 0xc4, 0xac, 0xe2, 0x48, 0xfc, 0x90, 0xf1, 0xbf, 0xb1, 0xf6, 0x32, + 0x1f, 0x91, 0xef, 0xfe, 0x13, 0x00, 0x00, 0xff, 0xff, 0x69, 0x83, 0x28, 0x71, 0xae, 0x09, 0x00, + 0x00, } func (this *AccessTypeParam) Equal(that interface{}) bool { @@ -556,6 +602,7 @@ func (this *AccessTypeParam) Equal(that interface{}) bool { } return true } + func (this *AccessConfig) Equal(that interface{}) bool { if that == nil { return this == nil @@ -591,6 +638,7 @@ func (this *AccessConfig) Equal(that interface{}) bool { } return true } + func (this *Params) Equal(that interface{}) bool { if that == nil { return this == nil @@ -618,6 +666,7 @@ func (this *Params) Equal(that interface{}) bool { } return true } + func (this *CodeInfo) Equal(that interface{}) bool { if that == nil { return this == nil @@ -648,6 +697,7 @@ func (this *CodeInfo) Equal(that interface{}) bool { } return true } + func (this *ContractInfo) Equal(that interface{}) bool { if that == nil { return this == nil @@ -690,6 +740,7 @@ func (this *ContractInfo) Equal(that interface{}) bool { } return true } + func (this *ContractCodeHistoryEntry) Equal(that interface{}) bool { if that == nil { return this == nil @@ -723,6 +774,7 @@ func (this *ContractCodeHistoryEntry) Equal(that interface{}) bool { } return true } + func (this *AbsoluteTxPosition) Equal(that interface{}) bool { if that == nil { return this == nil @@ -750,6 +802,7 @@ func (this *AbsoluteTxPosition) Equal(that interface{}) bool { } return true } + func (this *Model) Equal(that interface{}) bool { if that == nil { return this == nil @@ -777,6 +830,7 @@ func (this *Model) Equal(that interface{}) bool { } return true } + func (m *AccessTypeParam) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1147,6 +1201,7 @@ func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } + func (m *AccessTypeParam) Size() (n int) { if m == nil { return 0 @@ -1308,9 +1363,11 @@ func (m *Model) Size() (n int) { 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 @@ -1380,6 +1437,7 @@ func (m *AccessTypeParam) Unmarshal(dAtA []byte) error { } return nil } + func (m *AccessConfig) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1513,6 +1571,7 @@ func (m *AccessConfig) Unmarshal(dAtA []byte) error { } return nil } + func (m *Params) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1615,6 +1674,7 @@ func (m *Params) Unmarshal(dAtA []byte) error { } return nil } + func (m *CodeInfo) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -1764,6 +1824,7 @@ func (m *CodeInfo) Unmarshal(dAtA []byte) error { } return nil } + func (m *ContractInfo) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -2033,6 +2094,7 @@ func (m *ContractInfo) Unmarshal(dAtA []byte) error { } return nil } + func (m *ContractCodeHistoryEntry) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -2191,6 +2253,7 @@ func (m *ContractCodeHistoryEntry) Unmarshal(dAtA []byte) error { } return nil } + func (m *AbsoluteTxPosition) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -2279,6 +2342,7 @@ func (m *AbsoluteTxPosition) Unmarshal(dAtA []byte) error { } return nil } + func (m *Model) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 @@ -2397,6 +2461,7 @@ func (m *Model) Unmarshal(dAtA []byte) error { } return nil } + func skipTypes(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/wasm/types/types_test.go b/x/wasm/types/types_test.go index 25df828..3221c00 100644 --- a/x/wasm/types/types_test.go +++ b/x/wasm/types/types_test.go @@ -8,14 +8,13 @@ import ( "time" wasmvmtypes "github.com/CosmWasm/wasmvm/types" + "github.com/cometbft/cometbft/libs/rand" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/codec/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/rand" ) func TestContractInfoValidateBasic(t *testing.T) { @@ -33,7 +32,7 @@ func TestContractInfoValidateBasic(t *testing.T) { expError: true, }, "creator not an address": { - srcMutator: func(c *ContractInfo) { c.Creator = "invalid address" }, + srcMutator: func(c *ContractInfo) { c.Creator = invalidAddress }, expError: true, }, "admin empty": { @@ -41,7 +40,7 @@ func TestContractInfoValidateBasic(t *testing.T) { expError: false, }, "admin not an address": { - srcMutator: func(c *ContractInfo) { c.Admin = "invalid address" }, + srcMutator: func(c *ContractInfo) { c.Admin = invalidAddress }, expError: true, }, "label empty": { @@ -55,18 +54,20 @@ func TestContractInfoValidateBasic(t *testing.T) { "invalid extension": { srcMutator: func(c *ContractInfo) { // any protobuf type with ValidateBasic method - any, err := codectypes.NewAnyWithValue(&govtypes.TextProposal{}) + codecAny, err := codectypes.NewAnyWithValue(&v1beta1.TextProposal{}) + require.NoError(t, err) - c.Extension = any + c.Extension = codecAny }, expError: true, }, "not validatable extension": { srcMutator: func(c *ContractInfo) { // any protobuf type with ValidateBasic method - any, err := codectypes.NewAnyWithValue(&govtypes.Proposal{}) + codecAny, err := codectypes.NewAnyWithValue(&v1beta1.Proposal{}) + require.NoError(t, err) - c.Extension = any + c.Extension = codecAny }, }, } @@ -102,7 +103,7 @@ func TestCodeInfoValidateBasic(t *testing.T) { expError: true, }, "creator not an address": { - srcMutator: func(c *CodeInfo) { c.Creator = "invalid address" }, + srcMutator: func(c *CodeInfo) { c.Creator = invalidAddress }, expError: true, }, "Instantiate config invalid": { @@ -127,7 +128,7 @@ 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 := govtypes.NewProposal(&govtypes.TextProposal{Title: "bar"}, 1, anyTime, anyTime) + myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "bar"}, 1, anyTime, anyTime) require.NoError(t, err) myExtension.TotalDeposit = nil return &myExtension @@ -146,10 +147,10 @@ func TestContractInfoSetExtension(t *testing.T) { expNil: true, }, "validated and accepted": { - src: &govtypes.TextProposal{Title: "bar", Description: "set"}, + src: &v1beta1.TextProposal{Title: "bar", Description: "set"}, }, "validated and rejected": { - src: &govtypes.TextProposal{Title: "bar"}, + src: &v1beta1.TextProposal{Title: "bar"}, expErr: true, }, } @@ -178,7 +179,7 @@ func TestContractInfoMarshalUnmarshal(t *testing.T) { 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 := govtypes.NewProposal(&govtypes.TextProposal{Title: "bar"}, 1, anyTime, anyTime) + myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "bar"}, 1, anyTime, anyTime) require.NoError(t, err) myExtension.TotalDeposit = nil @@ -186,16 +187,16 @@ func TestContractInfoMarshalUnmarshal(t *testing.T) { err = src.SetExtension(&myExtension) require.NoError(t, err) - interfaceRegistry := types.NewInterfaceRegistry() + interfaceRegistry := codectypes.NewInterfaceRegistry() marshaler := codec.NewProtoCodec(interfaceRegistry) RegisterInterfaces(interfaceRegistry) // register proposal as extension type interfaceRegistry.RegisterImplementations( (*ContractInfoExtension)(nil), - &govtypes.Proposal{}, + &v1beta1.Proposal{}, ) // register gov types for nested Anys - govtypes.RegisterInterfaces(interfaceRegistry) + v1beta1.RegisterInterfaces(interfaceRegistry) // when encode bz, err := marshaler.Marshal(&src) @@ -207,14 +208,14 @@ func TestContractInfoMarshalUnmarshal(t *testing.T) { require.NoError(t, err) assert.Equal(t, src, dest) // and sanity check nested any - var destExt govtypes.Proposal + 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 := govtypes.NewProposal(&govtypes.TextProposal{Title: "foo"}, 1, anyTime, anyTime) + myExtension, err := v1beta1.NewProposal(&v1beta1.TextProposal{Title: "foo"}, 1, anyTime, anyTime) require.NoError(t, err) type TestExtensionAsStruct struct { ContractInfoExtension @@ -228,10 +229,11 @@ func TestContractInfoReadExtension(t *testing.T) { }{ "all good": { setup: func(i *ContractInfo) { - i.SetExtension(&myExtension) + err = i.SetExtension(&myExtension) + require.NoError(t, err) }, param: func() ContractInfoExtension { - return &govtypes.Proposal{} + return &v1beta1.Proposal{} }, expVal: &myExtension, }, @@ -239,13 +241,14 @@ func TestContractInfoReadExtension(t *testing.T) { setup: func(i *ContractInfo) { }, param: func() ContractInfoExtension { - return &govtypes.Proposal{} + return &v1beta1.Proposal{} }, - expVal: &govtypes.Proposal{}, + expVal: &v1beta1.Proposal{}, }, "nil argument value": { setup: func(i *ContractInfo) { - i.SetExtension(&myExtension) + err = i.SetExtension(&myExtension) + require.NoError(t, err) }, param: func() ContractInfoExtension { return nil @@ -254,10 +257,11 @@ func TestContractInfoReadExtension(t *testing.T) { }, "non matching types": { setup: func(i *ContractInfo) { - i.SetExtension(&myExtension) + err = i.SetExtension(&myExtension) + require.NoError(t, err) }, param: func() ContractInfoExtension { - return &govtypes.TextProposal{} + return &v1beta1.TextProposal{} }, expErr: true, }, diff --git a/x/wasm/types/validation.go b/x/wasm/types/validation.go index 526a6bf..d3e678b 100644 --- a/x/wasm/types/validation.go +++ b/x/wasm/types/validation.go @@ -4,7 +4,7 @@ import ( "fmt" "net/url" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + errorsmod "cosmossdk.io/errors" "github.com/docker/distribution/reference" ) @@ -24,10 +24,10 @@ var ( func validateWasmCode(s []byte, maxSize int) error { if len(s) == 0 { - return sdkerrors.Wrap(ErrEmpty, "is required") + return errorsmod.Wrap(ErrEmpty, "is required") } if len(s) > maxSize { - return sdkerrors.Wrapf(ErrLimit, "cannot be longer than %d bytes", maxSize) + return errorsmod.Wrapf(ErrLimit, "cannot be longer than %d bytes", maxSize) } return nil } @@ -35,7 +35,7 @@ func validateWasmCode(s []byte, maxSize int) error { // ValidateLabel ensure label constraints func ValidateLabel(label string) error { if label == "" { - return sdkerrors.Wrap(ErrEmpty, "is required") + return errorsmod.Wrap(ErrEmpty, "is required") } if len(label) > MaxLabelSize { return ErrLimit.Wrapf("cannot be longer than %d characters", MaxLabelSize) @@ -47,7 +47,7 @@ func ValidateLabel(label string) error { func ValidateSalt(salt []byte) error { switch n := len(salt); { case n == 0: - return sdkerrors.Wrap(ErrEmpty, "is required") + return errorsmod.Wrap(ErrEmpty, "is required") case n > MaxSaltSize: return ErrLimit.Wrapf("cannot be longer than %d characters", MaxSaltSize) } diff --git a/x/wasm/types/wasmer_engine.go b/x/wasm/types/wasmer_engine.go index 9b3cf71..9b2efde 100644 --- a/x/wasm/types/wasmer_engine.go +++ b/x/wasm/types/wasmer_engine.go @@ -3,6 +3,7 @@ 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 @@ -140,7 +141,7 @@ type WasmerEngine interface { Cleanup() // IBCChannelOpen is available on IBC-enabled contracts and is a hook to call into - // during the handshake pahse + // during the handshake phase IBCChannelOpen( checksum wasmvm.Checksum, env wasmvmtypes.Env, @@ -154,7 +155,7 @@ type WasmerEngine interface { ) (*wasmvmtypes.IBC3ChannelOpenResponse, uint64, error) // IBCChannelConnect is available on IBC-enabled contracts and is a hook to call into - // during the handshake pahse + // during the handshake phase IBCChannelConnect( checksum wasmvm.Checksum, env wasmvmtypes.Env, @@ -211,7 +212,7 @@ type WasmerEngine interface { ) (*wasmvmtypes.IBCBasicResponse, uint64, error) // IBCPacketTimeout is available on IBC-enabled contracts and is called when an - // outgoing packet (previously sent by this contract) will provably never be executed. + // outgoing packet (previously sent by this contract) will probably never be executed. // Usually handled like ack returning an error IBCPacketTimeout( checksum wasmvm.Checksum, @@ -239,3 +240,38 @@ type WasmerEngine interface { // 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) +}